Bug Summary

File:clang/lib/CodeGen/CGBlocks.cpp
Warning:line 598, column 19
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGBlocks.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.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-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/llvm/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/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp

1//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit blocks.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBlocks.h"
14#include "CGCXXABI.h"
15#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CGOpenCLRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "ConstantEmitter.h"
21#include "TargetInfo.h"
22#include "clang/AST/Attr.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/CodeGen/ConstantInitBuilder.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Support/ScopedPrinter.h"
29#include <algorithm>
30#include <cstdio>
31
32using namespace clang;
33using namespace CodeGen;
34
35CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
38 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
39 StructureType(nullptr), Block(block) {
40
41 // Skip asm prefix, if any. 'name' is usually taken directly from
42 // the mangled name of the enclosing function.
43 if (!name.empty() && name[0] == '\01')
44 name = name.substr(1);
45}
46
47// Anchor the vtable to this translation unit.
48BlockByrefHelpers::~BlockByrefHelpers() {}
49
50/// Build the given block as a global block.
51static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo,
53 llvm::Constant *blockFn);
54
55/// Build the helper function to copy a block.
56static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
57 const CGBlockInfo &blockInfo) {
58 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
59}
60
61/// Build the helper function to dispose of a block.
62static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
63 const CGBlockInfo &blockInfo) {
64 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
65}
66
67namespace {
68
69/// Represents a type of copy/destroy operation that should be performed for an
70/// entity that's captured by a block.
71enum class BlockCaptureEntityKind {
72 CXXRecord, // Copy or destroy
73 ARCWeak,
74 ARCStrong,
75 NonTrivialCStruct,
76 BlockObject, // Assign or release
77 None
78};
79
80/// Represents a captured entity that requires extra operations in order for
81/// this entity to be copied or destroyed correctly.
82struct BlockCaptureManagedEntity {
83 BlockCaptureEntityKind CopyKind, DisposeKind;
84 BlockFieldFlags CopyFlags, DisposeFlags;
85 const BlockDecl::Capture *CI;
86 const CGBlockInfo::Capture *Capture;
87
88 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
89 BlockCaptureEntityKind DisposeType,
90 BlockFieldFlags CopyFlags,
91 BlockFieldFlags DisposeFlags,
92 const BlockDecl::Capture &CI,
93 const CGBlockInfo::Capture &Capture)
94 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
95 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
96
97 bool operator<(const BlockCaptureManagedEntity &Other) const {
98 return Capture->getOffset() < Other.Capture->getOffset();
99 }
100};
101
102enum class CaptureStrKind {
103 // String for the copy helper.
104 CopyHelper,
105 // String for the dispose helper.
106 DisposeHelper,
107 // Merge the strings for the copy helper and dispose helper.
108 Merged
109};
110
111} // end anonymous namespace
112
113static void findBlockCapturedManagedEntities(
114 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
115 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
116
117static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
118 CaptureStrKind StrKind,
119 CharUnits BlockAlignment,
120 CodeGenModule &CGM);
121
122static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
123 CodeGenModule &CGM) {
124 std::string Name = "__block_descriptor_";
125 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
126
127 if (BlockInfo.needsCopyDisposeHelpers()) {
128 if (CGM.getLangOpts().Exceptions)
129 Name += "e";
130 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
131 Name += "a";
132 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
133
134 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
135 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
136 ManagedCaptures);
137
138 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
139 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
140
141 if (E.CopyKind == E.DisposeKind) {
142 // If CopyKind and DisposeKind are the same, merge the capture
143 // information.
144 assert(E.CopyKind != BlockCaptureEntityKind::None &&((E.CopyKind != BlockCaptureEntityKind::None && "shouldn't see BlockCaptureManagedEntity that is None"
) ? static_cast<void> (0) : __assert_fail ("E.CopyKind != BlockCaptureEntityKind::None && \"shouldn't see BlockCaptureManagedEntity that is None\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 145, __PRETTY_FUNCTION__))
145 "shouldn't see BlockCaptureManagedEntity that is None")((E.CopyKind != BlockCaptureEntityKind::None && "shouldn't see BlockCaptureManagedEntity that is None"
) ? static_cast<void> (0) : __assert_fail ("E.CopyKind != BlockCaptureEntityKind::None && \"shouldn't see BlockCaptureManagedEntity that is None\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 145, __PRETTY_FUNCTION__))
;
146 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
147 BlockInfo.BlockAlign, CGM);
148 } else {
149 // If CopyKind and DisposeKind are not the same, which can happen when
150 // either Kind is None or the captured object is a __strong block,
151 // concatenate the copy and dispose strings.
152 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
153 BlockInfo.BlockAlign, CGM);
154 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
155 BlockInfo.BlockAlign, CGM);
156 }
157 }
158 Name += "_";
159 }
160
161 std::string TypeAtEncoding =
162 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
163 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
164 /// a separator between symbol name and symbol version.
165 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
166 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
167 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
168 return Name;
169}
170
171/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
172/// buildBlockDescriptor is accessed from 5th field of the Block_literal
173/// meta-data and contains stationary information about the block literal.
174/// Its definition will have 4 (or optionally 6) words.
175/// \code
176/// struct Block_descriptor {
177/// unsigned long reserved;
178/// unsigned long size; // size of Block_literal metadata in bytes.
179/// void *copy_func_helper_decl; // optional copy helper.
180/// void *destroy_func_decl; // optional destructor helper.
181/// void *block_method_encoding_address; // @encode for block literal signature.
182/// void *block_layout_info; // encoding of captured block variables.
183/// };
184/// \endcode
185static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
186 const CGBlockInfo &blockInfo) {
187 ASTContext &C = CGM.getContext();
188
189 llvm::IntegerType *ulong =
190 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
191 llvm::PointerType *i8p = nullptr;
192 if (CGM.getLangOpts().OpenCL)
193 i8p =
194 llvm::Type::getInt8PtrTy(
195 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
196 else
197 i8p = CGM.VoidPtrTy;
198
199 std::string descName;
200
201 // If an equivalent block descriptor global variable exists, return it.
202 if (C.getLangOpts().ObjC &&
203 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
204 descName = getBlockDescriptorName(blockInfo, CGM);
205 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
206 return llvm::ConstantExpr::getBitCast(desc,
207 CGM.getBlockDescriptorType());
208 }
209
210 // If there isn't an equivalent block descriptor global variable, create a new
211 // one.
212 ConstantInitBuilder builder(CGM);
213 auto elements = builder.beginStruct();
214
215 // reserved
216 elements.addInt(ulong, 0);
217
218 // Size
219 // FIXME: What is the right way to say this doesn't fit? We should give
220 // a user diagnostic in that case. Better fix would be to change the
221 // API to size_t.
222 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
223
224 // Optional copy/dispose helpers.
225 bool hasInternalHelper = false;
226 if (blockInfo.needsCopyDisposeHelpers()) {
227 // copy_func_helper_decl
228 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
229 elements.add(copyHelper);
230
231 // destroy_func_decl
232 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
233 elements.add(disposeHelper);
234
235 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
236 cast<llvm::Function>(disposeHelper->getOperand(0))
237 ->hasInternalLinkage())
238 hasInternalHelper = true;
239 }
240
241 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
242 std::string typeAtEncoding =
243 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
244 elements.add(llvm::ConstantExpr::getBitCast(
245 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
246
247 // GC layout.
248 if (C.getLangOpts().ObjC) {
249 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
250 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
251 else
252 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
253 }
254 else
255 elements.addNullPointer(i8p);
256
257 unsigned AddrSpace = 0;
258 if (C.getLangOpts().OpenCL)
259 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
260
261 llvm::GlobalValue::LinkageTypes linkage;
262 if (descName.empty()) {
263 linkage = llvm::GlobalValue::InternalLinkage;
264 descName = "__block_descriptor_tmp";
265 } else if (hasInternalHelper) {
266 // If either the copy helper or the dispose helper has internal linkage,
267 // the block descriptor must have internal linkage too.
268 linkage = llvm::GlobalValue::InternalLinkage;
269 } else {
270 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
271 }
272
273 llvm::GlobalVariable *global =
274 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
275 /*constant*/ true, linkage, AddrSpace);
276
277 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
278 if (CGM.supportsCOMDAT())
279 global->setComdat(CGM.getModule().getOrInsertComdat(descName));
280 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
281 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
282 }
283
284 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
285}
286
287/*
288 Purely notional variadic template describing the layout of a block.
289
290 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
291 struct Block_literal {
292 /// Initialized to one of:
293 /// extern void *_NSConcreteStackBlock[];
294 /// extern void *_NSConcreteGlobalBlock[];
295 ///
296 /// In theory, we could start one off malloc'ed by setting
297 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
298 /// this isa:
299 /// extern void *_NSConcreteMallocBlock[];
300 struct objc_class *isa;
301
302 /// These are the flags (with corresponding bit number) that the
303 /// compiler is actually supposed to know about.
304 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
305 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
306 /// descriptor provides copy and dispose helper functions
307 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
308 /// object with a nontrivial destructor or copy constructor
309 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
310 /// as global memory
311 /// 29. BLOCK_USE_STRET - indicates that the block function
312 /// uses stret, which objc_msgSend needs to know about
313 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
314 /// @encoded signature string
315 /// And we're not supposed to manipulate these:
316 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
317 /// to malloc'ed memory
318 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
319 /// to GC-allocated memory
320 /// Additionally, the bottom 16 bits are a reference count which
321 /// should be zero on the stack.
322 int flags;
323
324 /// Reserved; should be zero-initialized.
325 int reserved;
326
327 /// Function pointer generated from block literal.
328 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
329
330 /// Block description metadata generated from block literal.
331 struct Block_descriptor *block_descriptor;
332
333 /// Captured values follow.
334 _CapturesTypes captures...;
335 };
336 */
337
338namespace {
339 /// A chunk of data that we actually have to capture in the block.
340 struct BlockLayoutChunk {
341 CharUnits Alignment;
342 CharUnits Size;
343 Qualifiers::ObjCLifetime Lifetime;
344 const BlockDecl::Capture *Capture; // null for 'this'
345 llvm::Type *Type;
346 QualType FieldType;
347
348 BlockLayoutChunk(CharUnits align, CharUnits size,
349 Qualifiers::ObjCLifetime lifetime,
350 const BlockDecl::Capture *capture,
351 llvm::Type *type, QualType fieldType)
352 : Alignment(align), Size(size), Lifetime(lifetime),
353 Capture(capture), Type(type), FieldType(fieldType) {}
354
355 /// Tell the block info that this chunk has the given field index.
356 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
357 if (!Capture) {
358 info.CXXThisIndex = index;
359 info.CXXThisOffset = offset;
360 } else {
361 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
362 info.Captures.insert({Capture->getVariable(), C});
363 }
364 }
365 };
366
367 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
368 /// all __weak together. Preserve descending alignment in all situations.
369 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
370 if (left.Alignment != right.Alignment)
371 return left.Alignment > right.Alignment;
372
373 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
374 if (chunk.Capture && chunk.Capture->isByRef())
375 return 1;
376 if (chunk.Lifetime == Qualifiers::OCL_Strong)
377 return 0;
378 if (chunk.Lifetime == Qualifiers::OCL_Weak)
379 return 2;
380 return 3;
381 };
382
383 return getPrefOrder(left) < getPrefOrder(right);
384 }
385} // end anonymous namespace
386
387/// Determines if the given type is safe for constant capture in C++.
388static bool isSafeForCXXConstantCapture(QualType type) {
389 const RecordType *recordType =
390 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
391
392 // Only records can be unsafe.
393 if (!recordType) return true;
394
395 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
396
397 // Maintain semantics for classes with non-trivial dtors or copy ctors.
398 if (!record->hasTrivialDestructor()) return false;
399 if (record->hasNonTrivialCopyConstructor()) return false;
400
401 // Otherwise, we just have to make sure there aren't any mutable
402 // fields that might have changed since initialization.
403 return !record->hasMutableFields();
404}
405
406/// It is illegal to modify a const object after initialization.
407/// Therefore, if a const object has a constant initializer, we don't
408/// actually need to keep storage for it in the block; we'll just
409/// rematerialize it at the start of the block function. This is
410/// acceptable because we make no promises about address stability of
411/// captured variables.
412static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
413 CodeGenFunction *CGF,
414 const VarDecl *var) {
415 // Return if this is a function parameter. We shouldn't try to
416 // rematerialize default arguments of function parameters.
417 if (isa<ParmVarDecl>(var))
18
Assuming 'var' is a 'ParmVarDecl'
19
Taking true branch
418 return nullptr;
20
Returning null pointer, which participates in a condition later
419
420 QualType type = var->getType();
421
422 // We can only do this if the variable is const.
423 if (!type.isConstQualified()) return nullptr;
424
425 // Furthermore, in C++ we have to worry about mutable fields:
426 // C++ [dcl.type.cv]p4:
427 // Except that any class member declared mutable can be
428 // modified, any attempt to modify a const object during its
429 // lifetime results in undefined behavior.
430 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
431 return nullptr;
432
433 // If the variable doesn't have any initializer (shouldn't this be
434 // invalid?), it's not clear what we should do. Maybe capture as
435 // zero?
436 const Expr *init = var->getInit();
437 if (!init) return nullptr;
438
439 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
440}
441
442/// Get the low bit of a nonzero character count. This is the
443/// alignment of the nth byte if the 0th byte is universally aligned.
444static CharUnits getLowBit(CharUnits v) {
445 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
446}
447
448static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
449 SmallVectorImpl<llvm::Type*> &elementTypes) {
450
451 assert(elementTypes.empty())((elementTypes.empty()) ? static_cast<void> (0) : __assert_fail
("elementTypes.empty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 451, __PRETTY_FUNCTION__))
;
452 if (CGM.getLangOpts().OpenCL) {
453 // The header is basically 'struct { int; int; generic void *;
454 // custom_fields; }'. Assert that struct is packed.
455 auto GenericAS =
456 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
457 auto GenPtrAlign =
458 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
459 auto GenPtrSize =
460 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
461 assert(CGM.getIntSize() <= GenPtrSize)((CGM.getIntSize() <= GenPtrSize) ? static_cast<void>
(0) : __assert_fail ("CGM.getIntSize() <= GenPtrSize", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 461, __PRETTY_FUNCTION__))
;
462 assert(CGM.getIntAlign() <= GenPtrAlign)((CGM.getIntAlign() <= GenPtrAlign) ? static_cast<void>
(0) : __assert_fail ("CGM.getIntAlign() <= GenPtrAlign", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 462, __PRETTY_FUNCTION__))
;
463 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign))(((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign)) ? static_cast
<void> (0) : __assert_fail ("(2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 463, __PRETTY_FUNCTION__))
;
464 elementTypes.push_back(CGM.IntTy); /* total size */
465 elementTypes.push_back(CGM.IntTy); /* align */
466 elementTypes.push_back(
467 CGM.getOpenCLRuntime()
468 .getGenericVoidPointerType()); /* invoke function */
469 unsigned Offset =
470 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
471 unsigned BlockAlign = GenPtrAlign.getQuantity();
472 if (auto *Helper =
473 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
474 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
475 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
476 // If necessary, add padding fields to the custom fields.
477 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
478 if (BlockAlign < Align)
479 BlockAlign = Align;
480 assert(Offset % Align == 0)((Offset % Align == 0) ? static_cast<void> (0) : __assert_fail
("Offset % Align == 0", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 480, __PRETTY_FUNCTION__))
;
481 Offset += CGM.getDataLayout().getTypeAllocSize(I);
482 elementTypes.push_back(I);
483 }
484 }
485 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
486 info.BlockSize = CharUnits::fromQuantity(Offset);
487 } else {
488 // The header is basically 'struct { void *; int; int; void *; void *; }'.
489 // Assert that the struct is packed.
490 assert(CGM.getIntSize() <= CGM.getPointerSize())((CGM.getIntSize() <= CGM.getPointerSize()) ? static_cast<
void> (0) : __assert_fail ("CGM.getIntSize() <= CGM.getPointerSize()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 490, __PRETTY_FUNCTION__))
;
491 assert(CGM.getIntAlign() <= CGM.getPointerAlign())((CGM.getIntAlign() <= CGM.getPointerAlign()) ? static_cast
<void> (0) : __assert_fail ("CGM.getIntAlign() <= CGM.getPointerAlign()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 491, __PRETTY_FUNCTION__))
;
492 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()))(((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()))
? static_cast<void> (0) : __assert_fail ("(2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign())"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 492, __PRETTY_FUNCTION__))
;
493 info.BlockAlign = CGM.getPointerAlign();
494 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
495 elementTypes.push_back(CGM.VoidPtrTy);
496 elementTypes.push_back(CGM.IntTy);
497 elementTypes.push_back(CGM.IntTy);
498 elementTypes.push_back(CGM.VoidPtrTy);
499 elementTypes.push_back(CGM.getBlockDescriptorType());
500 }
501}
502
503static QualType getCaptureFieldType(const CodeGenFunction &CGF,
504 const BlockDecl::Capture &CI) {
505 const VarDecl *VD = CI.getVariable();
506
507 // If the variable is captured by an enclosing block or lambda expression,
508 // use the type of the capture field.
509 if (CGF.BlockInfo && CI.isNested())
510 return CGF.BlockInfo->getCapture(VD).fieldType();
511 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
512 return FD->getType();
513 // If the captured variable is a non-escaping __block variable, the field
514 // type is the reference type. If the variable is a __block variable that
515 // already has a reference type, the field type is the variable's type.
516 return VD->isNonEscapingByref() ?
517 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
518}
519
520/// Compute the layout of the given block. Attempts to lay the block
521/// out with minimal space requirements.
522static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
523 CGBlockInfo &info) {
524 ASTContext &C = CGM.getContext();
525 const BlockDecl *block = info.getBlockDecl();
526
527 SmallVector<llvm::Type*, 8> elementTypes;
528 initializeForBlockHeader(CGM, info, elementTypes);
529 bool hasNonConstantCustomFields = false;
530 if (auto *OpenCLHelper =
5
Assuming 'OpenCLHelper' is null
6
Taking false branch
531 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
532 hasNonConstantCustomFields =
533 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
534 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
7
Calling 'BlockDecl::hasCaptures'
10
Returning from 'BlockDecl::hasCaptures'
535 info.StructureType =
536 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
537 info.CanBeGlobal = true;
538 return;
539 }
540 else if (C.getLangOpts().ObjC &&
11
Assuming field 'ObjC' is 0
541 CGM.getLangOpts().getGC() == LangOptions::NonGC)
542 info.HasCapturedVariableLayout = true;
543
544 // Collect the layout chunks.
545 SmallVector<BlockLayoutChunk, 16> layout;
546 layout.reserve(block->capturesCXXThis() +
547 (block->capture_end() - block->capture_begin()));
548
549 CharUnits maxFieldAlign;
550
551 // First, 'this'.
552 if (block->capturesCXXThis()) {
12
Assuming the condition is false
13
Taking false branch
553 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&((CGF && CGF->CurFuncDecl && isa<CXXMethodDecl
>(CGF->CurFuncDecl) && "Can't capture 'this' outside a method"
) ? static_cast<void> (0) : __assert_fail ("CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) && \"Can't capture 'this' outside a method\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 554, __PRETTY_FUNCTION__))
554 "Can't capture 'this' outside a method")((CGF && CGF->CurFuncDecl && isa<CXXMethodDecl
>(CGF->CurFuncDecl) && "Can't capture 'this' outside a method"
) ? static_cast<void> (0) : __assert_fail ("CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) && \"Can't capture 'this' outside a method\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 554, __PRETTY_FUNCTION__))
;
555 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
556
557 // Theoretically, this could be in a different address space, so
558 // don't assume standard pointer size/align.
559 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
560 std::pair<CharUnits,CharUnits> tinfo
561 = CGM.getContext().getTypeInfoInChars(thisType);
562 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
563
564 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
565 Qualifiers::OCL_None,
566 nullptr, llvmType, thisType));
567 }
568
569 // Next, all the block captures.
570 for (const auto &CI : block->captures()) {
14
Assuming '__begin1' is not equal to '__end1'
571 const VarDecl *variable = CI.getVariable();
572
573 if (CI.isEscapingByref()) {
15
Assuming the condition is false
16
Taking false branch
574 // We have to copy/dispose of the __block reference.
575 info.NeedsCopyDispose = true;
576
577 // Just use void* instead of a pointer to the byref type.
578 CharUnits align = CGM.getPointerAlign();
579 maxFieldAlign = std::max(maxFieldAlign, align);
580
581 // Since a __block variable cannot be captured by lambdas, its type and
582 // the capture field type should always match.
583 assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&((CGF && getCaptureFieldType(*CGF, CI) == variable->
getType() && "capture type differs from the variable type"
) ? static_cast<void> (0) : __assert_fail ("CGF && getCaptureFieldType(*CGF, CI) == variable->getType() && \"capture type differs from the variable type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 584, __PRETTY_FUNCTION__))
584 "capture type differs from the variable type")((CGF && getCaptureFieldType(*CGF, CI) == variable->
getType() && "capture type differs from the variable type"
) ? static_cast<void> (0) : __assert_fail ("CGF && getCaptureFieldType(*CGF, CI) == variable->getType() && \"capture type differs from the variable type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 584, __PRETTY_FUNCTION__))
;
585 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
586 Qualifiers::OCL_None, &CI,
587 CGM.VoidPtrTy, variable->getType()));
588 continue;
589 }
590
591 // Otherwise, build a layout chunk with the size and alignment of
592 // the declaration.
593 if (llvm::Constant *constant
21.1
'constant' is null
21.1
'constant' is null
= tryCaptureAsConstant(CGM, CGF, variable)) {
17
Calling 'tryCaptureAsConstant'
21
Returning from 'tryCaptureAsConstant'
22
Taking false branch
594 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
595 continue;
596 }
597
598 QualType VT = getCaptureFieldType(*CGF, CI);
23
Forming reference to null pointer
599
600 // If we have a lifetime qualifier, honor it for capture purposes.
601 // That includes *not* copying it if it's __unsafe_unretained.
602 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
603 if (lifetime) {
604 switch (lifetime) {
605 case Qualifiers::OCL_None: llvm_unreachable("impossible")::llvm::llvm_unreachable_internal("impossible", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 605)
;
606 case Qualifiers::OCL_ExplicitNone:
607 case Qualifiers::OCL_Autoreleasing:
608 break;
609
610 case Qualifiers::OCL_Strong:
611 case Qualifiers::OCL_Weak:
612 info.NeedsCopyDispose = true;
613 }
614
615 // Block pointers require copy/dispose. So do Objective-C pointers.
616 } else if (VT->isObjCRetainableType()) {
617 // But honor the inert __unsafe_unretained qualifier, which doesn't
618 // actually make it into the type system.
619 if (VT->isObjCInertUnsafeUnretainedType()) {
620 lifetime = Qualifiers::OCL_ExplicitNone;
621 } else {
622 info.NeedsCopyDispose = true;
623 // used for mrr below.
624 lifetime = Qualifiers::OCL_Strong;
625 }
626
627 // So do types that require non-trivial copy construction.
628 } else if (CI.hasCopyExpr()) {
629 info.NeedsCopyDispose = true;
630 info.HasCXXObject = true;
631 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
632 info.CapturesNonExternalType = true;
633
634 // So do C structs that require non-trivial copy construction or
635 // destruction.
636 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
637 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
638 info.NeedsCopyDispose = true;
639
640 // And so do types with destructors.
641 } else if (CGM.getLangOpts().CPlusPlus) {
642 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
643 if (!record->hasTrivialDestructor()) {
644 info.HasCXXObject = true;
645 info.NeedsCopyDispose = true;
646 if (!record->isExternallyVisible())
647 info.CapturesNonExternalType = true;
648 }
649 }
650 }
651
652 CharUnits size = C.getTypeSizeInChars(VT);
653 CharUnits align = C.getDeclAlign(variable);
654
655 maxFieldAlign = std::max(maxFieldAlign, align);
656
657 llvm::Type *llvmType =
658 CGM.getTypes().ConvertTypeForMem(VT);
659
660 layout.push_back(
661 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
662 }
663
664 // If that was everything, we're done here.
665 if (layout.empty()) {
666 info.StructureType =
667 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
668 info.CanBeGlobal = true;
669 return;
670 }
671
672 // Sort the layout by alignment. We have to use a stable sort here
673 // to get reproducible results. There should probably be an
674 // llvm::array_pod_stable_sort.
675 llvm::stable_sort(layout);
676
677 // Needed for blocks layout info.
678 info.BlockHeaderForcedGapOffset = info.BlockSize;
679 info.BlockHeaderForcedGapSize = CharUnits::Zero();
680
681 CharUnits &blockSize = info.BlockSize;
682 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
683
684 // Assuming that the first byte in the header is maximally aligned,
685 // get the alignment of the first byte following the header.
686 CharUnits endAlign = getLowBit(blockSize);
687
688 // If the end of the header isn't satisfactorily aligned for the
689 // maximum thing, look for things that are okay with the header-end
690 // alignment, and keep appending them until we get something that's
691 // aligned right. This algorithm is only guaranteed optimal if
692 // that condition is satisfied at some point; otherwise we can get
693 // things like:
694 // header // next byte has alignment 4
695 // something_with_size_5; // next byte has alignment 1
696 // something_with_alignment_8;
697 // which has 7 bytes of padding, as opposed to the naive solution
698 // which might have less (?).
699 if (endAlign < maxFieldAlign) {
700 SmallVectorImpl<BlockLayoutChunk>::iterator
701 li = layout.begin() + 1, le = layout.end();
702
703 // Look for something that the header end is already
704 // satisfactorily aligned for.
705 for (; li != le && endAlign < li->Alignment; ++li)
706 ;
707
708 // If we found something that's naturally aligned for the end of
709 // the header, keep adding things...
710 if (li != le) {
711 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
712 for (; li != le; ++li) {
713 assert(endAlign >= li->Alignment)((endAlign >= li->Alignment) ? static_cast<void> (
0) : __assert_fail ("endAlign >= li->Alignment", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 713, __PRETTY_FUNCTION__))
;
714
715 li->setIndex(info, elementTypes.size(), blockSize);
716 elementTypes.push_back(li->Type);
717 blockSize += li->Size;
718 endAlign = getLowBit(blockSize);
719
720 // ...until we get to the alignment of the maximum field.
721 if (endAlign >= maxFieldAlign) {
722 break;
723 }
724 }
725 // Don't re-append everything we just appended.
726 layout.erase(first, li);
727 }
728 }
729
730 assert(endAlign == getLowBit(blockSize))((endAlign == getLowBit(blockSize)) ? static_cast<void>
(0) : __assert_fail ("endAlign == getLowBit(blockSize)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 730, __PRETTY_FUNCTION__))
;
731
732 // At this point, we just have to add padding if the end align still
733 // isn't aligned right.
734 if (endAlign < maxFieldAlign) {
735 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
736 CharUnits padding = newBlockSize - blockSize;
737
738 // If we haven't yet added any fields, remember that there was an
739 // initial gap; this need to go into the block layout bit map.
740 if (blockSize == info.BlockHeaderForcedGapOffset) {
741 info.BlockHeaderForcedGapSize = padding;
742 }
743
744 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
745 padding.getQuantity()));
746 blockSize = newBlockSize;
747 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
748 }
749
750 assert(endAlign >= maxFieldAlign)((endAlign >= maxFieldAlign) ? static_cast<void> (0)
: __assert_fail ("endAlign >= maxFieldAlign", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 750, __PRETTY_FUNCTION__))
;
751 assert(endAlign == getLowBit(blockSize))((endAlign == getLowBit(blockSize)) ? static_cast<void>
(0) : __assert_fail ("endAlign == getLowBit(blockSize)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 751, __PRETTY_FUNCTION__))
;
752 // Slam everything else on now. This works because they have
753 // strictly decreasing alignment and we expect that size is always a
754 // multiple of alignment.
755 for (SmallVectorImpl<BlockLayoutChunk>::iterator
756 li = layout.begin(), le = layout.end(); li != le; ++li) {
757 if (endAlign < li->Alignment) {
758 // size may not be multiple of alignment. This can only happen with
759 // an over-aligned variable. We will be adding a padding field to
760 // make the size be multiple of alignment.
761 CharUnits padding = li->Alignment - endAlign;
762 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
763 padding.getQuantity()));
764 blockSize += padding;
765 endAlign = getLowBit(blockSize);
766 }
767 assert(endAlign >= li->Alignment)((endAlign >= li->Alignment) ? static_cast<void> (
0) : __assert_fail ("endAlign >= li->Alignment", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 767, __PRETTY_FUNCTION__))
;
768 li->setIndex(info, elementTypes.size(), blockSize);
769 elementTypes.push_back(li->Type);
770 blockSize += li->Size;
771 endAlign = getLowBit(blockSize);
772 }
773
774 info.StructureType =
775 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
776}
777
778/// Emit a block literal expression in the current function.
779llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
780 // If the block has no captures, we won't have a pre-computed
781 // layout for it.
782 if (!blockExpr->getBlockDecl()->hasCaptures())
783 // The block literal is emitted as a global variable, and the block invoke
784 // function has to be extracted from its initializer.
785 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
786 return Block;
787
788 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
789 computeBlockInfo(CGM, this, blockInfo);
790 blockInfo.BlockExpression = blockExpr;
791 if (!blockInfo.CanBeGlobal)
792 blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
793 blockInfo.BlockAlign, "block");
794 return EmitBlockLiteral(blockInfo);
795}
796
797llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
798 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
799 auto GenVoidPtrTy =
800 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
801 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
802 auto GenVoidPtrSize = CharUnits::fromQuantity(
803 CGM.getTarget().getPointerWidth(
804 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
805 8);
806 // Using the computed layout, generate the actual block function.
807 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
808 CodeGenFunction BlockCGF{CGM, true};
809 BlockCGF.SanOpts = SanOpts;
810 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
811 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
812 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
813
814 // If there is nothing to capture, we can emit this as a global block.
815 if (blockInfo.CanBeGlobal)
816 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
817
818 // Otherwise, we have to emit this as a local block.
819
820 Address blockAddr = blockInfo.LocalAddress;
821 assert(blockAddr.isValid() && "block has no address!")((blockAddr.isValid() && "block has no address!") ? static_cast
<void> (0) : __assert_fail ("blockAddr.isValid() && \"block has no address!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 821, __PRETTY_FUNCTION__))
;
822
823 llvm::Constant *isa;
824 llvm::Constant *descriptor;
825 BlockFlags flags;
826 if (!IsOpenCL) {
827 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
828 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
829 // block just returns the original block and releasing it is a no-op.
830 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
831 ? CGM.getNSConcreteGlobalBlock()
832 : CGM.getNSConcreteStackBlock();
833 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
834
835 // Build the block descriptor.
836 descriptor = buildBlockDescriptor(CGM, blockInfo);
837
838 // Compute the initial on-stack block flags.
839 flags = BLOCK_HAS_SIGNATURE;
840 if (blockInfo.HasCapturedVariableLayout)
841 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
842 if (blockInfo.needsCopyDisposeHelpers())
843 flags |= BLOCK_HAS_COPY_DISPOSE;
844 if (blockInfo.HasCXXObject)
845 flags |= BLOCK_HAS_CXX_OBJ;
846 if (blockInfo.UsesStret)
847 flags |= BLOCK_USE_STRET;
848 if (blockInfo.getBlockDecl()->doesNotEscape())
849 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
850 }
851
852 auto projectField = [&](unsigned index, const Twine &name) -> Address {
853 return Builder.CreateStructGEP(blockAddr, index, name);
854 };
855 auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
856 Builder.CreateStore(value, projectField(index, name));
857 };
858
859 // Initialize the block header.
860 {
861 // We assume all the header fields are densely packed.
862 unsigned index = 0;
863 CharUnits offset;
864 auto addHeaderField = [&](llvm::Value *value, CharUnits size,
865 const Twine &name) {
866 storeField(value, index, name);
867 offset += size;
868 index++;
869 };
870
871 if (!IsOpenCL) {
872 addHeaderField(isa, getPointerSize(), "block.isa");
873 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
874 getIntSize(), "block.flags");
875 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
876 "block.reserved");
877 } else {
878 addHeaderField(
879 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
880 getIntSize(), "block.size");
881 addHeaderField(
882 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
883 getIntSize(), "block.align");
884 }
885 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
886 if (!IsOpenCL)
887 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
888 else if (auto *Helper =
889 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
890 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
891 addHeaderField(
892 I.first,
893 CharUnits::fromQuantity(
894 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
895 I.second);
896 }
897 }
898 }
899
900 // Finally, capture all the values into the block.
901 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
902
903 // First, 'this'.
904 if (blockDecl->capturesCXXThis()) {
905 Address addr =
906 projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
907 Builder.CreateStore(LoadCXXThis(), addr);
908 }
909
910 // Next, captured variables.
911 for (const auto &CI : blockDecl->captures()) {
912 const VarDecl *variable = CI.getVariable();
913 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
914
915 // Ignore constant captures.
916 if (capture.isConstant()) continue;
917
918 QualType type = capture.fieldType();
919
920 // This will be a [[type]]*, except that a byref entry will just be
921 // an i8**.
922 Address blockField = projectField(capture.getIndex(), "block.captured");
923
924 // Compute the address of the thing we're going to move into the
925 // block literal.
926 Address src = Address::invalid();
927
928 if (blockDecl->isConversionFromLambda()) {
929 // The lambda capture in a lambda's conversion-to-block-pointer is
930 // special; we'll simply emit it directly.
931 src = Address::invalid();
932 } else if (CI.isEscapingByref()) {
933 if (BlockInfo && CI.isNested()) {
934 // We need to use the capture from the enclosing block.
935 const CGBlockInfo::Capture &enclosingCapture =
936 BlockInfo->getCapture(variable);
937
938 // This is a [[type]]*, except that a byref entry will just be an i8**.
939 src = Builder.CreateStructGEP(LoadBlockStruct(),
940 enclosingCapture.getIndex(),
941 "block.capture.addr");
942 } else {
943 auto I = LocalDeclMap.find(variable);
944 assert(I != LocalDeclMap.end())((I != LocalDeclMap.end()) ? static_cast<void> (0) : __assert_fail
("I != LocalDeclMap.end()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 944, __PRETTY_FUNCTION__))
;
945 src = I->second;
946 }
947 } else {
948 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
949 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
950 type.getNonReferenceType(), VK_LValue,
951 SourceLocation());
952 src = EmitDeclRefLValue(&declRef).getAddress(*this);
953 };
954
955 // For byrefs, we just write the pointer to the byref struct into
956 // the block field. There's no need to chase the forwarding
957 // pointer at this point, since we're building something that will
958 // live a shorter life than the stack byref anyway.
959 if (CI.isEscapingByref()) {
960 // Get a void* that points to the byref struct.
961 llvm::Value *byrefPointer;
962 if (CI.isNested())
963 byrefPointer = Builder.CreateLoad(src, "byref.capture");
964 else
965 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
966
967 // Write that void* into the capture field.
968 Builder.CreateStore(byrefPointer, blockField);
969
970 // If we have a copy constructor, evaluate that into the block field.
971 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
972 if (blockDecl->isConversionFromLambda()) {
973 // If we have a lambda conversion, emit the expression
974 // directly into the block instead.
975 AggValueSlot Slot =
976 AggValueSlot::forAddr(blockField, Qualifiers(),
977 AggValueSlot::IsDestructed,
978 AggValueSlot::DoesNotNeedGCBarriers,
979 AggValueSlot::IsNotAliased,
980 AggValueSlot::DoesNotOverlap);
981 EmitAggExpr(copyExpr, Slot);
982 } else {
983 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
984 }
985
986 // If it's a reference variable, copy the reference into the block field.
987 } else if (type->isReferenceType()) {
988 Builder.CreateStore(src.getPointer(), blockField);
989
990 // If type is const-qualified, copy the value into the block field.
991 } else if (type.isConstQualified() &&
992 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
993 CGM.getCodeGenOpts().OptimizationLevel != 0) {
994 llvm::Value *value = Builder.CreateLoad(src, "captured");
995 Builder.CreateStore(value, blockField);
996
997 // If this is an ARC __strong block-pointer variable, don't do a
998 // block copy.
999 //
1000 // TODO: this can be generalized into the normal initialization logic:
1001 // we should never need to do a block-copy when initializing a local
1002 // variable, because the local variable's lifetime should be strictly
1003 // contained within the stack block's.
1004 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1005 type->isBlockPointerType()) {
1006 // Load the block and do a simple retain.
1007 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1008 value = EmitARCRetainNonBlock(value);
1009
1010 // Do a primitive store to the block field.
1011 Builder.CreateStore(value, blockField);
1012
1013 // Otherwise, fake up a POD copy into the block field.
1014 } else {
1015 // Fake up a new variable so that EmitScalarInit doesn't think
1016 // we're referring to the variable in its own initializer.
1017 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1018 ImplicitParamDecl::Other);
1019
1020 // We use one of these or the other depending on whether the
1021 // reference is nested.
1022 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1023 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1024 type, VK_LValue, SourceLocation());
1025
1026 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1027 &declRef, VK_RValue, FPOptionsOverride());
1028 // FIXME: Pass a specific location for the expr init so that the store is
1029 // attributed to a reasonable location - otherwise it may be attributed to
1030 // locations of subexpressions in the initialization.
1031 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1032 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1033 /*captured by init*/ false);
1034 }
1035
1036 // Push a cleanup for the capture if necessary.
1037 if (!blockInfo.NeedsCopyDispose)
1038 continue;
1039
1040 // Ignore __block captures; there's nothing special in the on-stack block
1041 // that we need to do for them.
1042 if (CI.isByRef())
1043 continue;
1044
1045 // Ignore objects that aren't destructed.
1046 QualType::DestructionKind dtorKind = type.isDestructedType();
1047 if (dtorKind == QualType::DK_none)
1048 continue;
1049
1050 CodeGenFunction::Destroyer *destroyer;
1051
1052 // Block captures count as local values and have imprecise semantics.
1053 // They also can't be arrays, so need to worry about that.
1054 //
1055 // For const-qualified captures, emit clang.arc.use to ensure the captured
1056 // object doesn't get released while we are still depending on its validity
1057 // within the block.
1058 if (type.isConstQualified() &&
1059 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1060 CGM.getCodeGenOpts().OptimizationLevel != 0) {
1061 assert(CGM.getLangOpts().ObjCAutoRefCount &&((CGM.getLangOpts().ObjCAutoRefCount && "expected ObjC ARC to be enabled"
) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCAutoRefCount && \"expected ObjC ARC to be enabled\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1062, __PRETTY_FUNCTION__))
1062 "expected ObjC ARC to be enabled")((CGM.getLangOpts().ObjCAutoRefCount && "expected ObjC ARC to be enabled"
) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCAutoRefCount && \"expected ObjC ARC to be enabled\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1062, __PRETTY_FUNCTION__))
;
1063 destroyer = emitARCIntrinsicUse;
1064 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1065 destroyer = destroyARCStrongImprecise;
1066 } else {
1067 destroyer = getDestroyer(dtorKind);
1068 }
1069
1070 CleanupKind cleanupKind = NormalCleanup;
1071 bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1072 if (useArrayEHCleanup)
1073 cleanupKind = NormalAndEHCleanup;
1074
1075 // Extend the lifetime of the capture to the end of the scope enclosing the
1076 // block expression except when the block decl is in the list of RetExpr's
1077 // cleanup objects, in which case its lifetime ends after the full
1078 // expression.
1079 auto IsBlockDeclInRetExpr = [&]() {
1080 auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1081 if (EWC)
1082 for (auto &C : EWC->getObjects())
1083 if (auto *BD = C.dyn_cast<BlockDecl *>())
1084 if (BD == blockDecl)
1085 return true;
1086 return false;
1087 };
1088
1089 if (IsBlockDeclInRetExpr())
1090 pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1091 else
1092 pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1093 useArrayEHCleanup);
1094 }
1095
1096 // Cast to the converted block-pointer type, which happens (somewhat
1097 // unfortunately) to be a pointer to function type.
1098 llvm::Value *result = Builder.CreatePointerCast(
1099 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1100
1101 if (IsOpenCL) {
1102 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1103 result);
1104 }
1105
1106 return result;
1107}
1108
1109
1110llvm::Type *CodeGenModule::getBlockDescriptorType() {
1111 if (BlockDescriptorType)
1112 return BlockDescriptorType;
1113
1114 llvm::Type *UnsignedLongTy =
1115 getTypes().ConvertType(getContext().UnsignedLongTy);
1116
1117 // struct __block_descriptor {
1118 // unsigned long reserved;
1119 // unsigned long block_size;
1120 //
1121 // // later, the following will be added
1122 //
1123 // struct {
1124 // void (*copyHelper)();
1125 // void (*copyHelper)();
1126 // } helpers; // !!! optional
1127 //
1128 // const char *signature; // the block signature
1129 // const char *layout; // reserved
1130 // };
1131 BlockDescriptorType = llvm::StructType::create(
1132 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1133
1134 // Now form a pointer to that.
1135 unsigned AddrSpace = 0;
1136 if (getLangOpts().OpenCL)
1137 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1138 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1139 return BlockDescriptorType;
1140}
1141
1142llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1143 if (GenericBlockLiteralType)
1144 return GenericBlockLiteralType;
1145
1146 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1147
1148 if (getLangOpts().OpenCL) {
1149 // struct __opencl_block_literal_generic {
1150 // int __size;
1151 // int __align;
1152 // __generic void *__invoke;
1153 // /* custom fields */
1154 // };
1155 SmallVector<llvm::Type *, 8> StructFields(
1156 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1157 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1158 for (auto I : Helper->getCustomFieldTypes())
1159 StructFields.push_back(I);
1160 }
1161 GenericBlockLiteralType = llvm::StructType::create(
1162 StructFields, "struct.__opencl_block_literal_generic");
1163 } else {
1164 // struct __block_literal_generic {
1165 // void *__isa;
1166 // int __flags;
1167 // int __reserved;
1168 // void (*__invoke)(void *);
1169 // struct __block_descriptor *__descriptor;
1170 // };
1171 GenericBlockLiteralType =
1172 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1173 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1174 }
1175
1176 return GenericBlockLiteralType;
1177}
1178
1179RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1180 ReturnValueSlot ReturnValue) {
1181 const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1182 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1183 llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1184 llvm::Value *Func = nullptr;
1185 QualType FnType = BPT->getPointeeType();
1186 ASTContext &Ctx = getContext();
1187 CallArgList Args;
1188
1189 if (getLangOpts().OpenCL) {
1190 // For OpenCL, BlockPtr is already casted to generic block literal.
1191
1192 // First argument of a block call is a generic block literal casted to
1193 // generic void pointer, i.e. i8 addrspace(4)*
1194 llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1195 BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
1196 QualType VoidPtrQualTy = Ctx.getPointerType(
1197 Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1198 Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1199 // And the rest of the arguments.
1200 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1201
1202 // We *can* call the block directly unless it is a function argument.
1203 if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1204 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1205 else {
1206 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1207 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1208 }
1209 } else {
1210 // Bitcast the block literal to a generic block literal.
1211 BlockPtr = Builder.CreatePointerCast(
1212 BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1213 // Get pointer to the block invoke function
1214 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1215
1216 // First argument is a block literal casted to a void pointer
1217 BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1218 Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1219 // And the rest of the arguments.
1220 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1221
1222 // Load the function.
1223 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1224 }
1225
1226 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1227 const CGFunctionInfo &FnInfo =
1228 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1229
1230 // Cast the function pointer to the right type.
1231 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1232
1233 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1234 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1235
1236 // Prepare the callee.
1237 CGCallee Callee(CGCalleeInfo(), Func);
1238
1239 // And call the block.
1240 return EmitCall(FnInfo, Callee, ReturnValue, Args);
1241}
1242
1243Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1244 assert(BlockInfo && "evaluating block ref without block information?")((BlockInfo && "evaluating block ref without block information?"
) ? static_cast<void> (0) : __assert_fail ("BlockInfo && \"evaluating block ref without block information?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1244, __PRETTY_FUNCTION__))
;
1245 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1246
1247 // Handle constant captures.
1248 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1249
1250 Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1251 "block.capture.addr");
1252
1253 if (variable->isEscapingByref()) {
1254 // addr should be a void** right now. Load, then cast the result
1255 // to byref*.
1256
1257 auto &byrefInfo = getBlockByrefInfo(variable);
1258 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1259
1260 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1261 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1262
1263 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1264 variable->getName());
1265 }
1266
1267 assert((!variable->isNonEscapingByref() ||(((!variable->isNonEscapingByref() || capture.fieldType()->
isReferenceType()) && "the capture field of a non-escaping variable should have a "
"reference type") ? static_cast<void> (0) : __assert_fail
("(!variable->isNonEscapingByref() || capture.fieldType()->isReferenceType()) && \"the capture field of a non-escaping variable should have a \" \"reference type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1270, __PRETTY_FUNCTION__))
1268 capture.fieldType()->isReferenceType()) &&(((!variable->isNonEscapingByref() || capture.fieldType()->
isReferenceType()) && "the capture field of a non-escaping variable should have a "
"reference type") ? static_cast<void> (0) : __assert_fail
("(!variable->isNonEscapingByref() || capture.fieldType()->isReferenceType()) && \"the capture field of a non-escaping variable should have a \" \"reference type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1270, __PRETTY_FUNCTION__))
1269 "the capture field of a non-escaping variable should have a "(((!variable->isNonEscapingByref() || capture.fieldType()->
isReferenceType()) && "the capture field of a non-escaping variable should have a "
"reference type") ? static_cast<void> (0) : __assert_fail
("(!variable->isNonEscapingByref() || capture.fieldType()->isReferenceType()) && \"the capture field of a non-escaping variable should have a \" \"reference type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1270, __PRETTY_FUNCTION__))
1270 "reference type")(((!variable->isNonEscapingByref() || capture.fieldType()->
isReferenceType()) && "the capture field of a non-escaping variable should have a "
"reference type") ? static_cast<void> (0) : __assert_fail
("(!variable->isNonEscapingByref() || capture.fieldType()->isReferenceType()) && \"the capture field of a non-escaping variable should have a \" \"reference type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1270, __PRETTY_FUNCTION__))
;
1271 if (capture.fieldType()->isReferenceType())
1272 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1273
1274 return addr;
1275}
1276
1277void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1278 llvm::Constant *Addr) {
1279 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1280 (void)Ok;
1281 assert(Ok && "Trying to replace an already-existing global block!")((Ok && "Trying to replace an already-existing global block!"
) ? static_cast<void> (0) : __assert_fail ("Ok && \"Trying to replace an already-existing global block!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1281, __PRETTY_FUNCTION__))
;
1282}
1283
1284llvm::Constant *
1285CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1286 StringRef Name) {
1287 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1
Assuming 'Block' is null
2
Taking false branch
1288 return Block;
1289
1290 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1291 blockInfo.BlockExpression = BE;
1292
1293 // Compute information about the layout, etc., of this block.
1294 computeBlockInfo(*this, nullptr, blockInfo);
3
Passing null pointer value via 2nd parameter 'CGF'
4
Calling 'computeBlockInfo'
1295
1296 // Using that metadata, generate the actual block function.
1297 {
1298 CodeGenFunction::DeclMapTy LocalDeclMap;
1299 CodeGenFunction(*this).GenerateBlockFunction(
1300 GlobalDecl(), blockInfo, LocalDeclMap,
1301 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1302 }
1303
1304 return getAddrOfGlobalBlockIfEmitted(BE);
1305}
1306
1307static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1308 const CGBlockInfo &blockInfo,
1309 llvm::Constant *blockFn) {
1310 assert(blockInfo.CanBeGlobal)((blockInfo.CanBeGlobal) ? static_cast<void> (0) : __assert_fail
("blockInfo.CanBeGlobal", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1310, __PRETTY_FUNCTION__))
;
1311 // Callers should detect this case on their own: calling this function
1312 // generally requires computing layout information, which is a waste of time
1313 // if we've already emitted this block.
1314 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&((!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression
) && "Refusing to re-emit a global block.") ? static_cast
<void> (0) : __assert_fail ("!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) && \"Refusing to re-emit a global block.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1315, __PRETTY_FUNCTION__))
1315 "Refusing to re-emit a global block.")((!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression
) && "Refusing to re-emit a global block.") ? static_cast
<void> (0) : __assert_fail ("!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) && \"Refusing to re-emit a global block.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1315, __PRETTY_FUNCTION__))
;
1316
1317 // Generate the constants for the block literal initializer.
1318 ConstantInitBuilder builder(CGM);
1319 auto fields = builder.beginStruct();
1320
1321 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1322 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1323 if (!IsOpenCL) {
1324 // isa
1325 if (IsWindows)
1326 fields.addNullPointer(CGM.Int8PtrPtrTy);
1327 else
1328 fields.add(CGM.getNSConcreteGlobalBlock());
1329
1330 // __flags
1331 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1332 if (blockInfo.UsesStret)
1333 flags |= BLOCK_USE_STRET;
1334
1335 fields.addInt(CGM.IntTy, flags.getBitMask());
1336
1337 // Reserved
1338 fields.addInt(CGM.IntTy, 0);
1339 } else {
1340 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1341 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1342 }
1343
1344 // Function
1345 fields.add(blockFn);
1346
1347 if (!IsOpenCL) {
1348 // Descriptor
1349 fields.add(buildBlockDescriptor(CGM, blockInfo));
1350 } else if (auto *Helper =
1351 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1352 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1353 fields.add(I);
1354 }
1355 }
1356
1357 unsigned AddrSpace = 0;
1358 if (CGM.getContext().getLangOpts().OpenCL)
1359 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1360
1361 llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1362 "__block_literal_global", blockInfo.BlockAlign,
1363 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1364
1365 literal->addAttribute("objc_arc_inert");
1366
1367 // Windows does not allow globals to be initialised to point to globals in
1368 // different DLLs. Any such variables must run code to initialise them.
1369 if (IsWindows) {
1370 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1371 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1372 &CGM.getModule());
1373 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1374 Init));
1375 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1376 b.CreateStructGEP(literal, 0),
1377 CGM.getPointerAlign().getAsAlign());
1378 b.CreateRetVoid();
1379 // We can't use the normal LLVM global initialisation array, because we
1380 // need to specify that this runs early in library initialisation.
1381 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1382 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1383 Init, ".block_isa_init_ptr");
1384 InitVar->setSection(".CRT$XCLa");
1385 CGM.addUsedGlobal(InitVar);
1386 }
1387
1388 // Return a constant of the appropriately-casted type.
1389 llvm::Type *RequiredType =
1390 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1391 llvm::Constant *Result =
1392 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1393 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1394 if (CGM.getContext().getLangOpts().OpenCL)
1395 CGM.getOpenCLRuntime().recordBlockInfo(
1396 blockInfo.BlockExpression,
1397 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1398 return Result;
1399}
1400
1401void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1402 unsigned argNum,
1403 llvm::Value *arg) {
1404 assert(BlockInfo && "not emitting prologue of block invocation function?!")((BlockInfo && "not emitting prologue of block invocation function?!"
) ? static_cast<void> (0) : __assert_fail ("BlockInfo && \"not emitting prologue of block invocation function?!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1404, __PRETTY_FUNCTION__))
;
1405
1406 // Allocate a stack slot like for any local variable to guarantee optimal
1407 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1408 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1409 Builder.CreateStore(arg, alloc);
1410 if (CGDebugInfo *DI = getDebugInfo()) {
1411 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1412 DI->setLocation(D->getLocation());
1413 DI->EmitDeclareOfBlockLiteralArgVariable(
1414 *BlockInfo, D->getName(), argNum,
1415 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1416 }
1417 }
1418
1419 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1420 ApplyDebugLocation Scope(*this, StartLoc);
1421
1422 // Instead of messing around with LocalDeclMap, just set the value
1423 // directly as BlockPointer.
1424 BlockPointer = Builder.CreatePointerCast(
1425 arg,
1426 BlockInfo->StructureType->getPointerTo(
1427 getContext().getLangOpts().OpenCL
1428 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1429 : 0),
1430 "block");
1431}
1432
1433Address CodeGenFunction::LoadBlockStruct() {
1434 assert(BlockInfo && "not in a block invocation function!")((BlockInfo && "not in a block invocation function!")
? static_cast<void> (0) : __assert_fail ("BlockInfo && \"not in a block invocation function!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1434, __PRETTY_FUNCTION__))
;
1435 assert(BlockPointer && "no block pointer set!")((BlockPointer && "no block pointer set!") ? static_cast
<void> (0) : __assert_fail ("BlockPointer && \"no block pointer set!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1435, __PRETTY_FUNCTION__))
;
1436 return Address(BlockPointer, BlockInfo->BlockAlign);
1437}
1438
1439llvm::Function *
1440CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1441 const CGBlockInfo &blockInfo,
1442 const DeclMapTy &ldm,
1443 bool IsLambdaConversionToBlock,
1444 bool BuildGlobalBlock) {
1445 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1446
1447 CurGD = GD;
1448
1449 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1450
1451 BlockInfo = &blockInfo;
1452
1453 // Arrange for local static and local extern declarations to appear
1454 // to be local to this function as well, in case they're directly
1455 // referenced in a block.
1456 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1457 const auto *var = dyn_cast<VarDecl>(i->first);
1458 if (var && !var->hasLocalStorage())
1459 setAddrOfLocalVar(var, i->second);
1460 }
1461
1462 // Begin building the function declaration.
1463
1464 // Build the argument list.
1465 FunctionArgList args;
1466
1467 // The first argument is the block pointer. Just take it as a void*
1468 // and cast it later.
1469 QualType selfTy = getContext().VoidPtrTy;
1470
1471 // For OpenCL passed block pointer can be private AS local variable or
1472 // global AS program scope variable (for the case with and without captures).
1473 // Generic AS is used therefore to be able to accommodate both private and
1474 // generic AS in one implementation.
1475 if (getLangOpts().OpenCL)
1476 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1477 getContext().VoidTy, LangAS::opencl_generic));
1478
1479 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1480
1481 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1482 SourceLocation(), II, selfTy,
1483 ImplicitParamDecl::ObjCSelf);
1484 args.push_back(&SelfDecl);
1485
1486 // Now add the rest of the parameters.
1487 args.append(blockDecl->param_begin(), blockDecl->param_end());
1488
1489 // Create the function declaration.
1490 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1491 const CGFunctionInfo &fnInfo =
1492 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1493 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1494 blockInfo.UsesStret = true;
1495
1496 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1497
1498 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1499 llvm::Function *fn = llvm::Function::Create(
1500 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1501 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1502
1503 if (BuildGlobalBlock) {
1504 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1505 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1506 : VoidPtrTy;
1507 buildGlobalBlock(CGM, blockInfo,
1508 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1509 }
1510
1511 // Begin generating the function.
1512 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1513 blockDecl->getLocation(),
1514 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1515
1516 // Okay. Undo some of what StartFunction did.
1517
1518 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1519 // won't delete the dbg.declare intrinsics for captured variables.
1520 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1521 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1522 // Allocate a stack slot for it, so we can point the debugger to it
1523 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1524 getPointerAlign(),
1525 "block.addr");
1526 // Set the DebugLocation to empty, so the store is recognized as a
1527 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1528 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1529 Builder.CreateStore(BlockPointer, Alloca);
1530 BlockPointerDbgLoc = Alloca.getPointer();
1531 }
1532
1533 // If we have a C++ 'this' reference, go ahead and force it into
1534 // existence now.
1535 if (blockDecl->capturesCXXThis()) {
1536 Address addr = Builder.CreateStructGEP(
1537 LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1538 CXXThisValue = Builder.CreateLoad(addr, "this");
1539 }
1540
1541 // Also force all the constant captures.
1542 for (const auto &CI : blockDecl->captures()) {
1543 const VarDecl *variable = CI.getVariable();
1544 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1545 if (!capture.isConstant()) continue;
1546
1547 CharUnits align = getContext().getDeclAlign(variable);
1548 Address alloca =
1549 CreateMemTemp(variable->getType(), align, "block.captured-const");
1550
1551 Builder.CreateStore(capture.getConstant(), alloca);
1552
1553 setAddrOfLocalVar(variable, alloca);
1554 }
1555
1556 // Save a spot to insert the debug information for all the DeclRefExprs.
1557 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1558 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1559 --entry_ptr;
1560
1561 if (IsLambdaConversionToBlock)
1562 EmitLambdaBlockInvokeBody();
1563 else {
1564 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1565 incrementProfileCounter(blockDecl->getBody());
1566 EmitStmt(blockDecl->getBody());
1567 }
1568
1569 // Remember where we were...
1570 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1571
1572 // Go back to the entry.
1573 ++entry_ptr;
1574 Builder.SetInsertPoint(entry, entry_ptr);
1575
1576 // Emit debug information for all the DeclRefExprs.
1577 // FIXME: also for 'this'
1578 if (CGDebugInfo *DI = getDebugInfo()) {
1579 for (const auto &CI : blockDecl->captures()) {
1580 const VarDecl *variable = CI.getVariable();
1581 DI->EmitLocation(Builder, variable->getLocation());
1582
1583 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1584 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1585 if (capture.isConstant()) {
1586 auto addr = LocalDeclMap.find(variable)->second;
1587 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1588 Builder);
1589 continue;
1590 }
1591
1592 DI->EmitDeclareOfBlockDeclRefVariable(
1593 variable, BlockPointerDbgLoc, Builder, blockInfo,
1594 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1595 }
1596 }
1597 // Recover location if it was changed in the above loop.
1598 DI->EmitLocation(Builder,
1599 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1600 }
1601
1602 // And resume where we left off.
1603 if (resume == nullptr)
1604 Builder.ClearInsertionPoint();
1605 else
1606 Builder.SetInsertPoint(resume);
1607
1608 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1609
1610 return fn;
1611}
1612
1613static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1614computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1615 const LangOptions &LangOpts) {
1616 if (CI.getCopyExpr()) {
1617 assert(!CI.isByRef())((!CI.isByRef()) ? static_cast<void> (0) : __assert_fail
("!CI.isByRef()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1617, __PRETTY_FUNCTION__))
;
1618 // don't bother computing flags
1619 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1620 }
1621 BlockFieldFlags Flags;
1622 if (CI.isEscapingByref()) {
1623 Flags = BLOCK_FIELD_IS_BYREF;
1624 if (T.isObjCGCWeak())
1625 Flags |= BLOCK_FIELD_IS_WEAK;
1626 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1627 }
1628
1629 Flags = BLOCK_FIELD_IS_OBJECT;
1630 bool isBlockPointer = T->isBlockPointerType();
1631 if (isBlockPointer)
1632 Flags = BLOCK_FIELD_IS_BLOCK;
1633
1634 switch (T.isNonTrivialToPrimitiveCopy()) {
1635 case QualType::PCK_Struct:
1636 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1637 BlockFieldFlags());
1638 case QualType::PCK_ARCWeak:
1639 // We need to register __weak direct captures with the runtime.
1640 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1641 case QualType::PCK_ARCStrong:
1642 // We need to retain the copied value for __strong direct captures.
1643 // If it's a block pointer, we have to copy the block and assign that to
1644 // the destination pointer, so we might as well use _Block_object_assign.
1645 // Otherwise we can avoid that.
1646 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1647 : BlockCaptureEntityKind::BlockObject,
1648 Flags);
1649 case QualType::PCK_Trivial:
1650 case QualType::PCK_VolatileTrivial: {
1651 if (!T->isObjCRetainableType())
1652 // For all other types, the memcpy is fine.
1653 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1654
1655 // Special rules for ARC captures:
1656 Qualifiers QS = T.getQualifiers();
1657
1658 // Non-ARC captures of retainable pointers are strong and
1659 // therefore require a call to _Block_object_assign.
1660 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1661 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1662
1663 // Otherwise the memcpy is fine.
1664 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1665 }
1666 }
1667 llvm_unreachable("after exhaustive PrimitiveCopyKind switch")::llvm::llvm_unreachable_internal("after exhaustive PrimitiveCopyKind switch"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1667)
;
1668}
1669
1670static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1671computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1672 const LangOptions &LangOpts);
1673
1674/// Find the set of block captures that need to be explicitly copied or destroy.
1675static void findBlockCapturedManagedEntities(
1676 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1677 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
1678 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1679 const VarDecl *Variable = CI.getVariable();
1680 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1681 if (Capture.isConstant())
1682 continue;
1683
1684 QualType VT = Capture.fieldType();
1685 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1686 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
1687 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1688 DisposeInfo.first != BlockCaptureEntityKind::None)
1689 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1690 CopyInfo.second, DisposeInfo.second, CI,
1691 Capture);
1692 }
1693
1694 // Sort the captures by offset.
1695 llvm::sort(ManagedCaptures);
1696}
1697
1698namespace {
1699/// Release a __block variable.
1700struct CallBlockRelease final : EHScopeStack::Cleanup {
1701 Address Addr;
1702 BlockFieldFlags FieldFlags;
1703 bool LoadBlockVarAddr, CanThrow;
1704
1705 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1706 bool CT)
1707 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1708 CanThrow(CT) {}
1709
1710 void Emit(CodeGenFunction &CGF, Flags flags) override {
1711 llvm::Value *BlockVarAddr;
1712 if (LoadBlockVarAddr) {
1713 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1714 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1715 } else {
1716 BlockVarAddr = Addr.getPointer();
1717 }
1718
1719 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1720 }
1721};
1722} // end anonymous namespace
1723
1724/// Check if \p T is a C++ class that has a destructor that can throw.
1725bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1726 if (const auto *RD = T->getAsCXXRecordDecl())
1727 if (const CXXDestructorDecl *DD = RD->getDestructor())
1728 return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1729 return false;
1730}
1731
1732// Return a string that has the information about a capture.
1733static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1734 CaptureStrKind StrKind,
1735 CharUnits BlockAlignment,
1736 CodeGenModule &CGM) {
1737 std::string Str;
1738 ASTContext &Ctx = CGM.getContext();
1739 const BlockDecl::Capture &CI = *E.CI;
1740 QualType CaptureTy = CI.getVariable()->getType();
1741
1742 BlockCaptureEntityKind Kind;
1743 BlockFieldFlags Flags;
1744
1745 // CaptureStrKind::Merged should be passed only when the operations and the
1746 // flags are the same for copy and dispose.
1747 assert((StrKind != CaptureStrKind::Merged ||(((StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind
&& E.CopyFlags == E.DisposeFlags)) && "different operations and flags"
) ? static_cast<void> (0) : __assert_fail ("(StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) && \"different operations and flags\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1749, __PRETTY_FUNCTION__))
1748 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&(((StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind
&& E.CopyFlags == E.DisposeFlags)) && "different operations and flags"
) ? static_cast<void> (0) : __assert_fail ("(StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) && \"different operations and flags\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 "different operations and flags")(((StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind
&& E.CopyFlags == E.DisposeFlags)) && "different operations and flags"
) ? static_cast<void> (0) : __assert_fail ("(StrKind != CaptureStrKind::Merged || (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) && \"different operations and flags\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1749, __PRETTY_FUNCTION__))
;
1750
1751 if (StrKind == CaptureStrKind::DisposeHelper) {
1752 Kind = E.DisposeKind;
1753 Flags = E.DisposeFlags;
1754 } else {
1755 Kind = E.CopyKind;
1756 Flags = E.CopyFlags;
1757 }
1758
1759 switch (Kind) {
1760 case BlockCaptureEntityKind::CXXRecord: {
1761 Str += "c";
1762 SmallString<256> TyStr;
1763 llvm::raw_svector_ostream Out(TyStr);
1764 CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1765 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1766 break;
1767 }
1768 case BlockCaptureEntityKind::ARCWeak:
1769 Str += "w";
1770 break;
1771 case BlockCaptureEntityKind::ARCStrong:
1772 Str += "s";
1773 break;
1774 case BlockCaptureEntityKind::BlockObject: {
1775 const VarDecl *Var = CI.getVariable();
1776 unsigned F = Flags.getBitMask();
1777 if (F & BLOCK_FIELD_IS_BYREF) {
1778 Str += "r";
1779 if (F & BLOCK_FIELD_IS_WEAK)
1780 Str += "w";
1781 else {
1782 // If CaptureStrKind::Merged is passed, check both the copy expression
1783 // and the destructor.
1784 if (StrKind != CaptureStrKind::DisposeHelper) {
1785 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1786 Str += "c";
1787 }
1788 if (StrKind != CaptureStrKind::CopyHelper) {
1789 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1790 Str += "d";
1791 }
1792 }
1793 } else {
1794 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value")(((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value"
) ? static_cast<void> (0) : __assert_fail ("(F & BLOCK_FIELD_IS_OBJECT) && \"unexpected flag value\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1794, __PRETTY_FUNCTION__))
;
1795 if (F == BLOCK_FIELD_IS_BLOCK)
1796 Str += "b";
1797 else
1798 Str += "o";
1799 }
1800 break;
1801 }
1802 case BlockCaptureEntityKind::NonTrivialCStruct: {
1803 bool IsVolatile = CaptureTy.isVolatileQualified();
1804 CharUnits Alignment =
1805 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1806
1807 Str += "n";
1808 std::string FuncStr;
1809 if (StrKind == CaptureStrKind::DisposeHelper)
1810 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1811 CaptureTy, Alignment, IsVolatile, Ctx);
1812 else
1813 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1814 // It has all the information that the destructor string has.
1815 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1816 CaptureTy, Alignment, IsVolatile, Ctx);
1817 // The underscore is necessary here because non-trivial copy constructor
1818 // and destructor strings can start with a number.
1819 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1820 break;
1821 }
1822 case BlockCaptureEntityKind::None:
1823 break;
1824 }
1825
1826 return Str;
1827}
1828
1829static std::string getCopyDestroyHelperFuncName(
1830 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1831 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1832 assert((StrKind == CaptureStrKind::CopyHelper ||(((StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind
::DisposeHelper) && "unexpected CaptureStrKind") ? static_cast
<void> (0) : __assert_fail ("(StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind::DisposeHelper) && \"unexpected CaptureStrKind\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1834, __PRETTY_FUNCTION__))
1833 StrKind == CaptureStrKind::DisposeHelper) &&(((StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind
::DisposeHelper) && "unexpected CaptureStrKind") ? static_cast
<void> (0) : __assert_fail ("(StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind::DisposeHelper) && \"unexpected CaptureStrKind\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1834, __PRETTY_FUNCTION__))
1834 "unexpected CaptureStrKind")(((StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind
::DisposeHelper) && "unexpected CaptureStrKind") ? static_cast
<void> (0) : __assert_fail ("(StrKind == CaptureStrKind::CopyHelper || StrKind == CaptureStrKind::DisposeHelper) && \"unexpected CaptureStrKind\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1834, __PRETTY_FUNCTION__))
;
1835 std::string Name = StrKind == CaptureStrKind::CopyHelper
1836 ? "__copy_helper_block_"
1837 : "__destroy_helper_block_";
1838 if (CGM.getLangOpts().Exceptions)
1839 Name += "e";
1840 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1841 Name += "a";
1842 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1843
1844 for (const BlockCaptureManagedEntity &E : Captures) {
1845 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
1846 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
1847 }
1848
1849 return Name;
1850}
1851
1852static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1853 Address Field, QualType CaptureType,
1854 BlockFieldFlags Flags, bool ForCopyHelper,
1855 VarDecl *Var, CodeGenFunction &CGF) {
1856 bool EHOnly = ForCopyHelper;
1857
1858 switch (CaptureKind) {
1859 case BlockCaptureEntityKind::CXXRecord:
1860 case BlockCaptureEntityKind::ARCWeak:
1861 case BlockCaptureEntityKind::NonTrivialCStruct:
1862 case BlockCaptureEntityKind::ARCStrong: {
1863 if (CaptureType.isDestructedType() &&
1864 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1865 CodeGenFunction::Destroyer *Destroyer =
1866 CaptureKind == BlockCaptureEntityKind::ARCStrong
1867 ? CodeGenFunction::destroyARCStrongImprecise
1868 : CGF.getDestroyer(CaptureType.isDestructedType());
1869 CleanupKind Kind =
1870 EHOnly ? EHCleanup
1871 : CGF.getCleanupKind(CaptureType.isDestructedType());
1872 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1873 }
1874 break;
1875 }
1876 case BlockCaptureEntityKind::BlockObject: {
1877 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1878 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1879 // Calls to _Block_object_dispose along the EH path in the copy helper
1880 // function don't throw as newly-copied __block variables always have a
1881 // reference count of 2.
1882 bool CanThrow =
1883 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1884 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1885 CanThrow);
1886 }
1887 break;
1888 }
1889 case BlockCaptureEntityKind::None:
1890 break;
1891 }
1892}
1893
1894static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1895 llvm::Function *Fn,
1896 const CGFunctionInfo &FI,
1897 CodeGenModule &CGM) {
1898 if (CapturesNonExternalType) {
1899 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1900 } else {
1901 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1902 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1903 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
1904 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1905 }
1906}
1907/// Generate the copy-helper function for a block closure object:
1908/// static void block_copy_helper(block_t *dst, block_t *src);
1909/// The runtime will have previously initialized 'dst' by doing a
1910/// bit-copy of 'src'.
1911///
1912/// Note that this copies an entire block closure object to the heap;
1913/// it should not be confused with a 'byref copy helper', which moves
1914/// the contents of an individual __block variable to the heap.
1915llvm::Constant *
1916CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1917 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1918 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
1919 std::string FuncName =
1920 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
1921 CaptureStrKind::CopyHelper, CGM);
1922
1923 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1924 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
1925
1926 ASTContext &C = getContext();
1927
1928 QualType ReturnTy = C.VoidTy;
1929
1930 FunctionArgList args;
1931 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1932 args.push_back(&DstDecl);
1933 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1934 args.push_back(&SrcDecl);
1935
1936 const CGFunctionInfo &FI =
1937 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
1938
1939 // FIXME: it would be nice if these were mergeable with things with
1940 // identical semantics.
1941 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1942
1943 llvm::Function *Fn =
1944 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1945 FuncName, &CGM.getModule());
1946 if (CGM.supportsCOMDAT())
1947 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
1948
1949 IdentifierInfo *II = &C.Idents.get(FuncName);
1950
1951 SmallVector<QualType, 2> ArgTys;
1952 ArgTys.push_back(C.VoidPtrTy);
1953 ArgTys.push_back(C.VoidPtrTy);
1954 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
1955
1956 FunctionDecl *FD = FunctionDecl::Create(
1957 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
1958 FunctionTy, nullptr, SC_Static, false, false);
1959 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1960 CGM);
1961 // This is necessary to avoid inheriting the previous line number.
1962 FD->setImplicit();
1963 StartFunction(FD, ReturnTy, Fn, FI, args);
1964 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1965
1966 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1967
1968 Address src = GetAddrOfLocalVar(&SrcDecl);
1969 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1970 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1971
1972 Address dst = GetAddrOfLocalVar(&DstDecl);
1973 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1974 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1975
1976 for (const auto &CopiedCapture : CopiedCaptures) {
1977 const BlockDecl::Capture &CI = *CopiedCapture.CI;
1978 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
1979 QualType captureType = CI.getVariable()->getType();
1980 BlockFieldFlags flags = CopiedCapture.CopyFlags;
1981
1982 unsigned index = capture.getIndex();
1983 Address srcField = Builder.CreateStructGEP(src, index);
1984 Address dstField = Builder.CreateStructGEP(dst, index);
1985
1986 switch (CopiedCapture.CopyKind) {
1987 case BlockCaptureEntityKind::CXXRecord:
1988 // If there's an explicit copy expression, we do that.
1989 assert(CI.getCopyExpr() && "copy expression for variable is missing")((CI.getCopyExpr() && "copy expression for variable is missing"
) ? static_cast<void> (0) : __assert_fail ("CI.getCopyExpr() && \"copy expression for variable is missing\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 1989, __PRETTY_FUNCTION__))
;
1990 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1991 break;
1992 case BlockCaptureEntityKind::ARCWeak:
1993 EmitARCCopyWeak(dstField, srcField);
1994 break;
1995 case BlockCaptureEntityKind::NonTrivialCStruct: {
1996 // If this is a C struct that requires non-trivial copy construction,
1997 // emit a call to its copy constructor.
1998 QualType varType = CI.getVariable()->getType();
1999 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2000 MakeAddrLValue(srcField, varType));
2001 break;
2002 }
2003 case BlockCaptureEntityKind::ARCStrong: {
2004 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2005 // At -O0, store null into the destination field (so that the
2006 // storeStrong doesn't over-release) and then call storeStrong.
2007 // This is a workaround to not having an initStrong call.
2008 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2009 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2010 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2011 Builder.CreateStore(null, dstField);
2012 EmitARCStoreStrongCall(dstField, srcValue, true);
2013
2014 // With optimization enabled, take advantage of the fact that
2015 // the blocks runtime guarantees a memcpy of the block data, and
2016 // just emit a retain of the src field.
2017 } else {
2018 EmitARCRetainNonBlock(srcValue);
2019
2020 // Unless EH cleanup is required, we don't need this anymore, so kill
2021 // it. It's not quite worth the annoyance to avoid creating it in the
2022 // first place.
2023 if (!needsEHCleanup(captureType.isDestructedType()))
2024 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
2025 }
2026 break;
2027 }
2028 case BlockCaptureEntityKind::BlockObject: {
2029 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2030 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2031 llvm::Value *dstAddr =
2032 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2033 llvm::Value *args[] = {
2034 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2035 };
2036
2037 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2038 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2039 else
2040 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2041 break;
2042 }
2043 case BlockCaptureEntityKind::None:
2044 continue;
2045 }
2046
2047 // Ensure that we destroy the copied object if an exception is thrown later
2048 // in the helper function.
2049 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
2050 /*ForCopyHelper*/ true, CI.getVariable(), *this);
2051 }
2052
2053 FinishFunction();
2054
2055 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2056}
2057
2058static BlockFieldFlags
2059getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2060 QualType T) {
2061 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2062 if (T->isBlockPointerType())
2063 Flags = BLOCK_FIELD_IS_BLOCK;
2064 return Flags;
2065}
2066
2067static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2068computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2069 const LangOptions &LangOpts) {
2070 if (CI.isEscapingByref()) {
2071 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2072 if (T.isObjCGCWeak())
2073 Flags |= BLOCK_FIELD_IS_WEAK;
2074 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2075 }
2076
2077 switch (T.isDestructedType()) {
2078 case QualType::DK_cxx_destructor:
2079 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2080 case QualType::DK_objc_strong_lifetime:
2081 // Use objc_storeStrong for __strong direct captures; the
2082 // dynamic tools really like it when we do this.
2083 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2084 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2085 case QualType::DK_objc_weak_lifetime:
2086 // Support __weak direct captures.
2087 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2088 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2089 case QualType::DK_nontrivial_c_struct:
2090 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2091 BlockFieldFlags());
2092 case QualType::DK_none: {
2093 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2094 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2095 !LangOpts.ObjCAutoRefCount)
2096 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2097 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2098 // Otherwise, we have nothing to do.
2099 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2100 }
2101 }
2102 llvm_unreachable("after exhaustive DestructionKind switch")::llvm::llvm_unreachable_internal("after exhaustive DestructionKind switch"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2102)
;
2103}
2104
2105/// Generate the destroy-helper function for a block closure object:
2106/// static void block_destroy_helper(block_t *theBlock);
2107///
2108/// Note that this destroys a heap-allocated block closure object;
2109/// it should not be confused with a 'byref destroy helper', which
2110/// destroys the heap-allocated contents of an individual __block
2111/// variable.
2112llvm::Constant *
2113CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2114 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
2115 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
2116 std::string FuncName =
2117 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
2118 CaptureStrKind::DisposeHelper, CGM);
2119
2120 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2121 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2122
2123 ASTContext &C = getContext();
2124
2125 QualType ReturnTy = C.VoidTy;
2126
2127 FunctionArgList args;
2128 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2129 args.push_back(&SrcDecl);
2130
2131 const CGFunctionInfo &FI =
2132 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2133
2134 // FIXME: We'd like to put these into a mergable by content, with
2135 // internal linkage.
2136 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2137
2138 llvm::Function *Fn =
2139 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2140 FuncName, &CGM.getModule());
2141 if (CGM.supportsCOMDAT())
2142 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2143
2144 IdentifierInfo *II = &C.Idents.get(FuncName);
2145
2146 SmallVector<QualType, 1> ArgTys;
2147 ArgTys.push_back(C.VoidPtrTy);
2148 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2149
2150 FunctionDecl *FD = FunctionDecl::Create(
2151 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2152 FunctionTy, nullptr, SC_Static, false, false);
2153
2154 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2155 CGM);
2156 // This is necessary to avoid inheriting the previous line number.
2157 FD->setImplicit();
2158 StartFunction(FD, ReturnTy, Fn, FI, args);
2159 markAsIgnoreThreadCheckingAtRuntime(Fn);
2160
2161 auto AL = ApplyDebugLocation::CreateArtificial(*this);
2162
2163 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2164
2165 Address src = GetAddrOfLocalVar(&SrcDecl);
2166 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2167 src = Builder.CreateBitCast(src, structPtrTy, "block");
2168
2169 CodeGenFunction::RunCleanupsScope cleanups(*this);
2170
2171 for (const auto &DestroyedCapture : DestroyedCaptures) {
2172 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2173 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
2174 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
2175
2176 Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2177
2178 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
2179 CI.getVariable()->getType(), flags,
2180 /*ForCopyHelper*/ false, CI.getVariable(), *this);
2181 }
2182
2183 cleanups.ForceCleanup();
2184
2185 FinishFunction();
2186
2187 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2188}
2189
2190namespace {
2191
2192/// Emits the copy/dispose helper functions for a __block object of id type.
2193class ObjectByrefHelpers final : public BlockByrefHelpers {
2194 BlockFieldFlags Flags;
2195
2196public:
2197 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2198 : BlockByrefHelpers(alignment), Flags(flags) {}
2199
2200 void emitCopy(CodeGenFunction &CGF, Address destField,
2201 Address srcField) override {
2202 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2203
2204 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2205 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2206
2207 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2208
2209 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2210 llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2211
2212 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2213 CGF.EmitNounwindRuntimeCall(fn, args);
2214 }
2215
2216 void emitDispose(CodeGenFunction &CGF, Address field) override {
2217 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2218 llvm::Value *value = CGF.Builder.CreateLoad(field);
2219
2220 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2221 }
2222
2223 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2224 id.AddInteger(Flags.getBitMask());
2225 }
2226};
2227
2228/// Emits the copy/dispose helpers for an ARC __block __weak variable.
2229class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2230public:
2231 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2232
2233 void emitCopy(CodeGenFunction &CGF, Address destField,
2234 Address srcField) override {
2235 CGF.EmitARCMoveWeak(destField, srcField);
2236 }
2237
2238 void emitDispose(CodeGenFunction &CGF, Address field) override {
2239 CGF.EmitARCDestroyWeak(field);
2240 }
2241
2242 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2243 // 0 is distinguishable from all pointers and byref flags
2244 id.AddInteger(0);
2245 }
2246};
2247
2248/// Emits the copy/dispose helpers for an ARC __block __strong variable
2249/// that's not of block-pointer type.
2250class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2251public:
2252 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2253
2254 void emitCopy(CodeGenFunction &CGF, Address destField,
2255 Address srcField) override {
2256 // Do a "move" by copying the value and then zeroing out the old
2257 // variable.
2258
2259 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2260
2261 llvm::Value *null =
2262 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2263
2264 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2265 CGF.Builder.CreateStore(null, destField);
2266 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2267 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2268 return;
2269 }
2270 CGF.Builder.CreateStore(value, destField);
2271 CGF.Builder.CreateStore(null, srcField);
2272 }
2273
2274 void emitDispose(CodeGenFunction &CGF, Address field) override {
2275 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2276 }
2277
2278 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2279 // 1 is distinguishable from all pointers and byref flags
2280 id.AddInteger(1);
2281 }
2282};
2283
2284/// Emits the copy/dispose helpers for an ARC __block __strong
2285/// variable that's of block-pointer type.
2286class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2287public:
2288 ARCStrongBlockByrefHelpers(CharUnits alignment)
2289 : BlockByrefHelpers(alignment) {}
2290
2291 void emitCopy(CodeGenFunction &CGF, Address destField,
2292 Address srcField) override {
2293 // Do the copy with objc_retainBlock; that's all that
2294 // _Block_object_assign would do anyway, and we'd have to pass the
2295 // right arguments to make sure it doesn't get no-op'ed.
2296 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2297 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2298 CGF.Builder.CreateStore(copy, destField);
2299 }
2300
2301 void emitDispose(CodeGenFunction &CGF, Address field) override {
2302 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2303 }
2304
2305 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2306 // 2 is distinguishable from all pointers and byref flags
2307 id.AddInteger(2);
2308 }
2309};
2310
2311/// Emits the copy/dispose helpers for a __block variable with a
2312/// nontrivial copy constructor or destructor.
2313class CXXByrefHelpers final : public BlockByrefHelpers {
2314 QualType VarType;
2315 const Expr *CopyExpr;
2316
2317public:
2318 CXXByrefHelpers(CharUnits alignment, QualType type,
2319 const Expr *copyExpr)
2320 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2321
2322 bool needsCopy() const override { return CopyExpr != nullptr; }
2323 void emitCopy(CodeGenFunction &CGF, Address destField,
2324 Address srcField) override {
2325 if (!CopyExpr) return;
2326 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2327 }
2328
2329 void emitDispose(CodeGenFunction &CGF, Address field) override {
2330 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2331 CGF.PushDestructorCleanup(VarType, field);
2332 CGF.PopCleanupBlocks(cleanupDepth);
2333 }
2334
2335 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2336 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2337 }
2338};
2339
2340/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2341/// C struct.
2342class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2343 QualType VarType;
2344
2345public:
2346 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2347 : BlockByrefHelpers(alignment), VarType(type) {}
2348
2349 void emitCopy(CodeGenFunction &CGF, Address destField,
2350 Address srcField) override {
2351 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2352 CGF.MakeAddrLValue(srcField, VarType));
2353 }
2354
2355 bool needsDispose() const override {
2356 return VarType.isDestructedType();
2357 }
2358
2359 void emitDispose(CodeGenFunction &CGF, Address field) override {
2360 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2361 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2362 CGF.PopCleanupBlocks(cleanupDepth);
2363 }
2364
2365 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2366 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2367 }
2368};
2369} // end anonymous namespace
2370
2371static llvm::Constant *
2372generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2373 BlockByrefHelpers &generator) {
2374 ASTContext &Context = CGF.getContext();
2375
2376 QualType ReturnTy = Context.VoidTy;
2377
2378 FunctionArgList args;
2379 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2380 args.push_back(&Dst);
2381
2382 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2383 args.push_back(&Src);
2384
2385 const CGFunctionInfo &FI =
2386 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2387
2388 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2389
2390 // FIXME: We'd like to put these into a mergable by content, with
2391 // internal linkage.
2392 llvm::Function *Fn =
2393 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2394 "__Block_byref_object_copy_", &CGF.CGM.getModule());
2395
2396 IdentifierInfo *II
2397 = &Context.Idents.get("__Block_byref_object_copy_");
2398
2399 SmallVector<QualType, 2> ArgTys;
2400 ArgTys.push_back(Context.VoidPtrTy);
2401 ArgTys.push_back(Context.VoidPtrTy);
2402 QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2403
2404 FunctionDecl *FD = FunctionDecl::Create(
2405 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2406 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2407
2408 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2409
2410 CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
2411
2412 if (generator.needsCopy()) {
2413 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
2414
2415 // dst->x
2416 Address destField = CGF.GetAddrOfLocalVar(&Dst);
2417 destField = Address(CGF.Builder.CreateLoad(destField),
2418 byrefInfo.ByrefAlignment);
2419 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
2420 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2421 "dest-object");
2422
2423 // src->x
2424 Address srcField = CGF.GetAddrOfLocalVar(&Src);
2425 srcField = Address(CGF.Builder.CreateLoad(srcField),
2426 byrefInfo.ByrefAlignment);
2427 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
2428 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2429 "src-object");
2430
2431 generator.emitCopy(CGF, destField, srcField);
2432 }
2433
2434 CGF.FinishFunction();
2435
2436 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2437}
2438
2439/// Build the copy helper for a __block variable.
2440static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2441 const BlockByrefInfo &byrefInfo,
2442 BlockByrefHelpers &generator) {
2443 CodeGenFunction CGF(CGM);
2444 return generateByrefCopyHelper(CGF, byrefInfo, generator);
2445}
2446
2447/// Generate code for a __block variable's dispose helper.
2448static llvm::Constant *
2449generateByrefDisposeHelper(CodeGenFunction &CGF,
2450 const BlockByrefInfo &byrefInfo,
2451 BlockByrefHelpers &generator) {
2452 ASTContext &Context = CGF.getContext();
2453 QualType R = Context.VoidTy;
2454
2455 FunctionArgList args;
2456 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2457 ImplicitParamDecl::Other);
2458 args.push_back(&Src);
2459
2460 const CGFunctionInfo &FI =
2461 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2462
2463 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2464
2465 // FIXME: We'd like to put these into a mergable by content, with
2466 // internal linkage.
2467 llvm::Function *Fn =
2468 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2469 "__Block_byref_object_dispose_",
2470 &CGF.CGM.getModule());
2471
2472 IdentifierInfo *II
2473 = &Context.Idents.get("__Block_byref_object_dispose_");
2474
2475 SmallVector<QualType, 1> ArgTys;
2476 ArgTys.push_back(Context.VoidPtrTy);
2477 QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2478
2479 FunctionDecl *FD = FunctionDecl::Create(
2480 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2481 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2482
2483 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2484
2485 CGF.StartFunction(FD, R, Fn, FI, args);
2486
2487 if (generator.needsDispose()) {
2488 Address addr = CGF.GetAddrOfLocalVar(&Src);
2489 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2490 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2491 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2492 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2493
2494 generator.emitDispose(CGF, addr);
2495 }
2496
2497 CGF.FinishFunction();
2498
2499 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2500}
2501
2502/// Build the dispose helper for a __block variable.
2503static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2504 const BlockByrefInfo &byrefInfo,
2505 BlockByrefHelpers &generator) {
2506 CodeGenFunction CGF(CGM);
2507 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2508}
2509
2510/// Lazily build the copy and dispose helpers for a __block variable
2511/// with the given information.
2512template <class T>
2513static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2514 T &&generator) {
2515 llvm::FoldingSetNodeID id;
2516 generator.Profile(id);
2517
2518 void *insertPos;
2519 BlockByrefHelpers *node
2520 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521 if (node) return static_cast<T*>(node);
2522
2523 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528 return copy;
2529}
2530
2531/// Build the copy and dispose helpers for the given __block variable
2532/// emission. Places the helpers in the global cache. Returns null
2533/// if no helpers are required.
2534BlockByrefHelpers *
2535CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2536 const AutoVarEmission &emission) {
2537 const VarDecl &var = *emission.Variable;
2538 assert(var.isEscapingByref() &&((var.isEscapingByref() && "only escaping __block variables need byref helpers"
) ? static_cast<void> (0) : __assert_fail ("var.isEscapingByref() && \"only escaping __block variables need byref helpers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2539, __PRETTY_FUNCTION__))
2539 "only escaping __block variables need byref helpers")((var.isEscapingByref() && "only escaping __block variables need byref helpers"
) ? static_cast<void> (0) : __assert_fail ("var.isEscapingByref() && \"only escaping __block variables need byref helpers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2539, __PRETTY_FUNCTION__))
;
2540
2541 QualType type = var.getType();
2542
2543 auto &byrefInfo = getBlockByrefInfo(&var);
2544
2545 // The alignment we care about for the purposes of uniquing byref
2546 // helpers is the alignment of the actual byref value field.
2547 CharUnits valueAlignment =
2548 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2549
2550 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2551 const Expr *copyExpr =
2552 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2553 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2554
2555 return ::buildByrefHelpers(
2556 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2557 }
2558
2559 // If type is a non-trivial C struct type that is non-trivial to
2560 // destructly move or destroy, build the copy and dispose helpers.
2561 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2562 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2563 return ::buildByrefHelpers(
2564 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2565
2566 // Otherwise, if we don't have a retainable type, there's nothing to do.
2567 // that the runtime does extra copies.
2568 if (!type->isObjCRetainableType()) return nullptr;
2569
2570 Qualifiers qs = type.getQualifiers();
2571
2572 // If we have lifetime, that dominates.
2573 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2574 switch (lifetime) {
2575 case Qualifiers::OCL_None: llvm_unreachable("impossible")::llvm::llvm_unreachable_internal("impossible", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2575)
;
2576
2577 // These are just bits as far as the runtime is concerned.
2578 case Qualifiers::OCL_ExplicitNone:
2579 case Qualifiers::OCL_Autoreleasing:
2580 return nullptr;
2581
2582 // Tell the runtime that this is ARC __weak, called by the
2583 // byref routines.
2584 case Qualifiers::OCL_Weak:
2585 return ::buildByrefHelpers(CGM, byrefInfo,
2586 ARCWeakByrefHelpers(valueAlignment));
2587
2588 // ARC __strong __block variables need to be retained.
2589 case Qualifiers::OCL_Strong:
2590 // Block pointers need to be copied, and there's no direct
2591 // transfer possible.
2592 if (type->isBlockPointerType()) {
2593 return ::buildByrefHelpers(CGM, byrefInfo,
2594 ARCStrongBlockByrefHelpers(valueAlignment));
2595
2596 // Otherwise, we transfer ownership of the retain from the stack
2597 // to the heap.
2598 } else {
2599 return ::buildByrefHelpers(CGM, byrefInfo,
2600 ARCStrongByrefHelpers(valueAlignment));
2601 }
2602 }
2603 llvm_unreachable("fell out of lifetime switch!")::llvm::llvm_unreachable_internal("fell out of lifetime switch!"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2603)
;
2604 }
2605
2606 BlockFieldFlags flags;
2607 if (type->isBlockPointerType()) {
2608 flags |= BLOCK_FIELD_IS_BLOCK;
2609 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2610 type->isObjCObjectPointerType()) {
2611 flags |= BLOCK_FIELD_IS_OBJECT;
2612 } else {
2613 return nullptr;
2614 }
2615
2616 if (type.isObjCGCWeak())
2617 flags |= BLOCK_FIELD_IS_WEAK;
2618
2619 return ::buildByrefHelpers(CGM, byrefInfo,
2620 ObjectByrefHelpers(valueAlignment, flags));
2621}
2622
2623Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2624 const VarDecl *var,
2625 bool followForward) {
2626 auto &info = getBlockByrefInfo(var);
2627 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2628}
2629
2630Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2631 const BlockByrefInfo &info,
2632 bool followForward,
2633 const llvm::Twine &name) {
2634 // Chase the forwarding address if requested.
2635 if (followForward) {
2636 Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2637 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2638 }
2639
2640 return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2641}
2642
2643/// BuildByrefInfo - This routine changes a __block variable declared as T x
2644/// into:
2645///
2646/// struct {
2647/// void *__isa;
2648/// void *__forwarding;
2649/// int32_t __flags;
2650/// int32_t __size;
2651/// void *__copy_helper; // only if needed
2652/// void *__destroy_helper; // only if needed
2653/// void *__byref_variable_layout;// only if needed
2654/// char padding[X]; // only if needed
2655/// T x;
2656/// } x
2657///
2658const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2659 auto it = BlockByrefInfos.find(D);
2660 if (it != BlockByrefInfos.end())
2661 return it->second;
2662
2663 llvm::StructType *byrefType =
2664 llvm::StructType::create(getLLVMContext(),
2665 "struct.__block_byref_" + D->getNameAsString());
2666
2667 QualType Ty = D->getType();
2668
2669 CharUnits size;
2670 SmallVector<llvm::Type *, 8> types;
2671
2672 // void *__isa;
2673 types.push_back(Int8PtrTy);
2674 size += getPointerSize();
2675
2676 // void *__forwarding;
2677 types.push_back(llvm::PointerType::getUnqual(byrefType));
2678 size += getPointerSize();
2679
2680 // int32_t __flags;
2681 types.push_back(Int32Ty);
2682 size += CharUnits::fromQuantity(4);
2683
2684 // int32_t __size;
2685 types.push_back(Int32Ty);
2686 size += CharUnits::fromQuantity(4);
2687
2688 // Note that this must match *exactly* the logic in buildByrefHelpers.
2689 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2690 if (hasCopyAndDispose) {
2691 /// void *__copy_helper;
2692 types.push_back(Int8PtrTy);
2693 size += getPointerSize();
2694
2695 /// void *__destroy_helper;
2696 types.push_back(Int8PtrTy);
2697 size += getPointerSize();
2698 }
2699
2700 bool HasByrefExtendedLayout = false;
2701 Qualifiers::ObjCLifetime Lifetime;
2702 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2703 HasByrefExtendedLayout) {
2704 /// void *__byref_variable_layout;
2705 types.push_back(Int8PtrTy);
2706 size += CharUnits::fromQuantity(PointerSizeInBytes);
2707 }
2708
2709 // T x;
2710 llvm::Type *varTy = ConvertTypeForMem(Ty);
2711
2712 bool packed = false;
2713 CharUnits varAlign = getContext().getDeclAlign(D);
2714 CharUnits varOffset = size.alignTo(varAlign);
2715
2716 // We may have to insert padding.
2717 if (varOffset != size) {
2718 llvm::Type *paddingTy =
2719 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2720
2721 types.push_back(paddingTy);
2722 size = varOffset;
2723
2724 // Conversely, we might have to prevent LLVM from inserting padding.
2725 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2726 > varAlign.getQuantity()) {
2727 packed = true;
2728 }
2729 types.push_back(varTy);
2730
2731 byrefType->setBody(types, packed);
2732
2733 BlockByrefInfo info;
2734 info.Type = byrefType;
2735 info.FieldIndex = types.size() - 1;
2736 info.FieldOffset = varOffset;
2737 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2738
2739 auto pair = BlockByrefInfos.insert({D, info});
2740 assert(pair.second && "info was inserted recursively?")((pair.second && "info was inserted recursively?") ? static_cast
<void> (0) : __assert_fail ("pair.second && \"info was inserted recursively?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2740, __PRETTY_FUNCTION__))
;
2741 return pair.first->second;
2742}
2743
2744/// Initialize the structural components of a __block variable, i.e.
2745/// everything but the actual object.
2746void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2747 // Find the address of the local.
2748 Address addr = emission.Addr;
2749
2750 // That's an alloca of the byref structure type.
2751 llvm::StructType *byrefType = cast<llvm::StructType>(
2752 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2753
2754 unsigned nextHeaderIndex = 0;
2755 CharUnits nextHeaderOffset;
2756 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2757 const Twine &name) {
2758 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2759 Builder.CreateStore(value, fieldAddr);
2760
2761 nextHeaderIndex++;
2762 nextHeaderOffset += fieldSize;
2763 };
2764
2765 // Build the byref helpers if necessary. This is null if we don't need any.
2766 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2767
2768 const VarDecl &D = *emission.Variable;
2769 QualType type = D.getType();
2770
2771 bool HasByrefExtendedLayout;
2772 Qualifiers::ObjCLifetime ByrefLifetime;
2773 bool ByRefHasLifetime =
2774 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2775
2776 llvm::Value *V;
2777
2778 // Initialize the 'isa', which is just 0 or 1.
2779 int isa = 0;
2780 if (type.isObjCGCWeak())
2781 isa = 1;
2782 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2783 storeHeaderField(V, getPointerSize(), "byref.isa");
2784
2785 // Store the address of the variable into its own forwarding pointer.
2786 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2787
2788 // Blocks ABI:
2789 // c) the flags field is set to either 0 if no helper functions are
2790 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2791 BlockFlags flags;
2792 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2793 if (ByRefHasLifetime) {
2794 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2795 else switch (ByrefLifetime) {
2796 case Qualifiers::OCL_Strong:
2797 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2798 break;
2799 case Qualifiers::OCL_Weak:
2800 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2801 break;
2802 case Qualifiers::OCL_ExplicitNone:
2803 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2804 break;
2805 case Qualifiers::OCL_None:
2806 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2807 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2808 break;
2809 default:
2810 break;
2811 }
2812 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2813 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2814 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2815 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2816 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2817 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2818 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2819 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2820 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2821 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2822 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2823 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2824 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2825 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2826 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2827 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2828 }
2829 printf("\n");
2830 }
2831 }
2832 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2833 getIntSize(), "byref.flags");
2834
2835 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2836 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2837 storeHeaderField(V, getIntSize(), "byref.size");
2838
2839 if (helpers) {
2840 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2841 "byref.copyHelper");
2842 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2843 "byref.disposeHelper");
2844 }
2845
2846 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2847 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2848 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2849 }
2850}
2851
2852void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2853 bool CanThrow) {
2854 llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2855 llvm::Value *args[] = {
2856 Builder.CreateBitCast(V, Int8PtrTy),
2857 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2858 };
2859
2860 if (CanThrow)
2861 EmitRuntimeCallOrInvoke(F, args);
2862 else
2863 EmitNounwindRuntimeCall(F, args);
2864}
2865
2866void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2867 BlockFieldFlags Flags,
2868 bool LoadBlockVarAddr, bool CanThrow) {
2869 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2870 CanThrow);
2871}
2872
2873/// Adjust the declaration of something from the blocks API.
2874static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2875 llvm::Constant *C) {
2876 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2877
2878 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2879 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2880 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2881 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2882
2883 assert((isa<llvm::Function>(C->stripPointerCasts()) ||(((isa<llvm::Function>(C->stripPointerCasts()) || isa
<llvm::GlobalVariable>(C->stripPointerCasts())) &&
"expected Function or GlobalVariable") ? static_cast<void
> (0) : __assert_fail ("(isa<llvm::Function>(C->stripPointerCasts()) || isa<llvm::GlobalVariable>(C->stripPointerCasts())) && \"expected Function or GlobalVariable\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2885, __PRETTY_FUNCTION__))
2884 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&(((isa<llvm::Function>(C->stripPointerCasts()) || isa
<llvm::GlobalVariable>(C->stripPointerCasts())) &&
"expected Function or GlobalVariable") ? static_cast<void
> (0) : __assert_fail ("(isa<llvm::Function>(C->stripPointerCasts()) || isa<llvm::GlobalVariable>(C->stripPointerCasts())) && \"expected Function or GlobalVariable\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2885, __PRETTY_FUNCTION__))
2885 "expected Function or GlobalVariable")(((isa<llvm::Function>(C->stripPointerCasts()) || isa
<llvm::GlobalVariable>(C->stripPointerCasts())) &&
"expected Function or GlobalVariable") ? static_cast<void
> (0) : __assert_fail ("(isa<llvm::Function>(C->stripPointerCasts()) || isa<llvm::GlobalVariable>(C->stripPointerCasts())) && \"expected Function or GlobalVariable\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CGBlocks.cpp"
, 2885, __PRETTY_FUNCTION__))
;
2886
2887 const NamedDecl *ND = nullptr;
2888 for (const auto &Result : DC->lookup(&II))
2889 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2890 (ND = dyn_cast<VarDecl>(Result)))
2891 break;
2892
2893 // TODO: support static blocks runtime
2894 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2895 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2896 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2897 } else {
2898 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2899 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2900 }
2901 }
2902
2903 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2904 GV->hasExternalLinkage())
2905 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2906
2907 CGM.setDSOLocal(GV);
2908}
2909
2910llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2911 if (BlockObjectDispose)
2912 return BlockObjectDispose;
2913
2914 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2915 llvm::FunctionType *fty
2916 = llvm::FunctionType::get(VoidTy, args, false);
2917 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2918 configureBlocksRuntimeObject(
2919 *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2920 return BlockObjectDispose;
2921}
2922
2923llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2924 if (BlockObjectAssign)
2925 return BlockObjectAssign;
2926
2927 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2928 llvm::FunctionType *fty
2929 = llvm::FunctionType::get(VoidTy, args, false);
2930 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2931 configureBlocksRuntimeObject(
2932 *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
2933 return BlockObjectAssign;
2934}
2935
2936llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2937 if (NSConcreteGlobalBlock)
2938 return NSConcreteGlobalBlock;
2939
2940 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2941 Int8PtrTy->getPointerTo(),
2942 nullptr);
2943 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2944 return NSConcreteGlobalBlock;
2945}
2946
2947llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2948 if (NSConcreteStackBlock)
2949 return NSConcreteStackBlock;
2950
2951 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2952 Int8PtrTy->getPointerTo(),
2953 nullptr);
2954 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2955 return NSConcreteStackBlock;
2956}

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h

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