Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGBlocks.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D 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 -O2 -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~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGBlocks.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGBlocks.cpp

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/Decl.h

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