Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CGBlocks.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/CodeGen/CGBlocks.cpp

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

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