Bug Summary

File:clang/lib/CodeGen/CGBlocks.cpp
Warning:line 597, 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 _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/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~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -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-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGBlocks.cpp

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

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/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~++20201124111112+7b5254223ac/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~++20201124111112+7b5254223ac/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 this variable is known to have constant initialization. This is
807 /// currently only computed in C++, for static / thread storage duration
808 /// variables that might have constant initialization and for variables that
809 /// are usable in constant expressions.
810 bool HasConstantInitialization : 1;
811
812 /// Whether this variable is known to have constant destruction. That is,
813 /// whether running the destructor on the initial value is a side-effect
814 /// (and doesn't inspect any state that might have changed during program
815 /// execution). This is currently only computed if the destructor is
816 /// non-trivial.
817 bool HasConstantDestruction : 1;
818
819 /// In C++98, whether the initializer is an ICE. This affects whether the
820 /// variable is usable in constant expressions.
821 bool HasICEInit : 1;
822 bool CheckedForICEInit : 1;
823
824 Stmt *Value;
825 APValue Evaluated;
826
827 EvaluatedStmt()
828 : WasEvaluated(false), IsEvaluating(false),
829 HasConstantInitialization(false), HasConstantDestruction(false),
830 HasICEInit(false), CheckedForICEInit(false) {}
831};
832
833/// Represents a variable declaration or definition.
834class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
835public:
836 /// Initialization styles.
837 enum InitializationStyle {
838 /// C-style initialization with assignment
839 CInit,
840
841 /// Call-style initialization (C++98)
842 CallInit,
843
844 /// Direct list-initialization (C++11)
845 ListInit
846 };
847
848 /// Kinds of thread-local storage.
849 enum TLSKind {
850 /// Not a TLS variable.
851 TLS_None,
852
853 /// TLS with a known-constant initializer.
854 TLS_Static,
855
856 /// TLS with a dynamic initializer.
857 TLS_Dynamic
858 };
859
860 /// Return the string used to specify the storage class \p SC.
861 ///
862 /// It is illegal to call this function with SC == None.
863 static const char *getStorageClassSpecifierString(StorageClass SC);
864
865protected:
866 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
867 // have allocated the auxiliary struct of information there.
868 //
869 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
870 // this as *many* VarDecls are ParmVarDecls that don't have default
871 // arguments. We could save some space by moving this pointer union to be
872 // allocated in trailing space when necessary.
873 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
874
875 /// The initializer for this variable or, for a ParmVarDecl, the
876 /// C++ default argument.
877 mutable InitType Init;
878
879private:
880 friend class ASTDeclReader;
881 friend class ASTNodeImporter;
882 friend class StmtIteratorBase;
883
884 class VarDeclBitfields {
885 friend class ASTDeclReader;
886 friend class VarDecl;
887
888 unsigned SClass : 3;
889 unsigned TSCSpec : 2;
890 unsigned InitStyle : 2;
891
892 /// Whether this variable is an ARC pseudo-__strong variable; see
893 /// isARCPseudoStrong() for details.
894 unsigned ARCPseudoStrong : 1;
895 };
896 enum { NumVarDeclBits = 8 };
897
898protected:
899 enum { NumParameterIndexBits = 8 };
900
901 enum DefaultArgKind {
902 DAK_None,
903 DAK_Unparsed,
904 DAK_Uninstantiated,
905 DAK_Normal
906 };
907
908 enum { NumScopeDepthOrObjCQualsBits = 7 };
909
910 class ParmVarDeclBitfields {
911 friend class ASTDeclReader;
912 friend class ParmVarDecl;
913
914 unsigned : NumVarDeclBits;
915
916 /// Whether this parameter inherits a default argument from a
917 /// prior declaration.
918 unsigned HasInheritedDefaultArg : 1;
919
920 /// Describes the kind of default argument for this parameter. By default
921 /// this is none. If this is normal, then the default argument is stored in
922 /// the \c VarDecl initializer expression unless we were unable to parse
923 /// (even an invalid) expression for the default argument.
924 unsigned DefaultArgKind : 2;
925
926 /// Whether this parameter undergoes K&R argument promotion.
927 unsigned IsKNRPromoted : 1;
928
929 /// Whether this parameter is an ObjC method parameter or not.
930 unsigned IsObjCMethodParam : 1;
931
932 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
933 /// Otherwise, the number of function parameter scopes enclosing
934 /// the function parameter scope in which this parameter was
935 /// declared.
936 unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
937
938 /// The number of parameters preceding this parameter in the
939 /// function parameter scope in which it was declared.
940 unsigned ParameterIndex : NumParameterIndexBits;
941 };
942
943 class NonParmVarDeclBitfields {
944 friend class ASTDeclReader;
945 friend class ImplicitParamDecl;
946 friend class VarDecl;
947
948 unsigned : NumVarDeclBits;
949
950 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
951 /// Whether this variable is a definition which was demoted due to
952 /// module merge.
953 unsigned IsThisDeclarationADemotedDefinition : 1;
954
955 /// Whether this variable is the exception variable in a C++ catch
956 /// or an Objective-C @catch statement.
957 unsigned ExceptionVar : 1;
958
959 /// Whether this local variable could be allocated in the return
960 /// slot of its function, enabling the named return value optimization
961 /// (NRVO).
962 unsigned NRVOVariable : 1;
963
964 /// Whether this variable is the for-range-declaration in a C++0x
965 /// for-range statement.
966 unsigned CXXForRangeDecl : 1;
967
968 /// Whether this variable is the for-in loop declaration in Objective-C.
969 unsigned ObjCForDecl : 1;
970
971 /// Whether this variable is (C++1z) inline.
972 unsigned IsInline : 1;
973
974 /// Whether this variable has (C++1z) inline explicitly specified.
975 unsigned IsInlineSpecified : 1;
976
977 /// Whether this variable is (C++0x) constexpr.
978 unsigned IsConstexpr : 1;
979
980 /// Whether this variable is the implicit variable for a lambda
981 /// init-capture.
982 unsigned IsInitCapture : 1;
983
984 /// Whether this local extern variable's previous declaration was
985 /// declared in the same block scope. This controls whether we should merge
986 /// the type of this declaration with its previous declaration.
987 unsigned PreviousDeclInSameBlockScope : 1;
988
989 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
990 /// something else.
991 unsigned ImplicitParamKind : 3;
992
993 unsigned EscapingByref : 1;
994 };
995
996 union {
997 unsigned AllBits;
998 VarDeclBitfields VarDeclBits;
999 ParmVarDeclBitfields ParmVarDeclBits;
1000 NonParmVarDeclBitfields NonParmVarDeclBits;
1001 };
1002
1003 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1004 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1005 TypeSourceInfo *TInfo, StorageClass SC);
1006
1007 using redeclarable_base = Redeclarable<VarDecl>;
1008
1009 VarDecl *getNextRedeclarationImpl() override {
1010 return getNextRedeclaration();
1011 }
1012
1013 VarDecl *getPreviousDeclImpl() override {
1014 return getPreviousDecl();
1015 }
1016
1017 VarDecl *getMostRecentDeclImpl() override {
1018 return getMostRecentDecl();
1019 }
1020
1021public:
1022 using redecl_range = redeclarable_base::redecl_range;
1023 using redecl_iterator = redeclarable_base::redecl_iterator;
1024
1025 using redeclarable_base::redecls_begin;
1026 using redeclarable_base::redecls_end;
1027 using redeclarable_base::redecls;
1028 using redeclarable_base::getPreviousDecl;
1029 using redeclarable_base::getMostRecentDecl;
1030 using redeclarable_base::isFirstDecl;
1031
1032 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1033 SourceLocation StartLoc, SourceLocation IdLoc,
1034 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1035 StorageClass S);
1036
1037 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1038
1039 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1040
1041 /// Returns the storage class as written in the source. For the
1042 /// computed linkage of symbol, see getLinkage.
1043 StorageClass getStorageClass() const {
1044 return (StorageClass) VarDeclBits.SClass;
1045 }
1046 void setStorageClass(StorageClass SC);
1047
1048 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1049 VarDeclBits.TSCSpec = TSC;
1050 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1050, __PRETTY_FUNCTION__))
;
1051 }
1052 ThreadStorageClassSpecifier getTSCSpec() const {
1053 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1054 }
1055 TLSKind getTLSKind() const;
1056
1057 /// Returns true if a variable with function scope is a non-static local
1058 /// variable.
1059 bool hasLocalStorage() const {
1060 if (getStorageClass() == SC_None) {
1061 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1062 // used to describe variables allocated in global memory and which are
1063 // accessed inside a kernel(s) as read-only variables. As such, variables
1064 // in constant address space cannot have local storage.
1065 if (getType().getAddressSpace() == LangAS::opencl_constant)
1066 return false;
1067 // Second check is for C++11 [dcl.stc]p4.
1068 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1069 }
1070
1071 // Global Named Register (GNU extension)
1072 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1073 return false;
1074
1075 // Return true for: Auto, Register.
1076 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1077
1078 return getStorageClass() >= SC_Auto;
1079 }
1080
1081 /// Returns true if a variable with function scope is a static local
1082 /// variable.
1083 bool isStaticLocal() const {
1084 return (getStorageClass() == SC_Static ||
1085 // C++11 [dcl.stc]p4
1086 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1087 && !isFileVarDecl();
1088 }
1089
1090 /// Returns true if a variable has extern or __private_extern__
1091 /// storage.
1092 bool hasExternalStorage() const {
1093 return getStorageClass() == SC_Extern ||
1094 getStorageClass() == SC_PrivateExtern;
1095 }
1096
1097 /// Returns true for all variables that do not have local storage.
1098 ///
1099 /// This includes all global variables as well as static variables declared
1100 /// within a function.
1101 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1102
1103 /// Get the storage duration of this variable, per C++ [basic.stc].
1104 StorageDuration getStorageDuration() const {
1105 return hasLocalStorage() ? SD_Automatic :
1106 getTSCSpec() ? SD_Thread : SD_Static;
1107 }
1108
1109 /// Compute the language linkage.
1110 LanguageLinkage getLanguageLinkage() const;
1111
1112 /// Determines whether this variable is a variable with external, C linkage.
1113 bool isExternC() const;
1114
1115 /// Determines whether this variable's context is, or is nested within,
1116 /// a C++ extern "C" linkage spec.
1117 bool isInExternCContext() const;
1118
1119 /// Determines whether this variable's context is, or is nested within,
1120 /// a C++ extern "C++" linkage spec.
1121 bool isInExternCXXContext() const;
1122
1123 /// Returns true for local variable declarations other than parameters.
1124 /// Note that this includes static variables inside of functions. It also
1125 /// includes variables inside blocks.
1126 ///
1127 /// void foo() { int x; static int y; extern int z; }
1128 bool isLocalVarDecl() const {
1129 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1130 return false;
1131 if (const DeclContext *DC = getLexicalDeclContext())
1132 return DC->getRedeclContext()->isFunctionOrMethod();
1133 return false;
1134 }
1135
1136 /// Similar to isLocalVarDecl but also includes parameters.
1137 bool isLocalVarDeclOrParm() const {
1138 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1139 }
1140
1141 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1142 bool isFunctionOrMethodVarDecl() const {
1143 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1144 return false;
1145 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1146 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1147 }
1148
1149 /// Determines whether this is a static data member.
1150 ///
1151 /// This will only be true in C++, and applies to, e.g., the
1152 /// variable 'x' in:
1153 /// \code
1154 /// struct S {
1155 /// static int x;
1156 /// };
1157 /// \endcode
1158 bool isStaticDataMember() const {
1159 // If it wasn't static, it would be a FieldDecl.
1160 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1161 }
1162
1163 VarDecl *getCanonicalDecl() override;
1164 const VarDecl *getCanonicalDecl() const {
1165 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1166 }
1167
1168 enum DefinitionKind {
1169 /// This declaration is only a declaration.
1170 DeclarationOnly,
1171
1172 /// This declaration is a tentative definition.
1173 TentativeDefinition,
1174
1175 /// This declaration is definitely a definition.
1176 Definition
1177 };
1178
1179 /// Check whether this declaration is a definition. If this could be
1180 /// a tentative definition (in C), don't check whether there's an overriding
1181 /// definition.
1182 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1183 DefinitionKind isThisDeclarationADefinition() const {
1184 return isThisDeclarationADefinition(getASTContext());
1185 }
1186
1187 /// Check whether this variable is defined in this translation unit.
1188 DefinitionKind hasDefinition(ASTContext &) const;
1189 DefinitionKind hasDefinition() const {
1190 return hasDefinition(getASTContext());
1191 }
1192
1193 /// Get the tentative definition that acts as the real definition in a TU.
1194 /// Returns null if there is a proper definition available.
1195 VarDecl *getActingDefinition();
1196 const VarDecl *getActingDefinition() const {
1197 return const_cast<VarDecl*>(this)->getActingDefinition();
1198 }
1199
1200 /// Get the real (not just tentative) definition for this declaration.
1201 VarDecl *getDefinition(ASTContext &);
1202 const VarDecl *getDefinition(ASTContext &C) const {
1203 return const_cast<VarDecl*>(this)->getDefinition(C);
1204 }
1205 VarDecl *getDefinition() {
1206 return getDefinition(getASTContext());
1207 }
1208 const VarDecl *getDefinition() const {
1209 return const_cast<VarDecl*>(this)->getDefinition();
1210 }
1211
1212 /// Determine whether this is or was instantiated from an out-of-line
1213 /// definition of a static data member.
1214 bool isOutOfLine() const override;
1215
1216 /// Returns true for file scoped variable declaration.
1217 bool isFileVarDecl() const {
1218 Kind K = getKind();
1219 if (K == ParmVar || K == ImplicitParam)
1220 return false;
1221
1222 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1223 return true;
1224
1225 if (isStaticDataMember())
1226 return true;
1227
1228 return false;
1229 }
1230
1231 /// Get the initializer for this variable, no matter which
1232 /// declaration it is attached to.
1233 const Expr *getAnyInitializer() const {
1234 const VarDecl *D;
1235 return getAnyInitializer(D);
1236 }
1237
1238 /// Get the initializer for this variable, no matter which
1239 /// declaration it is attached to. Also get that declaration.
1240 const Expr *getAnyInitializer(const VarDecl *&D) const;
1241
1242 bool hasInit() const;
1243 const Expr *getInit() const {
1244 return const_cast<VarDecl *>(this)->getInit();
1245 }
1246 Expr *getInit();
1247
1248 /// Retrieve the address of the initializer expression.
1249 Stmt **getInitAddress();
1250
1251 void setInit(Expr *I);
1252
1253 /// Get the initializing declaration of this variable, if any. This is
1254 /// usually the definition, except that for a static data member it can be
1255 /// the in-class declaration.
1256 VarDecl *getInitializingDeclaration();
1257 const VarDecl *getInitializingDeclaration() const {
1258 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1259 }
1260
1261 /// Determine whether this variable's value might be usable in a
1262 /// constant expression, according to the relevant language standard.
1263 /// This only checks properties of the declaration, and does not check
1264 /// whether the initializer is in fact a constant expression.
1265 bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
1266
1267 /// Determine whether this variable's value can be used in a
1268 /// constant expression, according to the relevant language standard,
1269 /// including checking whether it was initialized by a constant expression.
1270 bool isUsableInConstantExpressions(const ASTContext &C) const;
1271
1272 EvaluatedStmt *ensureEvaluatedStmt() const;
1273 EvaluatedStmt *getEvaluatedStmt() 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.
1277 /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
1278 APValue *evaluateValue() const;
1279
1280private:
1281 APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
1282 bool IsConstantInitialization) const;
1283
1284public:
1285 /// Return the already-evaluated value of this variable's
1286 /// initializer, or NULL if the value is not yet known. Returns pointer
1287 /// to untyped APValue if the value could not be evaluated.
1288 APValue *getEvaluatedValue() const;
1289
1290 /// Evaluate the destruction of this variable to determine if it constitutes
1291 /// constant destruction.
1292 ///
1293 /// \pre hasConstantInitialization()
1294 /// \return \c true if this variable has constant destruction, \c false if
1295 /// not.
1296 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1297
1298 /// Determine whether this variable has constant initialization.
1299 ///
1300 /// This is only set in two cases: when the language semantics require
1301 /// constant initialization (globals in C and some globals in C++), and when
1302 /// the variable is usable in constant expressions (constexpr, const int, and
1303 /// reference variables in C++).
1304 bool hasConstantInitialization() const;
1305
1306 /// Determine whether the initializer of this variable is an integer constant
1307 /// expression. For use in C++98, where this affects whether the variable is
1308 /// usable in constant expressions.
1309 bool hasICEInitializer(const ASTContext &Context) const;
1310
1311 /// Evaluate the initializer of this variable to determine whether it's a
1312 /// constant initializer. Should only be called once, after completing the
1313 /// definition of the variable.
1314 bool checkForConstantInitialization(
1315 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1316
1317 void setInitStyle(InitializationStyle Style) {
1318 VarDeclBits.InitStyle = Style;
1319 }
1320
1321 /// The style of initialization for this declaration.
1322 ///
1323 /// C-style initialization is "int x = 1;". Call-style initialization is
1324 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1325 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1326 /// expression for class types. List-style initialization is C++11 syntax,
1327 /// e.g. "int x{1};". Clients can distinguish between different forms of
1328 /// initialization by checking this value. In particular, "int x = {1};" is
1329 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1330 /// Init expression in all three cases is an InitListExpr.
1331 InitializationStyle getInitStyle() const {
1332 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1333 }
1334
1335 /// Whether the initializer is a direct-initializer (list or call).
1336 bool isDirectInit() const {
1337 return getInitStyle() != CInit;
1338 }
1339
1340 /// If this definition should pretend to be a declaration.
1341 bool isThisDeclarationADemotedDefinition() const {
1342 return isa<ParmVarDecl>(this) ? false :
1343 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1344 }
1345
1346 /// This is a definition which should be demoted to a declaration.
1347 ///
1348 /// In some cases (mostly module merging) we can end up with two visible
1349 /// definitions one of which needs to be demoted to a declaration to keep
1350 /// the AST invariants.
1351 void demoteThisDefinitionToDeclaration() {
1352 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1353, __PRETTY_FUNCTION__))
;
1354 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1355 }
1356
1357 /// Determine whether this variable is the exception variable in a
1358 /// C++ catch statememt or an Objective-C \@catch statement.
1359 bool isExceptionVariable() const {
1360 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1361 }
1362 void setExceptionVariable(bool EV) {
1363 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1363, __PRETTY_FUNCTION__))
;
1364 NonParmVarDeclBits.ExceptionVar = EV;
1365 }
1366
1367 /// Determine whether this local variable can be used with the named
1368 /// return value optimization (NRVO).
1369 ///
1370 /// The named return value optimization (NRVO) works by marking certain
1371 /// non-volatile local variables of class type as NRVO objects. These
1372 /// locals can be allocated within the return slot of their containing
1373 /// function, in which case there is no need to copy the object to the
1374 /// return slot when returning from the function. Within the function body,
1375 /// each return that returns the NRVO object will have this variable as its
1376 /// NRVO candidate.
1377 bool isNRVOVariable() const {
1378 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1379 }
1380 void setNRVOVariable(bool NRVO) {
1381 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1381, __PRETTY_FUNCTION__))
;
1382 NonParmVarDeclBits.NRVOVariable = NRVO;
1383 }
1384
1385 /// Determine whether this variable is the for-range-declaration in
1386 /// a C++0x for-range statement.
1387 bool isCXXForRangeDecl() const {
1388 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1389 }
1390 void setCXXForRangeDecl(bool FRD) {
1391 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1391, __PRETTY_FUNCTION__))
;
1392 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1393 }
1394
1395 /// Determine whether this variable is a for-loop declaration for a
1396 /// for-in statement in Objective-C.
1397 bool isObjCForDecl() const {
1398 return NonParmVarDeclBits.ObjCForDecl;
1399 }
1400
1401 void setObjCForDecl(bool FRD) {
1402 NonParmVarDeclBits.ObjCForDecl = FRD;
1403 }
1404
1405 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1406 /// pseudo-__strong variable has a __strong-qualified type but does not
1407 /// actually retain the object written into it. Generally such variables are
1408 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1409 /// the variable is annotated with the objc_externally_retained attribute, 2)
1410 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1411 /// loop.
1412 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1413 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1414
1415 /// Whether this variable is (C++1z) inline.
1416 bool isInline() const {
1417 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1418 }
1419 bool isInlineSpecified() const {
1420 return isa<ParmVarDecl>(this) ? false
1421 : NonParmVarDeclBits.IsInlineSpecified;
1422 }
1423 void setInlineSpecified() {
1424 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1424, __PRETTY_FUNCTION__))
;
1425 NonParmVarDeclBits.IsInline = true;
1426 NonParmVarDeclBits.IsInlineSpecified = true;
1427 }
1428 void setImplicitlyInline() {
1429 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1429, __PRETTY_FUNCTION__))
;
1430 NonParmVarDeclBits.IsInline = true;
1431 }
1432
1433 /// Whether this variable is (C++11) constexpr.
1434 bool isConstexpr() const {
1435 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1436 }
1437 void setConstexpr(bool IC) {
1438 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1438, __PRETTY_FUNCTION__))
;
1439 NonParmVarDeclBits.IsConstexpr = IC;
1440 }
1441
1442 /// Whether this variable is the implicit variable for a lambda init-capture.
1443 bool isInitCapture() const {
1444 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1445 }
1446 void setInitCapture(bool IC) {
1447 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1447, __PRETTY_FUNCTION__))
;
1448 NonParmVarDeclBits.IsInitCapture = IC;
1449 }
1450
1451 /// Determine whether this variable is actually a function parameter pack or
1452 /// init-capture pack.
1453 bool isParameterPack() const;
1454
1455 /// Whether this local extern variable declaration's previous declaration
1456 /// was declared in the same block scope. Only correct in C++.
1457 bool isPreviousDeclInSameBlockScope() const {
1458 return isa<ParmVarDecl>(this)
1459 ? false
1460 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1461 }
1462 void setPreviousDeclInSameBlockScope(bool Same) {
1463 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1463, __PRETTY_FUNCTION__))
;
1464 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1465 }
1466
1467 /// Indicates the capture is a __block variable that is captured by a block
1468 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1469 /// returns false).
1470 bool isEscapingByref() const;
1471
1472 /// Indicates the capture is a __block variable that is never captured by an
1473 /// escaping block.
1474 bool isNonEscapingByref() const;
1475
1476 void setEscapingByref() {
1477 NonParmVarDeclBits.EscapingByref = true;
1478 }
1479
1480 /// Retrieve the variable declaration from which this variable could
1481 /// be instantiated, if it is an instantiation (rather than a non-template).
1482 VarDecl *getTemplateInstantiationPattern() const;
1483
1484 /// If this variable is an instantiated static data member of a
1485 /// class template specialization, returns the templated static data member
1486 /// from which it was instantiated.
1487 VarDecl *getInstantiatedFromStaticDataMember() const;
1488
1489 /// If this variable is an instantiation of a variable template or a
1490 /// static data member of a class template, determine what kind of
1491 /// template specialization or instantiation this is.
1492 TemplateSpecializationKind getTemplateSpecializationKind() const;
1493
1494 /// Get the template specialization kind of this variable for the purposes of
1495 /// template instantiation. This differs from getTemplateSpecializationKind()
1496 /// for an instantiation of a class-scope explicit specialization.
1497 TemplateSpecializationKind
1498 getTemplateSpecializationKindForInstantiation() const;
1499
1500 /// If this variable is an instantiation of a variable template or a
1501 /// static data member of a class template, determine its point of
1502 /// instantiation.
1503 SourceLocation getPointOfInstantiation() const;
1504
1505 /// If this variable is an instantiation of a static data member of a
1506 /// class template specialization, retrieves the member specialization
1507 /// information.
1508 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1509
1510 /// For a static data member that was instantiated from a static
1511 /// data member of a class template, set the template specialiation kind.
1512 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1513 SourceLocation PointOfInstantiation = SourceLocation());
1514
1515 /// Specify that this variable is an instantiation of the
1516 /// static data member VD.
1517 void setInstantiationOfStaticDataMember(VarDecl *VD,
1518 TemplateSpecializationKind TSK);
1519
1520 /// Retrieves the variable template that is described by this
1521 /// variable declaration.
1522 ///
1523 /// Every variable template is represented as a VarTemplateDecl and a
1524 /// VarDecl. The former contains template properties (such as
1525 /// the template parameter lists) while the latter contains the
1526 /// actual description of the template's
1527 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1528 /// VarDecl that from a VarTemplateDecl, while
1529 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1530 /// a VarDecl.
1531 VarTemplateDecl *getDescribedVarTemplate() const;
1532
1533 void setDescribedVarTemplate(VarTemplateDecl *Template);
1534
1535 // Is this variable known to have a definition somewhere in the complete
1536 // program? This may be true even if the declaration has internal linkage and
1537 // has no definition within this source file.
1538 bool isKnownToBeDefined() const;
1539
1540 /// Is destruction of this variable entirely suppressed? If so, the variable
1541 /// need not have a usable destructor at all.
1542 bool isNoDestroy(const ASTContext &) const;
1543
1544 /// Would the destruction of this variable have any effect, and if so, what
1545 /// kind?
1546 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1547
1548 // Implement isa/cast/dyncast/etc.
1549 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1550 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1551};
1552
1553class ImplicitParamDecl : public VarDecl {
1554 void anchor() override;
1555
1556public:
1557 /// Defines the kind of the implicit parameter: is this an implicit parameter
1558 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1559 /// context or something else.
1560 enum ImplicitParamKind : unsigned {
1561 /// Parameter for Objective-C 'self' argument
1562 ObjCSelf,
1563
1564 /// Parameter for Objective-C '_cmd' argument
1565 ObjCCmd,
1566
1567 /// Parameter for C++ 'this' argument
1568 CXXThis,
1569
1570 /// Parameter for C++ virtual table pointers
1571 CXXVTT,
1572
1573 /// Parameter for captured context
1574 CapturedContext,
1575
1576 /// Other implicit parameter
1577 Other,
1578 };
1579
1580 /// Create implicit parameter.
1581 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1582 SourceLocation IdLoc, IdentifierInfo *Id,
1583 QualType T, ImplicitParamKind ParamKind);
1584 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1585 ImplicitParamKind ParamKind);
1586
1587 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1588
1589 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1590 IdentifierInfo *Id, QualType Type,
1591 ImplicitParamKind ParamKind)
1592 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1593 /*TInfo=*/nullptr, SC_None) {
1594 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1595 setImplicit();
1596 }
1597
1598 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1599 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1600 SourceLocation(), /*Id=*/nullptr, Type,
1601 /*TInfo=*/nullptr, SC_None) {
1602 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1603 setImplicit();
1604 }
1605
1606 /// Returns the implicit parameter kind.
1607 ImplicitParamKind getParameterKind() const {
1608 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1609 }
1610
1611 // Implement isa/cast/dyncast/etc.
1612 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1613 static bool classofKind(Kind K) { return K == ImplicitParam; }
1614};
1615
1616/// Represents a parameter to a function.
1617class ParmVarDecl : public VarDecl {
1618public:
1619 enum { MaxFunctionScopeDepth = 255 };
1620 enum { MaxFunctionScopeIndex = 255 };
1621
1622protected:
1623 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1624 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1625 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1626 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1627 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1627, __PRETTY_FUNCTION__))
;
1628 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1628, __PRETTY_FUNCTION__))
;
1629 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1629, __PRETTY_FUNCTION__))
;
1630 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1630, __PRETTY_FUNCTION__))
;
1631 setDefaultArg(DefArg);
1632 }
1633
1634public:
1635 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1636 SourceLocation StartLoc,
1637 SourceLocation IdLoc, IdentifierInfo *Id,
1638 QualType T, TypeSourceInfo *TInfo,
1639 StorageClass S, Expr *DefArg);
1640
1641 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1642
1643 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1644
1645 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1646 ParmVarDeclBits.IsObjCMethodParam = true;
1647 setParameterIndex(parameterIndex);
1648 }
1649
1650 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1651 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1651, __PRETTY_FUNCTION__))
;
1652
1653 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1654 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1655, __PRETTY_FUNCTION__))
1655 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1655, __PRETTY_FUNCTION__))
;
1656
1657 setParameterIndex(parameterIndex);
1658 }
1659
1660 bool isObjCMethodParameter() const {
1661 return ParmVarDeclBits.IsObjCMethodParam;
1662 }
1663
1664 unsigned getFunctionScopeDepth() const {
1665 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1666 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1667 }
1668
1669 static constexpr unsigned getMaxFunctionScopeDepth() {
1670 return (1u << NumScopeDepthOrObjCQualsBits) - 1;
1671 }
1672
1673 /// Returns the index of this parameter in its prototype or method scope.
1674 unsigned getFunctionScopeIndex() const {
1675 return getParameterIndex();
1676 }
1677
1678 ObjCDeclQualifier getObjCDeclQualifier() const {
1679 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1680 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1681 }
1682 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1683 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1683, __PRETTY_FUNCTION__))
;
1684 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1685 }
1686
1687 /// True if the value passed to this parameter must undergo
1688 /// K&R-style default argument promotion:
1689 ///
1690 /// C99 6.5.2.2.
1691 /// If the expression that denotes the called function has a type
1692 /// that does not include a prototype, the integer promotions are
1693 /// performed on each argument, and arguments that have type float
1694 /// are promoted to double.
1695 bool isKNRPromoted() const {
1696 return ParmVarDeclBits.IsKNRPromoted;
1697 }
1698 void setKNRPromoted(bool promoted) {
1699 ParmVarDeclBits.IsKNRPromoted = promoted;
1700 }
1701
1702 Expr *getDefaultArg();
1703 const Expr *getDefaultArg() const {
1704 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1705 }
1706
1707 void setDefaultArg(Expr *defarg);
1708
1709 /// Retrieve the source range that covers the entire default
1710 /// argument.
1711 SourceRange getDefaultArgRange() const;
1712 void setUninstantiatedDefaultArg(Expr *arg);
1713 Expr *getUninstantiatedDefaultArg();
1714 const Expr *getUninstantiatedDefaultArg() const {
1715 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1716 }
1717
1718 /// Determines whether this parameter has a default argument,
1719 /// either parsed or not.
1720 bool hasDefaultArg() const;
1721
1722 /// Determines whether this parameter has a default argument that has not
1723 /// yet been parsed. This will occur during the processing of a C++ class
1724 /// whose member functions have default arguments, e.g.,
1725 /// @code
1726 /// class X {
1727 /// public:
1728 /// void f(int x = 17); // x has an unparsed default argument now
1729 /// }; // x has a regular default argument now
1730 /// @endcode
1731 bool hasUnparsedDefaultArg() const {
1732 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1733 }
1734
1735 bool hasUninstantiatedDefaultArg() const {
1736 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1737 }
1738
1739 /// Specify that this parameter has an unparsed default argument.
1740 /// The argument will be replaced with a real default argument via
1741 /// setDefaultArg when the class definition enclosing the function
1742 /// declaration that owns this default argument is completed.
1743 void setUnparsedDefaultArg() {
1744 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1745 }
1746
1747 bool hasInheritedDefaultArg() const {
1748 return ParmVarDeclBits.HasInheritedDefaultArg;
1749 }
1750
1751 void setHasInheritedDefaultArg(bool I = true) {
1752 ParmVarDeclBits.HasInheritedDefaultArg = I;
1753 }
1754
1755 QualType getOriginalType() const;
1756
1757 /// Sets the function declaration that owns this
1758 /// ParmVarDecl. Since ParmVarDecls are often created before the
1759 /// FunctionDecls that own them, this routine is required to update
1760 /// the DeclContext appropriately.
1761 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1762
1763 // Implement isa/cast/dyncast/etc.
1764 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1765 static bool classofKind(Kind K) { return K == ParmVar; }
1766
1767private:
1768 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1769
1770 void setParameterIndex(unsigned parameterIndex) {
1771 if (parameterIndex >= ParameterIndexSentinel) {
1772 setParameterIndexLarge(parameterIndex);
1773 return;
1774 }
1775
1776 ParmVarDeclBits.ParameterIndex = parameterIndex;
1777 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 1777, __PRETTY_FUNCTION__))
;
1778 }
1779 unsigned getParameterIndex() const {
1780 unsigned d = ParmVarDeclBits.ParameterIndex;
1781 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1782 }
1783
1784 void setParameterIndexLarge(unsigned parameterIndex);
1785 unsigned getParameterIndexLarge() const;
1786};
1787
1788enum class MultiVersionKind {
1789 None,
1790 Target,
1791 CPUSpecific,
1792 CPUDispatch
1793};
1794
1795/// Represents a function declaration or definition.
1796///
1797/// Since a given function can be declared several times in a program,
1798/// there may be several FunctionDecls that correspond to that
1799/// function. Only one of those FunctionDecls will be found when
1800/// traversing the list of declarations in the context of the
1801/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1802/// contains all of the information known about the function. Other,
1803/// previous declarations of the function are available via the
1804/// getPreviousDecl() chain.
1805class FunctionDecl : public DeclaratorDecl,
1806 public DeclContext,
1807 public Redeclarable<FunctionDecl> {
1808 // This class stores some data in DeclContext::FunctionDeclBits
1809 // to save some space. Use the provided accessors to access it.
1810public:
1811 /// The kind of templated function a FunctionDecl can be.
1812 enum TemplatedKind {
1813 // Not templated.
1814 TK_NonTemplate,
1815 // The pattern in a function template declaration.
1816 TK_FunctionTemplate,
1817 // A non-template function that is an instantiation or explicit
1818 // specialization of a member of a templated class.
1819 TK_MemberSpecialization,
1820 // An instantiation or explicit specialization of a function template.
1821 // Note: this might have been instantiated from a templated class if it
1822 // is a class-scope explicit specialization.
1823 TK_FunctionTemplateSpecialization,
1824 // A function template specialization that hasn't yet been resolved to a
1825 // particular specialized function template.
1826 TK_DependentFunctionTemplateSpecialization
1827 };
1828
1829 /// Stashed information about a defaulted function definition whose body has
1830 /// not yet been lazily generated.
1831 class DefaultedFunctionInfo final
1832 : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
1833 friend TrailingObjects;
1834 unsigned NumLookups;
1835
1836 public:
1837 static DefaultedFunctionInfo *Create(ASTContext &Context,
1838 ArrayRef<DeclAccessPair> Lookups);
1839 /// Get the unqualified lookup results that should be used in this
1840 /// defaulted function definition.
1841 ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
1842 return {getTrailingObjects<DeclAccessPair>(), NumLookups};
1843 }
1844 };
1845
1846private:
1847 /// A new[]'d array of pointers to VarDecls for the formal
1848 /// parameters of this function. This is null if a prototype or if there are
1849 /// no formals.
1850 ParmVarDecl **ParamInfo = nullptr;
1851
1852 /// The active member of this union is determined by
1853 /// FunctionDeclBits.HasDefaultedFunctionInfo.
1854 union {
1855 /// The body of the function.
1856 LazyDeclStmtPtr Body;
1857 /// Information about a future defaulted function definition.
1858 DefaultedFunctionInfo *DefaultedInfo;
1859 };
1860
1861 unsigned ODRHash;
1862
1863 /// End part of this FunctionDecl's source range.
1864 ///
1865 /// We could compute the full range in getSourceRange(). However, when we're
1866 /// dealing with a function definition deserialized from a PCH/AST file,
1867 /// we can only compute the full range once the function body has been
1868 /// de-serialized, so it's far better to have the (sometimes-redundant)
1869 /// EndRangeLoc.
1870 SourceLocation EndRangeLoc;
1871
1872 /// The template or declaration that this declaration
1873 /// describes or was instantiated from, respectively.
1874 ///
1875 /// For non-templates, this value will be NULL. For function
1876 /// declarations that describe a function template, this will be a
1877 /// pointer to a FunctionTemplateDecl. For member functions
1878 /// of class template specializations, this will be a MemberSpecializationInfo
1879 /// pointer containing information about the specialization.
1880 /// For function template specializations, this will be a
1881 /// FunctionTemplateSpecializationInfo, which contains information about
1882 /// the template being specialized and the template arguments involved in
1883 /// that specialization.
1884 llvm::PointerUnion<FunctionTemplateDecl *,
1885 MemberSpecializationInfo *,
1886 FunctionTemplateSpecializationInfo *,
1887 DependentFunctionTemplateSpecializationInfo *>
1888 TemplateOrSpecialization;
1889
1890 /// Provides source/type location info for the declaration name embedded in
1891 /// the DeclaratorDecl base class.
1892 DeclarationNameLoc DNLoc;
1893
1894 /// Specify that this function declaration is actually a function
1895 /// template specialization.
1896 ///
1897 /// \param C the ASTContext.
1898 ///
1899 /// \param Template the function template that this function template
1900 /// specialization specializes.
1901 ///
1902 /// \param TemplateArgs the template arguments that produced this
1903 /// function template specialization from the template.
1904 ///
1905 /// \param InsertPos If non-NULL, the position in the function template
1906 /// specialization set where the function template specialization data will
1907 /// be inserted.
1908 ///
1909 /// \param TSK the kind of template specialization this is.
1910 ///
1911 /// \param TemplateArgsAsWritten location info of template arguments.
1912 ///
1913 /// \param PointOfInstantiation point at which the function template
1914 /// specialization was first instantiated.
1915 void setFunctionTemplateSpecialization(ASTContext &C,
1916 FunctionTemplateDecl *Template,
1917 const TemplateArgumentList *TemplateArgs,
1918 void *InsertPos,
1919 TemplateSpecializationKind TSK,
1920 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1921 SourceLocation PointOfInstantiation);
1922
1923 /// Specify that this record is an instantiation of the
1924 /// member function FD.
1925 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1926 TemplateSpecializationKind TSK);
1927
1928 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1929
1930 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1931 // need to access this bit but we want to avoid making ASTDeclWriter
1932 // a friend of FunctionDeclBitfields just for this.
1933 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1934
1935 /// Whether an ODRHash has been stored.
1936 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1937
1938 /// State that an ODRHash has been stored.
1939 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1940
1941protected:
1942 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1943 const DeclarationNameInfo &NameInfo, QualType T,
1944 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1945 ConstexprSpecKind ConstexprKind,
1946 Expr *TrailingRequiresClause = nullptr);
1947
1948 using redeclarable_base = Redeclarable<FunctionDecl>;
1949
1950 FunctionDecl *getNextRedeclarationImpl() override {
1951 return getNextRedeclaration();
1952 }
1953
1954 FunctionDecl *getPreviousDeclImpl() override {
1955 return getPreviousDecl();
1956 }
1957
1958 FunctionDecl *getMostRecentDeclImpl() override {
1959 return getMostRecentDecl();
1960 }
1961
1962public:
1963 friend class ASTDeclReader;
1964 friend class ASTDeclWriter;
1965
1966 using redecl_range = redeclarable_base::redecl_range;
1967 using redecl_iterator = redeclarable_base::redecl_iterator;
1968
1969 using redeclarable_base::redecls_begin;
1970 using redeclarable_base::redecls_end;
1971 using redeclarable_base::redecls;
1972 using redeclarable_base::getPreviousDecl;
1973 using redeclarable_base::getMostRecentDecl;
1974 using redeclarable_base::isFirstDecl;
1975
1976 static FunctionDecl *
1977 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1978 SourceLocation NLoc, DeclarationName N, QualType T,
1979 TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1980 bool hasWrittenPrototype = true,
1981 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
1982 Expr *TrailingRequiresClause = nullptr) {
1983 DeclarationNameInfo NameInfo(N, NLoc);
1984 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1985 isInlineSpecified, hasWrittenPrototype,
1986 ConstexprKind, TrailingRequiresClause);
1987 }
1988
1989 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1990 SourceLocation StartLoc,
1991 const DeclarationNameInfo &NameInfo, QualType T,
1992 TypeSourceInfo *TInfo, StorageClass SC,
1993 bool isInlineSpecified, bool hasWrittenPrototype,
1994 ConstexprSpecKind ConstexprKind,
1995 Expr *TrailingRequiresClause);
1996
1997 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1998
1999 DeclarationNameInfo getNameInfo() const {
2000 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
2001 }
2002
2003 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2004 bool Qualified) const override;
2005
2006 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
2007
2008 /// Returns the location of the ellipsis of a variadic function.
2009 SourceLocation getEllipsisLoc() const {
2010 const auto *FPT = getType()->getAs<FunctionProtoType>();
2011 if (FPT && FPT->isVariadic())
2012 return FPT->getEllipsisLoc();
2013 return SourceLocation();
2014 }
2015
2016 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2017
2018 // Function definitions.
2019 //
2020 // A function declaration may be:
2021 // - a non defining declaration,
2022 // - a definition. A function may be defined because:
2023 // - it has a body, or will have it in the case of late parsing.
2024 // - it has an uninstantiated body. The body does not exist because the
2025 // function is not used yet, but the declaration is considered a
2026 // definition and does not allow other definition of this function.
2027 // - it does not have a user specified body, but it does not allow
2028 // redefinition, because it is deleted/defaulted or is defined through
2029 // some other mechanism (alias, ifunc).
2030
2031 /// Returns true if the function has a body.
2032 ///
2033 /// The function body might be in any of the (re-)declarations of this
2034 /// function. The variant that accepts a FunctionDecl pointer will set that
2035 /// function declaration to the actual declaration containing the body (if
2036 /// there is one).
2037 bool hasBody(const FunctionDecl *&Definition) const;
2038
2039 bool hasBody() const override {
2040 const FunctionDecl* Definition;
2041 return hasBody(Definition);
2042 }
2043
2044 /// Returns whether the function has a trivial body that does not require any
2045 /// specific codegen.
2046 bool hasTrivialBody() const;
2047
2048 /// Returns true if the function has a definition that does not need to be
2049 /// instantiated.
2050 ///
2051 /// The variant that accepts a FunctionDecl pointer will set that function
2052 /// declaration to the declaration that is a definition (if there is one).
2053 ///
2054 /// \param CheckForPendingFriendDefinition If \c true, also check for friend
2055 /// declarations that were instantiataed from function definitions.
2056 /// Such a declaration behaves as if it is a definition for the
2057 /// purpose of redefinition checking, but isn't actually a "real"
2058 /// definition until its body is instantiated.
2059 bool isDefined(const FunctionDecl *&Definition,
2060 bool CheckForPendingFriendDefinition = false) const;
2061
2062 bool isDefined() const {
2063 const FunctionDecl* Definition;
2064 return isDefined(Definition);
2065 }
2066
2067 /// Get the definition for this declaration.
2068 FunctionDecl *getDefinition() {
2069 const FunctionDecl *Definition;
2070 if (isDefined(Definition))
2071 return const_cast<FunctionDecl *>(Definition);
2072 return nullptr;
2073 }
2074 const FunctionDecl *getDefinition() const {
2075 return const_cast<FunctionDecl *>(this)->getDefinition();
2076 }
2077
2078 /// Retrieve the body (definition) of the function. The function body might be
2079 /// in any of the (re-)declarations of this function. The variant that accepts
2080 /// a FunctionDecl pointer will set that function declaration to the actual
2081 /// declaration containing the body (if there is one).
2082 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2083 /// unnecessary AST de-serialization of the body.
2084 Stmt *getBody(const FunctionDecl *&Definition) const;
2085
2086 Stmt *getBody() const override {
2087 const FunctionDecl* Definition;
2088 return getBody(Definition);
2089 }
2090
2091 /// Returns whether this specific declaration of the function is also a
2092 /// definition that does not contain uninstantiated body.
2093 ///
2094 /// This does not determine whether the function has been defined (e.g., in a
2095 /// previous definition); for that information, use isDefined.
2096 ///
2097 /// Note: the function declaration does not become a definition until the
2098 /// parser reaches the definition, if called before, this function will return
2099 /// `false`.
2100 bool isThisDeclarationADefinition() const {
2101 return isDeletedAsWritten() || isDefaulted() ||
2102 doesThisDeclarationHaveABody() || hasSkippedBody() ||
2103 willHaveBody() || hasDefiningAttr();
2104 }
2105
2106 /// Determine whether this specific declaration of the function is a friend
2107 /// declaration that was instantiated from a function definition. Such
2108 /// declarations behave like definitions in some contexts.
2109 bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
2110
2111 /// Returns whether this specific declaration of the function has a body.
2112 bool doesThisDeclarationHaveABody() const {
2113 return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
2114 isLateTemplateParsed();
2115 }
2116
2117 void setBody(Stmt *B);
2118 void setLazyBody(uint64_t Offset) {
2119 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2120 Body = LazyDeclStmtPtr(Offset);
2121 }
2122
2123 void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
2124 DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
2125
2126 /// Whether this function is variadic.
2127 bool isVariadic() const;
2128
2129 /// Whether this function is marked as virtual explicitly.
2130 bool isVirtualAsWritten() const {
2131 return FunctionDeclBits.IsVirtualAsWritten;
2132 }
2133
2134 /// State that this function is marked as virtual explicitly.
2135 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2136
2137 /// Whether this virtual function is pure, i.e. makes the containing class
2138 /// abstract.
2139 bool isPure() const { return FunctionDeclBits.IsPure; }
2140 void setPure(bool P = true);
2141
2142 /// Whether this templated function will be late parsed.
2143 bool isLateTemplateParsed() const {
2144 return FunctionDeclBits.IsLateTemplateParsed;
2145 }
2146
2147 /// State that this templated function will be late parsed.
2148 void setLateTemplateParsed(bool ILT = true) {
2149 FunctionDeclBits.IsLateTemplateParsed = ILT;
2150 }
2151
2152 /// Whether this function is "trivial" in some specialized C++ senses.
2153 /// Can only be true for default constructors, copy constructors,
2154 /// copy assignment operators, and destructors. Not meaningful until
2155 /// the class has been fully built by Sema.
2156 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2157 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2158
2159 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2160 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2161
2162 /// Whether this function is defaulted. Valid for e.g.
2163 /// special member functions, defaulted comparisions (not methods!).
2164 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2165 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2166
2167 /// Whether this function is explicitly defaulted.
2168 bool isExplicitlyDefaulted() const {
2169 return FunctionDeclBits.IsExplicitlyDefaulted;
2170 }
2171
2172 /// State that this function is explicitly defaulted.
2173 void setExplicitlyDefaulted(bool ED = true) {
2174 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2175 }
2176
2177 /// True if this method is user-declared and was not
2178 /// deleted or defaulted on its first declaration.
2179 bool isUserProvided() const {
2180 auto *DeclAsWritten = this;
2181 if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
2182 DeclAsWritten = Pattern;
2183 return !(DeclAsWritten->isDeleted() ||
2184 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2185 }
2186
2187 /// Whether falling off this function implicitly returns null/zero.
2188 /// If a more specific implicit return value is required, front-ends
2189 /// should synthesize the appropriate return statements.
2190 bool hasImplicitReturnZero() const {
2191 return FunctionDeclBits.HasImplicitReturnZero;
2192 }
2193
2194 /// State that falling off this function implicitly returns null/zero.
2195 /// If a more specific implicit return value is required, front-ends
2196 /// should synthesize the appropriate return statements.
2197 void setHasImplicitReturnZero(bool IRZ) {
2198 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2199 }
2200
2201 /// Whether this function has a prototype, either because one
2202 /// was explicitly written or because it was "inherited" by merging
2203 /// a declaration without a prototype with a declaration that has a
2204 /// prototype.
2205 bool hasPrototype() const {
2206 return hasWrittenPrototype() || hasInheritedPrototype();
2207 }
2208
2209 /// Whether this function has a written prototype.
2210 bool hasWrittenPrototype() const {
2211 return FunctionDeclBits.HasWrittenPrototype;
2212 }
2213
2214 /// State that this function has a written prototype.
2215 void setHasWrittenPrototype(bool P = true) {
2216 FunctionDeclBits.HasWrittenPrototype = P;
2217 }
2218
2219 /// Whether this function inherited its prototype from a
2220 /// previous declaration.
2221 bool hasInheritedPrototype() const {
2222 return FunctionDeclBits.HasInheritedPrototype;
2223 }
2224
2225 /// State that this function inherited its prototype from a
2226 /// previous declaration.
2227 void setHasInheritedPrototype(bool P = true) {
2228 FunctionDeclBits.HasInheritedPrototype = P;
2229 }
2230
2231 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2232 bool isConstexpr() const {
2233 return getConstexprKind() != ConstexprSpecKind::Unspecified;
2234 }
2235 void setConstexprKind(ConstexprSpecKind CSK) {
2236 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
2237 }
2238 ConstexprSpecKind getConstexprKind() const {
2239 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2240 }
2241 bool isConstexprSpecified() const {
2242 return getConstexprKind() == ConstexprSpecKind::Constexpr;
2243 }
2244 bool isConsteval() const {
2245 return getConstexprKind() == ConstexprSpecKind::Consteval;
2246 }
2247
2248 /// Whether the instantiation of this function is pending.
2249 /// This bit is set when the decision to instantiate this function is made
2250 /// and unset if and when the function body is created. That leaves out
2251 /// cases where instantiation did not happen because the template definition
2252 /// was not seen in this TU. This bit remains set in those cases, under the
2253 /// assumption that the instantiation will happen in some other TU.
2254 bool instantiationIsPending() const {
2255 return FunctionDeclBits.InstantiationIsPending;
2256 }
2257
2258 /// State that the instantiation of this function is pending.
2259 /// (see instantiationIsPending)
2260 void setInstantiationIsPending(bool IC) {
2261 FunctionDeclBits.InstantiationIsPending = IC;
2262 }
2263
2264 /// Indicates the function uses __try.
2265 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2266 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2267
2268 /// Whether this function has been deleted.
2269 ///
2270 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2271 /// acts like a normal function, except that it cannot actually be
2272 /// called or have its address taken. Deleted functions are
2273 /// typically used in C++ overload resolution to attract arguments
2274 /// whose type or lvalue/rvalue-ness would permit the use of a
2275 /// different overload that would behave incorrectly. For example,
2276 /// one might use deleted functions to ban implicit conversion from
2277 /// a floating-point number to an Integer type:
2278 ///
2279 /// @code
2280 /// struct Integer {
2281 /// Integer(long); // construct from a long
2282 /// Integer(double) = delete; // no construction from float or double
2283 /// Integer(long double) = delete; // no construction from long double
2284 /// };
2285 /// @endcode
2286 // If a function is deleted, its first declaration must be.
2287 bool isDeleted() const {
2288 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2289 }
2290
2291 bool isDeletedAsWritten() const {
2292 return FunctionDeclBits.IsDeleted && !isDefaulted();
2293 }
2294
2295 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2296
2297 /// Determines whether this function is "main", which is the
2298 /// entry point into an executable program.
2299 bool isMain() const;
2300
2301 /// Determines whether this function is a MSVCRT user defined entry
2302 /// point.
2303 bool isMSVCRTEntryPoint() const;
2304
2305 /// Determines whether this operator new or delete is one
2306 /// of the reserved global placement operators:
2307 /// void *operator new(size_t, void *);
2308 /// void *operator new[](size_t, void *);
2309 /// void operator delete(void *, void *);
2310 /// void operator delete[](void *, void *);
2311 /// These functions have special behavior under [new.delete.placement]:
2312 /// These functions are reserved, a C++ program may not define
2313 /// functions that displace the versions in the Standard C++ library.
2314 /// The provisions of [basic.stc.dynamic] do not apply to these
2315 /// reserved placement forms of operator new and operator delete.
2316 ///
2317 /// This function must be an allocation or deallocation function.
2318 bool isReservedGlobalPlacementOperator() const;
2319
2320 /// Determines whether this function is one of the replaceable
2321 /// global allocation functions:
2322 /// void *operator new(size_t);
2323 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2324 /// void *operator new[](size_t);
2325 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2326 /// void operator delete(void *) noexcept;
2327 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2328 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2329 /// void operator delete[](void *) noexcept;
2330 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2331 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2332 /// These functions have special behavior under C++1y [expr.new]:
2333 /// An implementation is allowed to omit a call to a replaceable global
2334 /// allocation function. [...]
2335 ///
2336 /// If this function is an aligned allocation/deallocation function, return
2337 /// the parameter number of the requested alignment through AlignmentParam.
2338 ///
2339 /// If this function is an allocation/deallocation function that takes
2340 /// the `std::nothrow_t` tag, return true through IsNothrow,
2341 bool isReplaceableGlobalAllocationFunction(
2342 Optional<unsigned> *AlignmentParam = nullptr,
2343 bool *IsNothrow = nullptr) const;
2344
2345 /// Determine if this function provides an inline implementation of a builtin.
2346 bool isInlineBuiltinDeclaration() const;
2347
2348 /// Determine whether this is a destroying operator delete.
2349 bool isDestroyingOperatorDelete() const;
2350
2351 /// Compute the language linkage.
2352 LanguageLinkage getLanguageLinkage() const;
2353
2354 /// Determines whether this function is a function with
2355 /// external, C linkage.
2356 bool isExternC() const;
2357
2358 /// Determines whether this function's context is, or is nested within,
2359 /// a C++ extern "C" linkage spec.
2360 bool isInExternCContext() const;
2361
2362 /// Determines whether this function's context is, or is nested within,
2363 /// a C++ extern "C++" linkage spec.
2364 bool isInExternCXXContext() const;
2365
2366 /// Determines whether this is a global function.
2367 bool isGlobal() const;
2368
2369 /// Determines whether this function is known to be 'noreturn', through
2370 /// an attribute on its declaration or its type.
2371 bool isNoReturn() const;
2372
2373 /// True if the function was a definition but its body was skipped.
2374 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2375 void setHasSkippedBody(bool Skipped = true) {
2376 FunctionDeclBits.HasSkippedBody = Skipped;
2377 }
2378
2379 /// True if this function will eventually have a body, once it's fully parsed.
2380 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2381 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2382
2383 /// True if this function is considered a multiversioned function.
2384 bool isMultiVersion() const {
2385 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2386 }
2387
2388 /// Sets the multiversion state for this declaration and all of its
2389 /// redeclarations.
2390 void setIsMultiVersion(bool V = true) {
2391 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2392 }
2393
2394 /// Gets the kind of multiversioning attribute this declaration has. Note that
2395 /// this can return a value even if the function is not multiversion, such as
2396 /// the case of 'target'.
2397 MultiVersionKind getMultiVersionKind() const;
2398
2399
2400 /// True if this function is a multiversioned dispatch function as a part of
2401 /// the cpu_specific/cpu_dispatch functionality.
2402 bool isCPUDispatchMultiVersion() const;
2403 /// True if this function is a multiversioned processor specific function as a
2404 /// part of the cpu_specific/cpu_dispatch functionality.
2405 bool isCPUSpecificMultiVersion() const;
2406
2407 /// True if this function is a multiversioned dispatch function as a part of
2408 /// the target functionality.
2409 bool isTargetMultiVersion() const;
2410
2411 /// \brief Get the associated-constraints of this function declaration.
2412 /// Currently, this will either be a vector of size 1 containing the
2413 /// trailing-requires-clause or an empty vector.
2414 ///
2415 /// Use this instead of getTrailingRequiresClause for concepts APIs that
2416 /// accept an ArrayRef of constraint expressions.
2417 void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
2418 if (auto *TRC = getTrailingRequiresClause())
2419 AC.push_back(TRC);
2420 }
2421
2422 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2423
2424 FunctionDecl *getCanonicalDecl() override;
2425 const FunctionDecl *getCanonicalDecl() const {
2426 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2427 }
2428
2429 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2430
2431 // ArrayRef interface to parameters.
2432 ArrayRef<ParmVarDecl *> parameters() const {
2433 return {ParamInfo, getNumParams()};
2434 }
2435 MutableArrayRef<ParmVarDecl *> parameters() {
2436 return {ParamInfo, getNumParams()};
2437 }
2438
2439 // Iterator access to formal parameters.
2440 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2441 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2442
2443 bool param_empty() const { return parameters().empty(); }
2444 param_iterator param_begin() { return parameters().begin(); }
2445 param_iterator param_end() { return parameters().end(); }
2446 param_const_iterator param_begin() const { return parameters().begin(); }
2447 param_const_iterator param_end() const { return parameters().end(); }
2448 size_t param_size() const { return parameters().size(); }
2449
2450 /// Return the number of parameters this function must have based on its
2451 /// FunctionType. This is the length of the ParamInfo array after it has been
2452 /// created.
2453 unsigned getNumParams() const;
2454
2455 const ParmVarDecl *getParamDecl(unsigned i) const {
2456 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2456, __PRETTY_FUNCTION__))
;
2457 return ParamInfo[i];
2458 }
2459 ParmVarDecl *getParamDecl(unsigned i) {
2460 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2460, __PRETTY_FUNCTION__))
;
2461 return ParamInfo[i];
2462 }
2463 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2464 setParams(getASTContext(), NewParamInfo);
2465 }
2466
2467 /// Returns the minimum number of arguments needed to call this function. This
2468 /// may be fewer than the number of function parameters, if some of the
2469 /// parameters have default arguments (in C++).
2470 unsigned getMinRequiredArguments() const;
2471
2472 /// Determine whether this function has a single parameter, or multiple
2473 /// parameters where all but the first have default arguments.
2474 ///
2475 /// This notion is used in the definition of copy/move constructors and
2476 /// initializer list constructors. Note that, unlike getMinRequiredArguments,
2477 /// parameter packs are not treated specially here.
2478 bool hasOneParamOrDefaultArgs() const;
2479
2480 /// Find the source location information for how the type of this function
2481 /// was written. May be absent (for example if the function was declared via
2482 /// a typedef) and may contain a different type from that of the function
2483 /// (for example if the function type was adjusted by an attribute).
2484 FunctionTypeLoc getFunctionTypeLoc() const;
2485
2486 QualType getReturnType() const {
2487 return getType()->castAs<FunctionType>()->getReturnType();
2488 }
2489
2490 /// Attempt to compute an informative source range covering the
2491 /// function return type. This may omit qualifiers and other information with
2492 /// limited representation in the AST.
2493 SourceRange getReturnTypeSourceRange() const;
2494
2495 /// Attempt to compute an informative source range covering the
2496 /// function parameters, including the ellipsis of a variadic function.
2497 /// The source range excludes the parentheses, and is invalid if there are
2498 /// no parameters and no ellipsis.
2499 SourceRange getParametersSourceRange() const;
2500
2501 /// Get the declared return type, which may differ from the actual return
2502 /// type if the return type is deduced.
2503 QualType getDeclaredReturnType() const {
2504 auto *TSI = getTypeSourceInfo();
2505 QualType T = TSI ? TSI->getType() : getType();
2506 return T->castAs<FunctionType>()->getReturnType();
2507 }
2508
2509 /// Gets the ExceptionSpecificationType as declared.
2510 ExceptionSpecificationType getExceptionSpecType() const {
2511 auto *TSI = getTypeSourceInfo();
2512 QualType T = TSI ? TSI->getType() : getType();
2513 const auto *FPT = T->getAs<FunctionProtoType>();
2514 return FPT ? FPT->getExceptionSpecType() : EST_None;
2515 }
2516
2517 /// Attempt to compute an informative source range covering the
2518 /// function exception specification, if any.
2519 SourceRange getExceptionSpecSourceRange() const;
2520
2521 /// Determine the type of an expression that calls this function.
2522 QualType getCallResultType() const {
2523 return getType()->castAs<FunctionType>()->getCallResultType(
2524 getASTContext());
2525 }
2526
2527 /// Returns the storage class as written in the source. For the
2528 /// computed linkage of symbol, see getLinkage.
2529 StorageClass getStorageClass() const {
2530 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2531 }
2532
2533 /// Sets the storage class as written in the source.
2534 void setStorageClass(StorageClass SClass) {
2535 FunctionDeclBits.SClass = SClass;
2536 }
2537
2538 /// Determine whether the "inline" keyword was specified for this
2539 /// function.
2540 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2541
2542 /// Set whether the "inline" keyword was specified for this function.
2543 void setInlineSpecified(bool I) {
2544 FunctionDeclBits.IsInlineSpecified = I;
2545 FunctionDeclBits.IsInline = I;
2546 }
2547
2548 /// Flag that this function is implicitly inline.
2549 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2550
2551 /// Determine whether this function should be inlined, because it is
2552 /// either marked "inline" or "constexpr" or is a member function of a class
2553 /// that was defined in the class body.
2554 bool isInlined() const { return FunctionDeclBits.IsInline; }
2555
2556 bool isInlineDefinitionExternallyVisible() const;
2557
2558 bool isMSExternInline() const;
2559
2560 bool doesDeclarationForceExternallyVisibleDefinition() const;
2561
2562 bool isStatic() const { return getStorageClass() == SC_Static; }
2563
2564 /// Whether this function declaration represents an C++ overloaded
2565 /// operator, e.g., "operator+".
2566 bool isOverloadedOperator() const {
2567 return getOverloadedOperator() != OO_None;
2568 }
2569
2570 OverloadedOperatorKind getOverloadedOperator() const;
2571
2572 const IdentifierInfo *getLiteralIdentifier() const;
2573
2574 /// If this function is an instantiation of a member function
2575 /// of a class template specialization, retrieves the function from
2576 /// which it was instantiated.
2577 ///
2578 /// This routine will return non-NULL for (non-templated) member
2579 /// functions of class templates and for instantiations of function
2580 /// templates. For example, given:
2581 ///
2582 /// \code
2583 /// template<typename T>
2584 /// struct X {
2585 /// void f(T);
2586 /// };
2587 /// \endcode
2588 ///
2589 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2590 /// whose parent is the class template specialization X<int>. For
2591 /// this declaration, getInstantiatedFromFunction() will return
2592 /// the FunctionDecl X<T>::A. When a complete definition of
2593 /// X<int>::A is required, it will be instantiated from the
2594 /// declaration returned by getInstantiatedFromMemberFunction().
2595 FunctionDecl *getInstantiatedFromMemberFunction() const;
2596
2597 /// What kind of templated function this is.
2598 TemplatedKind getTemplatedKind() const;
2599
2600 /// If this function is an instantiation of a member function of a
2601 /// class template specialization, retrieves the member specialization
2602 /// information.
2603 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2604
2605 /// Specify that this record is an instantiation of the
2606 /// member function FD.
2607 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2608 TemplateSpecializationKind TSK) {
2609 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2610 }
2611
2612 /// Retrieves the function template that is described by this
2613 /// function declaration.
2614 ///
2615 /// Every function template is represented as a FunctionTemplateDecl
2616 /// and a FunctionDecl (or something derived from FunctionDecl). The
2617 /// former contains template properties (such as the template
2618 /// parameter lists) while the latter contains the actual
2619 /// description of the template's
2620 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2621 /// FunctionDecl that describes the function template,
2622 /// getDescribedFunctionTemplate() retrieves the
2623 /// FunctionTemplateDecl from a FunctionDecl.
2624 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2625
2626 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2627
2628 /// Determine whether this function is a function template
2629 /// specialization.
2630 bool isFunctionTemplateSpecialization() const {
2631 return getPrimaryTemplate() != nullptr;
2632 }
2633
2634 /// If this function is actually a function template specialization,
2635 /// retrieve information about this function template specialization.
2636 /// Otherwise, returns NULL.
2637 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2638
2639 /// Determines whether this function is a function template
2640 /// specialization or a member of a class template specialization that can
2641 /// be implicitly instantiated.
2642 bool isImplicitlyInstantiable() const;
2643
2644 /// Determines if the given function was instantiated from a
2645 /// function template.
2646 bool isTemplateInstantiation() const;
2647
2648 /// Retrieve the function declaration from which this function could
2649 /// be instantiated, if it is an instantiation (rather than a non-template
2650 /// or a specialization, for example).
2651 ///
2652 /// If \p ForDefinition is \c false, explicit specializations will be treated
2653 /// as if they were implicit instantiations. This will then find the pattern
2654 /// corresponding to non-definition portions of the declaration, such as
2655 /// default arguments and the exception specification.
2656 FunctionDecl *
2657 getTemplateInstantiationPattern(bool ForDefinition = true) const;
2658
2659 /// Retrieve the primary template that this function template
2660 /// specialization either specializes or was instantiated from.
2661 ///
2662 /// If this function declaration is not a function template specialization,
2663 /// returns NULL.
2664 FunctionTemplateDecl *getPrimaryTemplate() const;
2665
2666 /// Retrieve the template arguments used to produce this function
2667 /// template specialization from the primary template.
2668 ///
2669 /// If this function declaration is not a function template specialization,
2670 /// returns NULL.
2671 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2672
2673 /// Retrieve the template argument list as written in the sources,
2674 /// if any.
2675 ///
2676 /// If this function declaration is not a function template specialization
2677 /// or if it had no explicit template argument list, returns NULL.
2678 /// Note that it an explicit template argument list may be written empty,
2679 /// e.g., template<> void foo<>(char* s);
2680 const ASTTemplateArgumentListInfo*
2681 getTemplateSpecializationArgsAsWritten() const;
2682
2683 /// Specify that this function declaration is actually a function
2684 /// template specialization.
2685 ///
2686 /// \param Template the function template that this function template
2687 /// specialization specializes.
2688 ///
2689 /// \param TemplateArgs the template arguments that produced this
2690 /// function template specialization from the template.
2691 ///
2692 /// \param InsertPos If non-NULL, the position in the function template
2693 /// specialization set where the function template specialization data will
2694 /// be inserted.
2695 ///
2696 /// \param TSK the kind of template specialization this is.
2697 ///
2698 /// \param TemplateArgsAsWritten location info of template arguments.
2699 ///
2700 /// \param PointOfInstantiation point at which the function template
2701 /// specialization was first instantiated.
2702 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2703 const TemplateArgumentList *TemplateArgs,
2704 void *InsertPos,
2705 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2706 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2707 SourceLocation PointOfInstantiation = SourceLocation()) {
2708 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2709 InsertPos, TSK, TemplateArgsAsWritten,
2710 PointOfInstantiation);
2711 }
2712
2713 /// Specifies that this function declaration is actually a
2714 /// dependent function template specialization.
2715 void setDependentTemplateSpecialization(ASTContext &Context,
2716 const UnresolvedSetImpl &Templates,
2717 const TemplateArgumentListInfo &TemplateArgs);
2718
2719 DependentFunctionTemplateSpecializationInfo *
2720 getDependentSpecializationInfo() const;
2721
2722 /// Determine what kind of template instantiation this function
2723 /// represents.
2724 TemplateSpecializationKind getTemplateSpecializationKind() const;
2725
2726 /// Determine the kind of template specialization this function represents
2727 /// for the purpose of template instantiation.
2728 TemplateSpecializationKind
2729 getTemplateSpecializationKindForInstantiation() const;
2730
2731 /// Determine what kind of template instantiation this function
2732 /// represents.
2733 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2734 SourceLocation PointOfInstantiation = SourceLocation());
2735
2736 /// Retrieve the (first) point of instantiation of a function template
2737 /// specialization or a member of a class template specialization.
2738 ///
2739 /// \returns the first point of instantiation, if this function was
2740 /// instantiated from a template; otherwise, returns an invalid source
2741 /// location.
2742 SourceLocation getPointOfInstantiation() const;
2743
2744 /// Determine whether this is or was instantiated from an out-of-line
2745 /// definition of a member function.
2746 bool isOutOfLine() const override;
2747
2748 /// Identify a memory copying or setting function.
2749 /// If the given function is a memory copy or setting function, returns
2750 /// the corresponding Builtin ID. If the function is not a memory function,
2751 /// returns 0.
2752 unsigned getMemoryFunctionKind() const;
2753
2754 /// Returns ODRHash of the function. This value is calculated and
2755 /// stored on first call, then the stored value returned on the other calls.
2756 unsigned getODRHash();
2757
2758 /// Returns cached ODRHash of the function. This must have been previously
2759 /// computed and stored.
2760 unsigned getODRHash() const;
2761
2762 // Implement isa/cast/dyncast/etc.
2763 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2764 static bool classofKind(Kind K) {
2765 return K >= firstFunction && K <= lastFunction;
2766 }
2767 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2768 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2769 }
2770 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2771 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2772 }
2773};
2774
2775/// Represents a member of a struct/union/class.
2776class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2777 unsigned BitField : 1;
2778 unsigned Mutable : 1;
2779 mutable unsigned CachedFieldIndex : 30;
2780
2781 /// The kinds of value we can store in InitializerOrBitWidth.
2782 ///
2783 /// Note that this is compatible with InClassInitStyle except for
2784 /// ISK_CapturedVLAType.
2785 enum InitStorageKind {
2786 /// If the pointer is null, there's nothing special. Otherwise,
2787 /// this is a bitfield and the pointer is the Expr* storing the
2788 /// bit-width.
2789 ISK_NoInit = (unsigned) ICIS_NoInit,
2790
2791 /// The pointer is an (optional due to delayed parsing) Expr*
2792 /// holding the copy-initializer.
2793 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2794
2795 /// The pointer is an (optional due to delayed parsing) Expr*
2796 /// holding the list-initializer.
2797 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2798
2799 /// The pointer is a VariableArrayType* that's been captured;
2800 /// the enclosing context is a lambda or captured statement.
2801 ISK_CapturedVLAType,
2802 };
2803
2804 /// If this is a bitfield with a default member initializer, this
2805 /// structure is used to represent the two expressions.
2806 struct InitAndBitWidth {
2807 Expr *Init;
2808 Expr *BitWidth;
2809 };
2810
2811 /// Storage for either the bit-width, the in-class initializer, or
2812 /// both (via InitAndBitWidth), or the captured variable length array bound.
2813 ///
2814 /// If the storage kind is ISK_InClassCopyInit or
2815 /// ISK_InClassListInit, but the initializer is null, then this
2816 /// field has an in-class initializer that has not yet been parsed
2817 /// and attached.
2818 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2819 // overwhelmingly common case that we have none of these things.
2820 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2821
2822protected:
2823 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2824 SourceLocation IdLoc, IdentifierInfo *Id,
2825 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2826 InClassInitStyle InitStyle)
2827 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2828 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2829 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2830 if (BW)
2831 setBitWidth(BW);
2832 }
2833
2834public:
2835 friend class ASTDeclReader;
2836 friend class ASTDeclWriter;
2837
2838 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2839 SourceLocation StartLoc, SourceLocation IdLoc,
2840 IdentifierInfo *Id, QualType T,
2841 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2842 InClassInitStyle InitStyle);
2843
2844 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2845
2846 /// Returns the index of this field within its record,
2847 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2848 unsigned getFieldIndex() const;
2849
2850 /// Determines whether this field is mutable (C++ only).
2851 bool isMutable() const { return Mutable; }
2852
2853 /// Determines whether this field is a bitfield.
2854 bool isBitField() const { return BitField; }
2855
2856 /// Determines whether this is an unnamed bitfield.
2857 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2858
2859 /// Determines whether this field is a
2860 /// representative for an anonymous struct or union. Such fields are
2861 /// unnamed and are implicitly generated by the implementation to
2862 /// store the data for the anonymous union or struct.
2863 bool isAnonymousStructOrUnion() const;
2864
2865 Expr *getBitWidth() const {
2866 if (!BitField)
2867 return nullptr;
2868 void *Ptr = InitStorage.getPointer();
2869 if (getInClassInitStyle())
2870 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2871 return static_cast<Expr*>(Ptr);
2872 }
2873
2874 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2875
2876 /// Set the bit-field width for this member.
2877 // Note: used by some clients (i.e., do not remove it).
2878 void setBitWidth(Expr *Width) {
2879 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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2880, __PRETTY_FUNCTION__))
2880 "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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2880, __PRETTY_FUNCTION__))
;
2881 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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2881, __PRETTY_FUNCTION__))
;
2882 InitStorage.setPointer(
2883 InitStorage.getInt()
2884 ? new (getASTContext())
2885 InitAndBitWidth{getInClassInitializer(), Width}
2886 : static_cast<void*>(Width));
2887 BitField = true;
2888 }
2889
2890 /// Remove the bit-field width from this member.
2891 // Note: used by some clients (i.e., do not remove it).
2892 void removeBitWidth() {
2893 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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2893, __PRETTY_FUNCTION__))
;
2894 InitStorage.setPointer(getInClassInitializer());
2895 BitField = false;
2896 }
2897
2898 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2899 /// at all and instead act as a separator between contiguous runs of other
2900 /// bit-fields.
2901 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2902
2903 /// Determine if this field is a subobject of zero size, that is, either a
2904 /// zero-length bit-field or a field of empty class type with the
2905 /// [[no_unique_address]] attribute.
2906 bool isZeroSize(const ASTContext &Ctx) const;
2907
2908 /// Get the kind of (C++11) default member initializer that this field has.
2909 InClassInitStyle getInClassInitStyle() const {
2910 InitStorageKind storageKind = InitStorage.getInt();
2911 return (storageKind == ISK_CapturedVLAType
2912 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2913 }
2914
2915 /// Determine whether this member has a C++11 default member initializer.
2916 bool hasInClassInitializer() const {
2917 return getInClassInitStyle() != ICIS_NoInit;
2918 }
2919
2920 /// Get the C++11 default member initializer for this member, or null if one
2921 /// has not been set. If a valid declaration has a default member initializer,
2922 /// but this returns null, then we have not parsed and attached it yet.
2923 Expr *getInClassInitializer() const {
2924 if (!hasInClassInitializer())
2925 return nullptr;
2926 void *Ptr = InitStorage.getPointer();
2927 if (BitField)
2928 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2929 return static_cast<Expr*>(Ptr);
2930 }
2931
2932 /// Set the C++11 in-class initializer for this member.
2933 void setInClassInitializer(Expr *Init) {
2934 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2934, __PRETTY_FUNCTION__))
;
2935 if (BitField)
2936 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2937 else
2938 InitStorage.setPointer(Init);
2939 }
2940
2941 /// Remove the C++11 in-class initializer from this member.
2942 void removeInClassInitializer() {
2943 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~++20201124111112+7b5254223ac/clang/include/clang/AST/Decl.h"
, 2943, __PRETTY_FUNCTION__))
;
2944 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2945 }
2946
2947 /// Determine whether this member captures the variable length array
2948 /// type.
2949 bool hasCapturedVLAType() const {
2950 return InitStorage.getInt() == ISK_CapturedVLAType;
2951 }
2952
2953 /// Get the captured variable length array type.
2954 const VariableArrayType *getCapturedVLAType() const {
2955 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2956 InitStorage.getPointer())
2957 : nullptr;
2958 }
2959
2960 /// Set the captured variable length array type for this field.
2961 void setCapturedVLAType(const VariableArrayType *VLAType);
2962
2963 /// Returns the parent of this field declaration, which
2964 /// is the struct in which this field is defined.
2965 ///
2966 /// Returns null if this is not a normal class/struct field declaration, e.g.
2967 /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
2968 const RecordDecl *getParent() const {
2969 return dyn_cast<RecordDecl>(getDeclContext());
2970 }
2971
2972 RecordDecl *getParent() {
2973 return dyn_cast<RecordDecl>(getDeclContext());
2974 }
2975
2976 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2977
2978 /// Retrieves the canonical declaration of this field.
2979 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2980 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2981
2982 // Implement isa/cast/dyncast/etc.
2983 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2984 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2985};
2986
2987/// An instance of this object exists for each enum constant
2988/// that is defined. For example, in "enum X {a,b}", each of a/b are
2989/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2990/// TagType for the X EnumDecl.
2991class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {