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