Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/CodeGen/CGBlocks.cpp

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

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