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