blob: b1dbb505b5d09a4f243e7af2e9ccf94c4d02e47b [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
17#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000018#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000022#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000023#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000024#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000025#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000026#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Module.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000029#include "llvm/Support/ScopedPrinter.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000030#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000031#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000032
Anders Carlsson2437cbf2009-02-12 00:39:25 +000033using namespace clang;
34using namespace CodeGen;
35
John McCall08ef4662011-11-10 08:15:53 +000036CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
37 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000038 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Akira Hatanaka9978da32018-08-10 15:09:24 +000039 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
40 StructureType(nullptr), Block(block), DominatingIP(nullptr) {
Craig Topper8a13c412014-05-21 05:09:00 +000041
John McCall08ef4662011-11-10 08:15:53 +000042 // Skip asm prefix, if any. 'name' is usually taken directly from
43 // the mangled name of the enclosing function.
44 if (!name.empty() && name[0] == '\01')
45 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000046}
47
John McCallf9b056b2011-03-31 08:03:29 +000048// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000049BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000050
John McCall351762c2011-02-07 10:33:21 +000051/// Build the given block as a global block.
52static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo,
54 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000055
John McCall351762c2011-02-07 10:33:21 +000056/// Build the helper function to copy a block.
57static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
60}
61
Alp Tokerf6a24ce2013-12-05 16:25:25 +000062/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000063static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
64 const CGBlockInfo &blockInfo) {
65 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
66}
67
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000068/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
69/// buildBlockDescriptor is accessed from 5th field of the Block_literal
70/// meta-data and contains stationary information about the block literal.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000071/// Its definition will have 4 (or optionally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000072/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000073/// struct Block_descriptor {
74/// unsigned long reserved;
75/// unsigned long size; // size of Block_literal metadata in bytes.
76/// void *copy_func_helper_decl; // optional copy helper.
77/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000078/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000079/// void *block_layout_info; // encoding of captured block variables.
80/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000081/// \endcode
John McCall351762c2011-02-07 10:33:21 +000082static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
83 const CGBlockInfo &blockInfo) {
84 ASTContext &C = CGM.getContext();
85
John McCall6c9f1fdb2016-11-19 08:17:24 +000086 llvm::IntegerType *ulong =
87 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
88 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000089 if (CGM.getLangOpts().OpenCL)
Fangrui Song6907ce22018-07-30 19:24:48 +000090 i8p =
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000091 llvm::Type::getInt8PtrTy(
92 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
93 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000094 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000095
John McCall23c9dc62016-11-28 22:18:27 +000096 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000097 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000098
99 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +0000100 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +0000101
102 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000103 // FIXME: What is the right way to say this doesn't fit? We should give
104 // a user diagnostic in that case. Better fix would be to change the
105 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000106 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000107
John McCall351762c2011-02-07 10:33:21 +0000108 // Optional copy/dispose helpers.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000109 if (blockInfo.needsCopyDisposeHelpers()) {
Mike Stump85284ba2009-02-13 16:19:19 +0000110 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000111 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000112
113 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000114 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000115 }
116
John McCall351762c2011-02-07 10:33:21 +0000117 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
118 std::string typeAtEncoding =
119 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000120 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000121 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Fangrui Song6907ce22018-07-30 19:24:48 +0000122
John McCall351762c2011-02-07 10:33:21 +0000123 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000124 if (C.getLangOpts().ObjC1) {
125 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000127 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000128 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000129 }
John McCall351762c2011-02-07 10:33:21 +0000130 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000131 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000132
Joey Goulyddbda402016-08-10 15:57:02 +0000133 unsigned AddrSpace = 0;
134 if (C.getLangOpts().OpenCL)
135 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000136
John McCall351762c2011-02-07 10:33:21 +0000137 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000138 elements.finishAndCreateGlobal("__block_descriptor_tmp",
139 CGM.getPointerAlign(),
140 /*constant*/ true,
141 llvm::GlobalValue::InternalLinkage,
142 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000143
John McCall351762c2011-02-07 10:33:21 +0000144 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000145}
146
John McCall351762c2011-02-07 10:33:21 +0000147/*
148 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000149
John McCall351762c2011-02-07 10:33:21 +0000150 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
151 struct Block_literal {
152 /// Initialized to one of:
153 /// extern void *_NSConcreteStackBlock[];
154 /// extern void *_NSConcreteGlobalBlock[];
155 ///
156 /// In theory, we could start one off malloc'ed by setting
157 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
158 /// this isa:
159 /// extern void *_NSConcreteMallocBlock[];
160 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000161
John McCall351762c2011-02-07 10:33:21 +0000162 /// These are the flags (with corresponding bit number) that the
163 /// compiler is actually supposed to know about.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000164 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
John McCall351762c2011-02-07 10:33:21 +0000165 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
166 /// descriptor provides copy and dispose helper functions
167 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
168 /// object with a nontrivial destructor or copy constructor
169 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
170 /// as global memory
171 /// 29. BLOCK_USE_STRET - indicates that the block function
172 /// uses stret, which objc_msgSend needs to know about
173 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
174 /// @encoded signature string
175 /// And we're not supposed to manipulate these:
176 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
177 /// to malloc'ed memory
178 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
179 /// to GC-allocated memory
180 /// Additionally, the bottom 16 bits are a reference count which
181 /// should be zero on the stack.
182 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Reserved; should be zero-initialized.
185 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Function pointer generated from block literal.
188 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000189
John McCall351762c2011-02-07 10:33:21 +0000190 /// Block description metadata generated from block literal.
191 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000192
John McCall351762c2011-02-07 10:33:21 +0000193 /// Captured values follow.
194 _CapturesTypes captures...;
195 };
196 */
David Chisnall950a9512009-11-17 19:33:30 +0000197
John McCall351762c2011-02-07 10:33:21 +0000198namespace {
199 /// A chunk of data that we actually have to capture in the block.
200 struct BlockLayoutChunk {
201 CharUnits Alignment;
202 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000203 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000204 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000205 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000206 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000207
John McCall351762c2011-02-07 10:33:21 +0000208 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000209 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000210 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000211 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000212 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000213 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000214
John McCall351762c2011-02-07 10:33:21 +0000215 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000216 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
217 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000218 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000219 info.CXXThisOffset = offset;
220 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000221 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
222 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000223 }
John McCall87fe5d52010-05-20 01:18:31 +0000224 }
John McCall351762c2011-02-07 10:33:21 +0000225 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000226
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000227 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
228 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000229 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000230 if (left.Alignment != right.Alignment)
231 return left.Alignment > right.Alignment;
232
233 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000234 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000235 return 1;
236 if (chunk.Lifetime == Qualifiers::OCL_Strong)
237 return 0;
238 if (chunk.Lifetime == Qualifiers::OCL_Weak)
239 return 2;
240 return 3;
241 };
242
243 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000244 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000245} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000246
John McCallb0a3ecb2011-02-08 03:07:00 +0000247/// Determines if the given type is safe for constant capture in C++.
248static bool isSafeForCXXConstantCapture(QualType type) {
249 const RecordType *recordType =
250 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
251
252 // Only records can be unsafe.
253 if (!recordType) return true;
254
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000255 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000256
257 // Maintain semantics for classes with non-trivial dtors or copy ctors.
258 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000259 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000260
261 // Otherwise, we just have to make sure there aren't any mutable
262 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000263 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000264}
265
John McCall351762c2011-02-07 10:33:21 +0000266/// It is illegal to modify a const object after initialization.
267/// Therefore, if a const object has a constant initializer, we don't
268/// actually need to keep storage for it in the block; we'll just
269/// rematerialize it at the start of the block function. This is
270/// acceptable because we make no promises about address stability of
271/// captured variables.
272static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000273 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000274 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000275 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000276 // rematerialize default arguments of function parameters.
277 if (isa<ParmVarDecl>(var))
278 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000279
John McCall351762c2011-02-07 10:33:21 +0000280 QualType type = var->getType();
281
282 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000283 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000284
John McCallb0a3ecb2011-02-08 03:07:00 +0000285 // Furthermore, in C++ we have to worry about mutable fields:
286 // C++ [dcl.type.cv]p4:
287 // Except that any class member declared mutable can be
288 // modified, any attempt to modify a const object during its
289 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000290 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000291 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000292
293 // If the variable doesn't have any initializer (shouldn't this be
294 // invalid?), it's not clear what we should do. Maybe capture as
295 // zero?
296 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000297 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000298
John McCallde0fe072017-08-15 21:42:52 +0000299 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000300}
301
302/// Get the low bit of a nonzero character count. This is the
303/// alignment of the nth byte if the 0th byte is universally aligned.
304static CharUnits getLowBit(CharUnits v) {
305 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
306}
307
308static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000310
311 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000312 if (CGM.getLangOpts().OpenCL) {
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000313 // The header is basically 'struct { int; int;
Yaxun Liu10712d92017-10-04 20:32:17 +0000314 // custom_fields; }'. Assert that struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000315 elementTypes.push_back(CGM.IntTy); /* total size */
316 elementTypes.push_back(CGM.IntTy); /* align */
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000317 unsigned Offset = 2 * CGM.getIntSize().getQuantity();
318 unsigned BlockAlign = CGM.getIntAlign().getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000319 if (auto *Helper =
320 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
321 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
322 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
323 // If necessary, add padding fields to the custom fields.
324 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
325 if (BlockAlign < Align)
326 BlockAlign = Align;
327 assert(Offset % Align == 0);
328 Offset += CGM.getDataLayout().getTypeAllocSize(I);
329 elementTypes.push_back(I);
330 }
331 }
332 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
333 info.BlockSize = CharUnits::fromQuantity(Offset);
334 } else {
335 // The header is basically 'struct { void *; int; int; void *; void *; }'.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000336 // Assert that the struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000337 assert(CGM.getIntSize() <= CGM.getPointerSize());
338 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
339 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
340 info.BlockAlign = CGM.getPointerAlign();
341 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
342 elementTypes.push_back(CGM.VoidPtrTy);
343 elementTypes.push_back(CGM.IntTy);
344 elementTypes.push_back(CGM.IntTy);
345 elementTypes.push_back(CGM.VoidPtrTy);
346 elementTypes.push_back(CGM.getBlockDescriptorType());
347 }
John McCall351762c2011-02-07 10:33:21 +0000348}
349
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000350static QualType getCaptureFieldType(const CodeGenFunction &CGF,
351 const BlockDecl::Capture &CI) {
352 const VarDecl *VD = CI.getVariable();
353
354 // If the variable is captured by an enclosing block or lambda expression,
355 // use the type of the capture field.
356 if (CGF.BlockInfo && CI.isNested())
357 return CGF.BlockInfo->getCapture(VD).fieldType();
358 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
359 return FD->getType();
360 return VD->getType();
361}
362
John McCall351762c2011-02-07 10:33:21 +0000363/// Compute the layout of the given block. Attempts to lay the block
364/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000365static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
366 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000367 ASTContext &C = CGM.getContext();
368 const BlockDecl *block = info.getBlockDecl();
369
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000370 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000371 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000372 bool hasNonConstantCustomFields = false;
373 if (auto *OpenCLHelper =
374 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
375 hasNonConstantCustomFields =
376 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
377 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000378 info.StructureType =
379 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
380 info.CanBeGlobal = true;
381 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000382 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000383 else if (C.getLangOpts().ObjC1 &&
384 CGM.getLangOpts().getGC() == LangOptions::NonGC)
385 info.HasCapturedVariableLayout = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000386
John McCall351762c2011-02-07 10:33:21 +0000387 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000389 layout.reserve(block->capturesCXXThis() +
390 (block->capture_end() - block->capture_begin()));
391
392 CharUnits maxFieldAlign;
393
394 // First, 'this'.
395 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000396 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
397 "Can't capture 'this' outside a method");
398 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000399
John McCall7f416cc2015-09-08 08:05:57 +0000400 // Theoretically, this could be in a different address space, so
401 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000402 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000403 std::pair<CharUnits,CharUnits> tinfo
404 = CGM.getContext().getTypeInfoInChars(thisType);
405 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
406
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000407 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
408 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000409 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000410 }
411
412 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000413 for (const auto &CI : block->captures()) {
414 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000415
Aaron Ballman9371dd22014-03-14 18:34:04 +0000416 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000417 // We have to copy/dispose of the __block reference.
418 info.NeedsCopyDispose = true;
419
John McCall351762c2011-02-07 10:33:21 +0000420 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000421 CharUnits align = CGM.getPointerAlign();
422 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000423
John McCall7f416cc2015-09-08 08:05:57 +0000424 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
425 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000426 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000427 continue;
428 }
429
430 // Otherwise, build a layout chunk with the size and alignment of
431 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000432 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000433 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
434 continue;
435 }
436
John McCall31168b02011-06-15 23:02:42 +0000437 // If we have a lifetime qualifier, honor it for capture purposes.
438 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000439 Qualifiers::ObjCLifetime lifetime =
440 variable->getType().getObjCLifetime();
441 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000442 switch (lifetime) {
443 case Qualifiers::OCL_None: llvm_unreachable("impossible");
444 case Qualifiers::OCL_ExplicitNone:
445 case Qualifiers::OCL_Autoreleasing:
446 break;
John McCall351762c2011-02-07 10:33:21 +0000447
John McCall31168b02011-06-15 23:02:42 +0000448 case Qualifiers::OCL_Strong:
449 case Qualifiers::OCL_Weak:
450 info.NeedsCopyDispose = true;
451 }
452
453 // Block pointers require copy/dispose. So do Objective-C pointers.
454 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000455 // But honor the inert __unsafe_unretained qualifier, which doesn't
456 // actually make it into the type system.
457 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
458 lifetime = Qualifiers::OCL_ExplicitNone;
459 } else {
460 info.NeedsCopyDispose = true;
461 // used for mrr below.
462 lifetime = Qualifiers::OCL_Strong;
463 }
John McCall351762c2011-02-07 10:33:21 +0000464
465 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000466 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000467 info.NeedsCopyDispose = true;
468 info.HasCXXObject = true;
Akira Hatanaka9978da32018-08-10 15:09:24 +0000469 if (!variable->getType()->getAsCXXRecordDecl()->isExternallyVisible())
470 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000471
Akira Hatanaka7275da02018-02-28 07:15:55 +0000472 // So do C structs that require non-trivial copy construction or
473 // destruction.
474 } else if (variable->getType().isNonTrivialToPrimitiveCopy() ==
475 QualType::PCK_Struct ||
476 variable->getType().isDestructedType() ==
477 QualType::DK_nontrivial_c_struct) {
478 info.NeedsCopyDispose = true;
479
John McCall351762c2011-02-07 10:33:21 +0000480 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000481 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000482 if (const CXXRecordDecl *record =
483 variable->getType()->getAsCXXRecordDecl()) {
484 if (!record->hasTrivialDestructor()) {
485 info.HasCXXObject = true;
486 info.NeedsCopyDispose = true;
Akira Hatanaka9978da32018-08-10 15:09:24 +0000487 if (!record->isExternallyVisible())
488 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000489 }
490 }
491 }
492
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000493 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000494 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000495 CharUnits align = C.getDeclAlign(variable);
Fangrui Song6907ce22018-07-30 19:24:48 +0000496
John McCall351762c2011-02-07 10:33:21 +0000497 maxFieldAlign = std::max(maxFieldAlign, align);
498
Jay Foad7c57be32011-07-11 09:56:20 +0000499 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000500 CGM.getTypes().ConvertTypeForMem(VT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000501
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000502 layout.push_back(
503 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000504 }
505
506 // If that was everything, we're done here.
507 if (layout.empty()) {
508 info.StructureType =
509 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
510 info.CanBeGlobal = true;
511 return;
512 }
513
514 // Sort the layout by alignment. We have to use a stable sort here
515 // to get reproducible results. There should probably be an
516 // llvm::array_pod_stable_sort.
517 std::stable_sort(layout.begin(), layout.end());
Fangrui Song6907ce22018-07-30 19:24:48 +0000518
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000519 // Needed for blocks layout info.
520 info.BlockHeaderForcedGapOffset = info.BlockSize;
521 info.BlockHeaderForcedGapSize = CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +0000522
John McCall351762c2011-02-07 10:33:21 +0000523 CharUnits &blockSize = info.BlockSize;
524 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
525
526 // Assuming that the first byte in the header is maximally aligned,
527 // get the alignment of the first byte following the header.
528 CharUnits endAlign = getLowBit(blockSize);
529
530 // If the end of the header isn't satisfactorily aligned for the
531 // maximum thing, look for things that are okay with the header-end
532 // alignment, and keep appending them until we get something that's
533 // aligned right. This algorithm is only guaranteed optimal if
534 // that condition is satisfied at some point; otherwise we can get
535 // things like:
536 // header // next byte has alignment 4
537 // something_with_size_5; // next byte has alignment 1
538 // something_with_alignment_8;
539 // which has 7 bytes of padding, as opposed to the naive solution
540 // which might have less (?).
541 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000542 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000543 li = layout.begin() + 1, le = layout.end();
544
545 // Look for something that the header end is already
546 // satisfactorily aligned for.
547 for (; li != le && endAlign < li->Alignment; ++li)
548 ;
549
550 // If we found something that's naturally aligned for the end of
551 // the header, keep adding things...
552 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000553 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000554 for (; li != le; ++li) {
555 assert(endAlign >= li->Alignment);
556
John McCall7f416cc2015-09-08 08:05:57 +0000557 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000558 elementTypes.push_back(li->Type);
559 blockSize += li->Size;
560 endAlign = getLowBit(blockSize);
561
562 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000563 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000564 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000565 }
John McCall351762c2011-02-07 10:33:21 +0000566 }
John McCall351762c2011-02-07 10:33:21 +0000567 // Don't re-append everything we just appended.
568 layout.erase(first, li);
569 }
570 }
571
John McCallac0350a2012-04-26 21:14:42 +0000572 assert(endAlign == getLowBit(blockSize));
Fangrui Song6907ce22018-07-30 19:24:48 +0000573
John McCall351762c2011-02-07 10:33:21 +0000574 // At this point, we just have to add padding if the end align still
575 // isn't aligned right.
576 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000577 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000578 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000579
John McCall7f416cc2015-09-08 08:05:57 +0000580 // If we haven't yet added any fields, remember that there was an
581 // initial gap; this need to go into the block layout bit map.
582 if (blockSize == info.BlockHeaderForcedGapOffset) {
583 info.BlockHeaderForcedGapSize = padding;
584 }
585
John McCalle3dc1702011-02-15 09:22:45 +0000586 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
587 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000588 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000589 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000590 }
591
John McCall1db0a2f2012-05-01 20:28:00 +0000592 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000593 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000594 // Slam everything else on now. This works because they have
595 // strictly decreasing alignment and we expect that size is always a
596 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000597 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000598 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000599 if (endAlign < li->Alignment) {
600 // size may not be multiple of alignment. This can only happen with
601 // an over-aligned variable. We will be adding a padding field to
602 // make the size be multiple of alignment.
603 CharUnits padding = li->Alignment - endAlign;
604 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
605 padding.getQuantity()));
606 blockSize += padding;
607 endAlign = getLowBit(blockSize);
608 }
John McCall351762c2011-02-07 10:33:21 +0000609 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000610 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000611 elementTypes.push_back(li->Type);
612 blockSize += li->Size;
613 endAlign = getLowBit(blockSize);
614 }
615
616 info.StructureType =
617 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
618}
619
John McCall08ef4662011-11-10 08:15:53 +0000620/// Enter the scope of a block. This should be run at the entrance to
621/// a full-expression so that the block's cleanups are pushed at the
622/// right place in the stack.
623static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000624 assert(CGF.HaveInsertPoint());
625
John McCall08ef4662011-11-10 08:15:53 +0000626 // Allocate the block info and place it at the head of the list.
627 CGBlockInfo &blockInfo =
628 *new CGBlockInfo(block, CGF.CurFn->getName());
629 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
630 CGF.FirstBlockInfo = &blockInfo;
631
632 // Compute information about the layout, etc., of this block,
633 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000634 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000635
636 // Nothing else to do if it can be global.
637 if (blockInfo.CanBeGlobal) return;
638
639 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000640 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
641 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000642
643 // If there are cleanups to emit, enter them (but inactive).
644 if (!blockInfo.NeedsCopyDispose) return;
645
646 // Walk through the captures (in order) and find the ones not
647 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000648 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000649 // Ignore __block captures; there's nothing special in the
650 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000651 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000652
653 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000654 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000655 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
656 if (capture.isConstant()) continue;
657
658 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000659 QualType VT = getCaptureFieldType(CGF, CI);
660 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000661 if (dtorKind == QualType::DK_none) continue;
662
663 CodeGenFunction::Destroyer *destroyer;
664
665 // Block captures count as local values and have imprecise semantics.
666 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000667 //
668 // For const-qualified captures, emit clang.arc.use to ensure the captured
669 // object doesn't get released while we are still depending on its validity
670 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000671 if (VT.isConstQualified() &&
672 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
673 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
674 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
675 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000676 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000677 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000678 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000679 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000680 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000681 }
682
683 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000684 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
685 capture.getIndex(),
686 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000687
John McCallf4beacd2011-11-10 10:43:54 +0000688 // We can use that GEP as the dominating IP.
689 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000690 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000691
John McCall08ef4662011-11-10 08:15:53 +0000692 CleanupKind cleanupKind = InactiveNormalCleanup;
693 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
Fangrui Song6907ce22018-07-30 19:24:48 +0000694 if (useArrayEHCleanup)
John McCall08ef4662011-11-10 08:15:53 +0000695 cleanupKind = InactiveNormalAndEHCleanup;
696
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000697 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000698 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000699
700 // Remember where that cleanup was.
701 capture.setCleanup(CGF.EHStack.stable_begin());
702 }
703}
704
705/// Enter a full-expression with a non-trivial number of objects to
706/// clean up. This is in this file because, at the moment, the only
707/// kind of cleanup object is a BlockDecl*.
708void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
709 assert(E->getNumObjects() != 0);
George Burgess IV8b93a592018-03-02 20:10:38 +0000710 for (const ExprWithCleanups::CleanupObject &C : E->getObjects())
711 enterBlockScope(*this, C);
John McCall08ef4662011-11-10 08:15:53 +0000712}
713
714/// Find the layout for the given block in a linked list and remove it.
715static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
716 const BlockDecl *block) {
717 while (true) {
718 assert(head && *head);
719 CGBlockInfo *cur = *head;
720
721 // If this is the block we're looking for, splice it out of the list.
722 if (cur->getBlockDecl() == block) {
723 *head = cur->NextBlockInfo;
724 return cur;
725 }
726
727 head = &cur->NextBlockInfo;
728 }
729}
730
731/// Destroy a chain of block layouts.
732void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
733 assert(head && "destroying an empty chain");
734 do {
735 CGBlockInfo *cur = head;
736 head = cur->NextBlockInfo;
737 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000738 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000739}
740
John McCall351762c2011-02-07 10:33:21 +0000741/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000742llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000743 // If the block has no captures, we won't have a pre-computed
744 // layout for it.
745 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000746 // The block literal is emitted as a global variable, and the block invoke
747 // function has to be extracted from its initializer.
748 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
George Burgess IVe3763372016-12-22 02:50:20 +0000749 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000750 }
John McCall08ef4662011-11-10 08:15:53 +0000751 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000752 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000753 blockInfo.BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000754 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000755 }
John McCall351762c2011-02-07 10:33:21 +0000756
John McCall08ef4662011-11-10 08:15:53 +0000757 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000758 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000759 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
760 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000761
John McCall08ef4662011-11-10 08:15:53 +0000762 blockInfo->BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000763 return EmitBlockLiteral(*blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000764}
765
Yaxun Liufa13d012018-02-15 16:39:19 +0000766llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000767 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
John McCall08ef4662011-11-10 08:15:53 +0000768 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000769 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000770 CodeGenFunction BlockCGF{CGM, true};
771 BlockCGF.SanOpts = SanOpts;
772 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000773 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
John McCall351762c2011-02-07 10:33:21 +0000774
775 // If there is nothing to capture, we can emit this as a global block.
776 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000777 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000778
779 // Otherwise, we have to emit this as a local block.
780
John McCall7f416cc2015-09-08 08:05:57 +0000781 Address blockAddr = blockInfo.LocalAddress;
782 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000783
Yaxun Liu10712d92017-10-04 20:32:17 +0000784 llvm::Constant *isa;
785 llvm::Constant *descriptor;
786 BlockFlags flags;
787 if (!IsOpenCL) {
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000788 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
789 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
790 // block just returns the original block and releasing it is a no-op.
791 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
792 ? CGM.getNSConcreteGlobalBlock()
793 : CGM.getNSConcreteStackBlock();
794 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
Yaxun Liu10712d92017-10-04 20:32:17 +0000795
796 // Build the block descriptor.
797 descriptor = buildBlockDescriptor(CGM, blockInfo);
798
799 // Compute the initial on-stack block flags.
800 flags = BLOCK_HAS_SIGNATURE;
801 if (blockInfo.HasCapturedVariableLayout)
802 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000803 if (blockInfo.needsCopyDisposeHelpers())
Yaxun Liu10712d92017-10-04 20:32:17 +0000804 flags |= BLOCK_HAS_COPY_DISPOSE;
805 if (blockInfo.HasCXXObject)
806 flags |= BLOCK_HAS_CXX_OBJ;
807 if (blockInfo.UsesStret)
808 flags |= BLOCK_USE_STRET;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000809 if (blockInfo.getBlockDecl()->doesNotEscape())
810 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
Yaxun Liu10712d92017-10-04 20:32:17 +0000811 }
John McCall351762c2011-02-07 10:33:21 +0000812
John McCall7f416cc2015-09-08 08:05:57 +0000813 auto projectField =
814 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
815 return Builder.CreateStructGEP(blockAddr, index, offset, name);
816 };
817 auto storeField =
818 [&](llvm::Value *value, unsigned index, CharUnits offset,
819 const Twine &name) {
820 Builder.CreateStore(value, projectField(index, offset, name));
821 };
822
823 // Initialize the block header.
824 {
825 // We assume all the header fields are densely packed.
826 unsigned index = 0;
827 CharUnits offset;
828 auto addHeaderField =
829 [&](llvm::Value *value, CharUnits size, const Twine &name) {
830 storeField(value, index, offset, name);
831 offset += size;
832 index++;
833 };
834
Yaxun Liu10712d92017-10-04 20:32:17 +0000835 if (!IsOpenCL) {
836 addHeaderField(isa, getPointerSize(), "block.isa");
837 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
838 getIntSize(), "block.flags");
839 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
840 "block.reserved");
841 } else {
842 addHeaderField(
843 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
844 getIntSize(), "block.size");
845 addHeaderField(
846 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
847 getIntSize(), "block.align");
848 }
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000849 if (!IsOpenCL) {
850 addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
851 getPointerSize(), "block.invoke");
Yaxun Liu10712d92017-10-04 20:32:17 +0000852 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000853 } else if (auto *Helper =
854 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000855 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
856 addHeaderField(
857 I.first,
858 CharUnits::fromQuantity(
859 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
860 I.second);
861 }
862 }
John McCall7f416cc2015-09-08 08:05:57 +0000863 }
John McCall351762c2011-02-07 10:33:21 +0000864
865 // Finally, capture all the values into the block.
866 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
867
868 // First, 'this'.
869 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000870 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
871 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000872 Builder.CreateStore(LoadCXXThis(), addr);
873 }
874
875 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000876 for (const auto &CI : blockDecl->captures()) {
877 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000878 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
879
880 // Ignore constant captures.
881 if (capture.isConstant()) continue;
882
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000883 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000884
885 // This will be a [[type]]*, except that a byref entry will just be
886 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000887 Address blockField =
888 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000889
890 // Compute the address of the thing we're going to move into the
891 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000892 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000893
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000894 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000895 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000896 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000897 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000898 } else if (CI.isByRef()) {
899 if (BlockInfo && CI.isNested()) {
900 // We need to use the capture from the enclosing block.
901 const CGBlockInfo::Capture &enclosingCapture =
902 BlockInfo->getCapture(variable);
903
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000904 // This is a [[type]]*, except that a byref entry will just be an i8**.
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000905 src = Builder.CreateStructGEP(LoadBlockStruct(),
906 enclosingCapture.getIndex(),
907 enclosingCapture.getOffset(),
908 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000909 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000910 auto I = LocalDeclMap.find(variable);
911 assert(I != LocalDeclMap.end());
912 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000913 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000914 } else {
915 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
916 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
917 type.getNonReferenceType(), VK_LValue,
918 SourceLocation());
919 src = EmitDeclRefLValue(&declRef).getAddress();
920 };
John McCall351762c2011-02-07 10:33:21 +0000921
922 // For byrefs, we just write the pointer to the byref struct into
923 // the block field. There's no need to chase the forwarding
924 // pointer at this point, since we're building something that will
925 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000926 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000927 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000928 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000929 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000930 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000931 else
John McCall7f416cc2015-09-08 08:05:57 +0000932 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000933
John McCalle3dc1702011-02-15 09:22:45 +0000934 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000935 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000936
937 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000938 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000939 if (blockDecl->isConversionFromLambda()) {
940 // If we have a lambda conversion, emit the expression
941 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000942 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000943 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000944 AggValueSlot::IsDestructed,
945 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000946 AggValueSlot::IsNotAliased,
947 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000948 EmitAggExpr(copyExpr, Slot);
949 } else {
950 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
951 }
John McCall351762c2011-02-07 10:33:21 +0000952
953 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000954 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000955 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000956
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000957 // If type is const-qualified, copy the value into the block field.
958 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000959 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
960 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000961 llvm::Value *value = Builder.CreateLoad(src, "captured");
962 Builder.CreateStore(value, blockField);
963
John McCall4d14a902013-04-08 23:27:49 +0000964 // If this is an ARC __strong block-pointer variable, don't do a
965 // block copy.
966 //
967 // TODO: this can be generalized into the normal initialization logic:
968 // we should never need to do a block-copy when initializing a local
969 // variable, because the local variable's lifetime should be strictly
970 // contained within the stack block's.
971 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
972 type->isBlockPointerType()) {
973 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000974 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000975 value = EmitARCRetainNonBlock(value);
976
977 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000978 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000979
980 // Otherwise, fake up a POD copy into the block field.
981 } else {
John McCall31168b02011-06-15 23:02:42 +0000982 // Fake up a new variable so that EmitScalarInit doesn't think
983 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000984 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
985 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000986
John McCall93be3f72011-02-07 18:37:40 +0000987 // We use one of these or the other depending on whether the
988 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000989 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
990 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
991 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000992
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000993 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000994 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000995 // FIXME: Pass a specific location for the expr init so that the store is
996 // attributed to a reasonable location - otherwise it may be attributed to
997 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +0000998 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000999 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +00001000 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +00001001 }
1002
John McCall08ef4662011-11-10 08:15:53 +00001003 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001004 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +00001005 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1006 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +00001007 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +00001008 }
John McCall351762c2011-02-07 10:33:21 +00001009 }
1010
1011 // Cast to the converted block-pointer type, which happens (somewhat
1012 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001013 llvm::Value *result = Builder.CreatePointerCast(
1014 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001015
Yaxun Liufa13d012018-02-15 16:39:19 +00001016 if (IsOpenCL) {
1017 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1018 result);
1019 }
1020
John McCall351762c2011-02-07 10:33:21 +00001021 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001022}
1023
1024
Chris Lattnera5f58b02011-07-09 17:41:47 +00001025llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001026 if (BlockDescriptorType)
1027 return BlockDescriptorType;
1028
Chris Lattnera5f58b02011-07-09 17:41:47 +00001029 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001030 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001031
Mike Stump650c9322009-02-13 15:16:56 +00001032 // struct __block_descriptor {
1033 // unsigned long reserved;
1034 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001035 //
1036 // // later, the following will be added
1037 //
1038 // struct {
1039 // void (*copyHelper)();
1040 // void (*copyHelper)();
1041 // } helpers; // !!! optional
1042 //
1043 // const char *signature; // the block signature
1044 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001045 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001046 BlockDescriptorType = llvm::StructType::create(
1047 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001048
John McCall351762c2011-02-07 10:33:21 +00001049 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001050 unsigned AddrSpace = 0;
1051 if (getLangOpts().OpenCL)
1052 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1053 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001054 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001055}
1056
Chris Lattnera5f58b02011-07-09 17:41:47 +00001057llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001058 assert(!getLangOpts().OpenCL && "OpenCL does not need this");
1059
Mike Stump005c9a62009-02-13 15:25:34 +00001060 if (GenericBlockLiteralType)
1061 return GenericBlockLiteralType;
1062
Chris Lattnera5f58b02011-07-09 17:41:47 +00001063 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001064
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001065 // struct __block_literal_generic {
1066 // void *__isa;
1067 // int __flags;
1068 // int __reserved;
1069 // void (*__invoke)(void *);
1070 // struct __block_descriptor *__descriptor;
1071 // };
1072 GenericBlockLiteralType =
1073 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1074 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001075
Mike Stump005c9a62009-02-13 15:25:34 +00001076 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001077}
1078
Yaxun Liu10712d92017-10-04 20:32:17 +00001079RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001080 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001081 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001083
John McCallb92ab1a2016-10-26 23:46:34 +00001084 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Erich Keaneed69e1b2018-08-03 18:08:36 +00001085 llvm::Value *FuncPtr = nullptr;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001086
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001087 if (!CGM.getLangOpts().OpenCL) {
1088 // Get a pointer to the generic block literal.
1089 llvm::Type *BlockLiteralTy =
1090 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), 0);
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001091
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001092 // Bitcast the callee to a block literal.
1093 BlockPtr =
1094 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001095
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001096 // Get the function pointer from the literal.
1097 FuncPtr =
1098 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
1099 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001100
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001101 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001102 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001103
1104 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1105 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1106 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001107 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001108 VoidPtrQualTy =
1109 getContext().getPointerType(getContext().getAddrSpaceQualType(
1110 getContext().VoidTy, LangAS::opencl_generic));
1111 }
1112
1113 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1114 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001115
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001116 QualType FnType = BPT->getPointeeType();
1117
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001118 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001119 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001120
Anders Carlsson5f50c652009-04-07 22:10:22 +00001121 // Load the function.
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001122 llvm::Value *Func;
1123 if (CGM.getLangOpts().OpenCL)
1124 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1125 else
1126 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001127
John McCall85915252011-03-09 08:39:33 +00001128 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001129 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001130 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001131
Anders Carlsson5f50c652009-04-07 22:10:22 +00001132 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001133 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattner2192fe52011-07-18 04:24:23 +00001135 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001136 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001137
John McCallb92ab1a2016-10-26 23:46:34 +00001138 // Prepare the callee.
1139 CGCallee Callee(CGCalleeInfo(), Func);
1140
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001141 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001142 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001143}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001144
John McCall7f416cc2015-09-08 08:05:57 +00001145Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1146 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001147 assert(BlockInfo && "evaluating block ref without block information?");
1148 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001149
John McCall351762c2011-02-07 10:33:21 +00001150 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001151 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001152
John McCall7f416cc2015-09-08 08:05:57 +00001153 Address addr =
1154 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1155 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001156
John McCall351762c2011-02-07 10:33:21 +00001157 if (isByRef) {
1158 // addr should be a void** right now. Load, then cast the result
1159 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001160
John McCall7f416cc2015-09-08 08:05:57 +00001161 auto &byrefInfo = getBlockByrefInfo(variable);
1162 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001163
John McCall7f416cc2015-09-08 08:05:57 +00001164 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1165 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001166
John McCall7f416cc2015-09-08 08:05:57 +00001167 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1168 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001169 }
1170
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001171 if (capture.fieldType()->isReferenceType())
1172 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001173
John McCall351762c2011-02-07 10:33:21 +00001174 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001175}
1176
George Burgess IVe3763372016-12-22 02:50:20 +00001177void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1178 llvm::Constant *Addr) {
1179 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1180 (void)Ok;
1181 assert(Ok && "Trying to replace an already-existing global block!");
1182}
1183
Mike Stump2d5a2872009-02-14 22:16:35 +00001184llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001185CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1186 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001187 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1188 return Block;
1189
George Burgess IV70d15b32016-11-03 02:21:43 +00001190 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1191 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001192
John McCall351762c2011-02-07 10:33:21 +00001193 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001194 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001195
John McCall351762c2011-02-07 10:33:21 +00001196 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001197 {
John McCall7f416cc2015-09-08 08:05:57 +00001198 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001199 CodeGenFunction(*this).GenerateBlockFunction(
1200 GlobalDecl(), blockInfo, LocalDeclMap,
1201 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001202 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001203
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001204 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001205}
1206
John McCall351762c2011-02-07 10:33:21 +00001207static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1208 const CGBlockInfo &blockInfo,
1209 llvm::Constant *blockFn) {
1210 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001211 // Callers should detect this case on their own: calling this function
1212 // generally requires computing layout information, which is a waste of time
1213 // if we've already emitted this block.
1214 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1215 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001216
1217 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001218 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001219 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001220
Yaxun Liu10712d92017-10-04 20:32:17 +00001221 bool IsOpenCL = CGM.getLangOpts().OpenCL;
David Chisnallc5a458c2018-08-09 08:02:42 +00001222 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
Yaxun Liu10712d92017-10-04 20:32:17 +00001223 if (!IsOpenCL) {
1224 // isa
David Chisnallc5a458c2018-08-09 08:02:42 +00001225 if (IsWindows)
1226 fields.addNullPointer(CGM.Int8PtrPtrTy);
1227 else
1228 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001229
Yaxun Liu10712d92017-10-04 20:32:17 +00001230 // __flags
1231 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1232 if (blockInfo.UsesStret)
1233 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001234
Yaxun Liu10712d92017-10-04 20:32:17 +00001235 fields.addInt(CGM.IntTy, flags.getBitMask());
1236
1237 // Reserved
1238 fields.addInt(CGM.IntTy, 0);
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001239
1240 // Function
1241 fields.add(blockFn);
Yaxun Liu10712d92017-10-04 20:32:17 +00001242 } else {
1243 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1244 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1245 }
John McCall351762c2011-02-07 10:33:21 +00001246
Yaxun Liu10712d92017-10-04 20:32:17 +00001247 if (!IsOpenCL) {
1248 // Descriptor
1249 fields.add(buildBlockDescriptor(CGM, blockInfo));
1250 } else if (auto *Helper =
1251 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1252 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1253 fields.add(I);
1254 }
1255 }
John McCall351762c2011-02-07 10:33:21 +00001256
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001257 unsigned AddrSpace = 0;
1258 if (CGM.getContext().getLangOpts().OpenCL)
1259 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1260
1261 llvm::Constant *literal = fields.finishAndCreateGlobal(
1262 "__block_literal_global", blockInfo.BlockAlign,
David Chisnallc5a458c2018-08-09 08:02:42 +00001263 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1264
1265 // Windows does not allow globals to be initialised to point to globals in
1266 // different DLLs. Any such variables must run code to initialise them.
1267 if (IsWindows) {
1268 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1269 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1270 &CGM.getModule());
1271 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1272 Init));
1273 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1274 b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1275 b.CreateRetVoid();
1276 // We can't use the normal LLVM global initialisation array, because we
1277 // need to specify that this runs early in library initialisation.
1278 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1279 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1280 Init, ".block_isa_init_ptr");
1281 InitVar->setSection(".CRT$XCLa");
1282 CGM.addUsedGlobal(InitVar);
1283 }
John McCall351762c2011-02-07 10:33:21 +00001284
1285 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001286 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001287 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001288 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001289 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001290 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001291 if (CGM.getContext().getLangOpts().OpenCL)
1292 CGM.getOpenCLRuntime().recordBlockInfo(
1293 blockInfo.BlockExpression,
1294 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001295 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001296}
1297
John McCall7f416cc2015-09-08 08:05:57 +00001298void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1299 unsigned argNum,
1300 llvm::Value *arg) {
1301 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1302
Adrian Prantl356347b2017-10-26 20:08:52 +00001303 // Allocate a stack slot like for any local variable to guarantee optimal
1304 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1305 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1306 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001307 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001308 if (CGM.getCodeGenOpts().getDebugInfo() >=
1309 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001310 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001311 DI->EmitDeclareOfBlockLiteralArgVariable(
1312 *BlockInfo, D->getName(), argNum,
1313 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001314 }
1315 }
1316
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001317 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
John McCall7f416cc2015-09-08 08:05:57 +00001318 ApplyDebugLocation Scope(*this, StartLoc);
1319
1320 // Instead of messing around with LocalDeclMap, just set the value
1321 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001322 BlockPointer = Builder.CreatePointerCast(
1323 arg,
1324 BlockInfo->StructureType->getPointerTo(
1325 getContext().getLangOpts().OpenCL
1326 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1327 : 0),
1328 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001329}
1330
1331Address CodeGenFunction::LoadBlockStruct() {
1332 assert(BlockInfo && "not in a block invocation function!");
1333 assert(BlockPointer && "no block pointer set!");
1334 return Address(BlockPointer, BlockInfo->BlockAlign);
1335}
1336
Mike Stump4446dcf2009-03-05 08:32:30 +00001337llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001338CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1339 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001340 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001341 bool IsLambdaConversionToBlock,
1342 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001343 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001344
Fariborz Jahanian63628032012-06-26 16:06:38 +00001345 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001346
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001347 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001348
John McCall351762c2011-02-07 10:33:21 +00001349 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Mike Stump5469f292009-03-13 23:34:28 +00001351 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001352 // to be local to this function as well, in case they're directly
1353 // referenced in a block.
1354 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001355 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001356 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001357 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001358 }
1359
John McCall351762c2011-02-07 10:33:21 +00001360 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001361
John McCall351762c2011-02-07 10:33:21 +00001362 // Build the argument list.
1363 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001364
John McCall351762c2011-02-07 10:33:21 +00001365 // The first argument is the block pointer. Just take it as a void*
1366 // and cast it later.
1367 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001368
1369 // For OpenCL passed block pointer can be private AS local variable or
1370 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001371 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001372 // generic AS in one implementation.
1373 if (getLangOpts().OpenCL)
1374 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1375 getContext().VoidTy, LangAS::opencl_generic));
1376
Mike Stump7fe9cc12009-10-21 03:49:08 +00001377 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001378
Alexey Bataev56223232017-06-09 13:40:18 +00001379 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1380 SourceLocation(), II, selfTy,
1381 ImplicitParamDecl::ObjCSelf);
1382 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001383
John McCall351762c2011-02-07 10:33:21 +00001384 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001385 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001386
John McCall351762c2011-02-07 10:33:21 +00001387 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001388 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001389 const CGFunctionInfo &fnInfo =
1390 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001391 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001392 blockInfo.UsesStret = true;
1393
John McCalla729c622012-02-17 03:33:10 +00001394 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001395
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001396 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001397 llvm::Function *fn = llvm::Function::Create(
1398 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001399 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001400
Yaxun Liu10712d92017-10-04 20:32:17 +00001401 if (BuildGlobalBlock) {
1402 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1403 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1404 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001405 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001406 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1407 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001408
John McCall351762c2011-02-07 10:33:21 +00001409 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001410 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001411 blockDecl->getLocation(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001412 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
Mike Stumpb7074c02009-02-13 15:32:32 +00001413
John McCall147d0212011-02-22 22:38:33 +00001414 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001415
Adrian Prantl0f6df002013-03-29 19:20:35 +00001416 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1417 // won't delete the dbg.declare intrinsics for captured variables.
1418 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1419 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1420 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001421 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1422 getPointerAlign(),
1423 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001424 // Set the DebugLocation to empty, so the store is recognized as a
1425 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001426 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001427 Builder.CreateStore(BlockPointer, Alloca);
1428 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001429 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001430
John McCall87fe5d52010-05-20 01:18:31 +00001431 // If we have a C++ 'this' reference, go ahead and force it into
1432 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001433 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001434 Address addr =
1435 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1436 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001437 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001438 }
1439
John McCall351762c2011-02-07 10:33:21 +00001440 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001441 for (const auto &CI : blockDecl->captures()) {
1442 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001443 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1444 if (!capture.isConstant()) continue;
1445
John McCall7f416cc2015-09-08 08:05:57 +00001446 CharUnits align = getContext().getDeclAlign(variable);
1447 Address alloca =
1448 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001449
John McCall7f416cc2015-09-08 08:05:57 +00001450 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001451
John McCall7f416cc2015-09-08 08:05:57 +00001452 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001453 }
1454
John McCall113bee02012-03-10 09:33:50 +00001455 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001456 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1457 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1458 --entry_ptr;
1459
Eli Friedman2495ab02012-02-25 02:48:22 +00001460 if (IsLambdaConversionToBlock)
1461 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001462 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001463 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001464 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001465 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001466 }
Mike Stump017460a2009-10-01 22:29:41 +00001467
Mike Stump7d699112009-10-01 00:27:30 +00001468 // Remember where we were...
1469 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001470
Mike Stump7d699112009-10-01 00:27:30 +00001471 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001472 ++entry_ptr;
1473 Builder.SetInsertPoint(entry, entry_ptr);
1474
John McCall113bee02012-03-10 09:33:50 +00001475 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001476 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001477 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001478 for (const auto &CI : blockDecl->captures()) {
1479 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001480 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001481
Benjamin Kramer8c305922016-02-02 11:06:51 +00001482 if (CGM.getCodeGenOpts().getDebugInfo() >=
1483 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001484 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1485 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001486 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001487 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1488 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001489 continue;
1490 }
John McCall351762c2011-02-07 10:33:21 +00001491
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001492 DI->EmitDeclareOfBlockDeclRefVariable(
1493 variable, BlockPointerDbgLoc, Builder, blockInfo,
1494 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001495 }
Mike Stump2e722b92009-09-30 02:43:10 +00001496 }
Manman Renab08a9a2013-01-04 18:51:35 +00001497 // Recover location if it was changed in the above loop.
1498 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001499 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001500 }
John McCall351762c2011-02-07 10:33:21 +00001501
Mike Stump7d699112009-10-01 00:27:30 +00001502 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001503 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001504 Builder.ClearInsertionPoint();
1505 else
1506 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001507
John McCall351762c2011-02-07 10:33:21 +00001508 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001509
John McCall351762c2011-02-07 10:33:21 +00001510 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001511}
Mike Stump1db7d042009-02-28 09:07:16 +00001512
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001513namespace {
1514
1515/// Represents a type of copy/destroy operation that should be performed for an
1516/// entity that's captured by a block.
1517enum class BlockCaptureEntityKind {
1518 CXXRecord, // Copy or destroy
1519 ARCWeak,
1520 ARCStrong,
Akira Hatanaka7275da02018-02-28 07:15:55 +00001521 NonTrivialCStruct,
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001522 BlockObject, // Assign or release
1523 None
1524};
1525
1526/// Represents a captured entity that requires extra operations in order for
1527/// this entity to be copied or destroyed correctly.
1528struct BlockCaptureManagedEntity {
1529 BlockCaptureEntityKind Kind;
1530 BlockFieldFlags Flags;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001531 const BlockDecl::Capture *CI;
1532 const CGBlockInfo::Capture *Capture;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001533
1534 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1535 const BlockDecl::Capture &CI,
1536 const CGBlockInfo::Capture &Capture)
Akira Hatanaka9978da32018-08-10 15:09:24 +00001537 : Kind(Type), Flags(Flags), CI(&CI), Capture(&Capture) {}
1538
1539 bool operator<(const BlockCaptureManagedEntity &Other) const {
1540 return Capture->getOffset() < Other.Capture->getOffset();
1541 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001542};
1543
1544} // end anonymous namespace
1545
1546static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1547computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1548 const LangOptions &LangOpts) {
1549 if (CI.getCopyExpr()) {
1550 assert(!CI.isByRef());
1551 // don't bother computing flags
1552 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1553 }
1554 BlockFieldFlags Flags;
1555 if (CI.isByRef()) {
1556 Flags = BLOCK_FIELD_IS_BYREF;
1557 if (T.isObjCGCWeak())
1558 Flags |= BLOCK_FIELD_IS_WEAK;
1559 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1560 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001561
1562 Flags = BLOCK_FIELD_IS_OBJECT;
1563 bool isBlockPointer = T->isBlockPointerType();
1564 if (isBlockPointer)
1565 Flags = BLOCK_FIELD_IS_BLOCK;
1566
Akira Hatanaka7275da02018-02-28 07:15:55 +00001567 switch (T.isNonTrivialToPrimitiveCopy()) {
1568 case QualType::PCK_Struct:
1569 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1570 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001571 case QualType::PCK_ARCWeak:
1572 // We need to register __weak direct captures with the runtime.
1573 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001574 case QualType::PCK_ARCStrong:
1575 // We need to retain the copied value for __strong direct captures.
1576 // If it's a block pointer, we have to copy the block and assign that to
1577 // the destination pointer, so we might as well use _Block_object_assign.
1578 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001579 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1580 : BlockCaptureEntityKind::BlockObject,
1581 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001582 case QualType::PCK_Trivial:
1583 case QualType::PCK_VolatileTrivial: {
1584 if (!T->isObjCRetainableType())
1585 // For all other types, the memcpy is fine.
1586 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1587
1588 // Special rules for ARC captures:
1589 Qualifiers QS = T.getQualifiers();
1590
Akira Hatanaka7275da02018-02-28 07:15:55 +00001591 // Non-ARC captures of retainable pointers are strong and
1592 // therefore require a call to _Block_object_assign.
1593 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1594 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1595
1596 // Otherwise the memcpy is fine.
1597 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001598 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001599 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001600 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001601}
1602
1603/// Find the set of block captures that need to be explicitly copied or destroy.
1604static void findBlockCapturedManagedEntities(
1605 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1606 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1607 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1608 const BlockDecl::Capture &, QualType, const LangOptions &)>
1609 Predicate) {
1610 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1611 const VarDecl *Variable = CI.getVariable();
1612 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1613 if (Capture.isConstant())
1614 continue;
1615
1616 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1617 if (Info.first != BlockCaptureEntityKind::None)
1618 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1619 }
Akira Hatanaka9978da32018-08-10 15:09:24 +00001620
1621 // Sort the captures by offset.
1622 llvm::sort(ManagedCaptures.begin(), ManagedCaptures.end());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001623}
1624
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001625namespace {
1626/// Release a __block variable.
1627struct CallBlockRelease final : EHScopeStack::Cleanup {
1628 Address Addr;
1629 BlockFieldFlags FieldFlags;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001630 bool LoadBlockVarAddr, CanThrow;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001631
Akira Hatanaka9978da32018-08-10 15:09:24 +00001632 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1633 bool CT)
1634 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1635 CanThrow(CT) {}
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001636
1637 void Emit(CodeGenFunction &CGF, Flags flags) override {
1638 llvm::Value *BlockVarAddr;
1639 if (LoadBlockVarAddr) {
1640 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1641 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1642 } else {
1643 BlockVarAddr = Addr.getPointer();
1644 }
1645
Akira Hatanaka9978da32018-08-10 15:09:24 +00001646 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001647 }
1648};
1649} // end anonymous namespace
1650
Akira Hatanaka9978da32018-08-10 15:09:24 +00001651/// Check if \p T is a C++ class that has a destructor that can throw.
1652bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1653 if (const auto *RD = T->getAsCXXRecordDecl())
1654 if (const CXXDestructorDecl *DD = RD->getDestructor())
1655 return DD->getType()->getAs<FunctionProtoType>()->canThrow();
1656 return false;
1657}
1658
1659static std::string getCopyDestroyHelperFuncName(
1660 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1661 CharUnits BlockAlignment, bool IsCopyHelper, CodeGenModule &CGM) {
1662 ASTContext &Ctx = CGM.getContext();
1663 std::unique_ptr<ItaniumMangleContext> MC(
1664 ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics()));
1665
1666 std::string Name =
1667 IsCopyHelper ? "__copy_helper_block_" : "__destroy_helper_block_";
1668 if (CGM.getLangOpts().Exceptions)
1669 Name += "e";
1670 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1671 Name += "a";
1672 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1673
1674 for (const BlockCaptureManagedEntity &E : Captures) {
1675 const BlockDecl::Capture &CI = *E.CI;
1676 BlockFieldFlags Flags = E.Flags;
1677 QualType CaptureTy = CI.getVariable()->getType();
1678 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
1679
1680 switch (E.Kind) {
1681 case BlockCaptureEntityKind::CXXRecord: {
1682 Name += "c";
1683 SmallString<256> Str;
1684 llvm::raw_svector_ostream Out(Str);
1685 MC->mangleTypeName(CaptureTy, Out);
1686 Name += llvm::to_string(Str.size()) + Str.c_str();
1687 break;
1688 }
1689 case BlockCaptureEntityKind::ARCWeak:
1690 Name += "w";
1691 break;
1692 case BlockCaptureEntityKind::ARCStrong:
1693 Name += "s";
1694 break;
1695 case BlockCaptureEntityKind::BlockObject: {
1696 const VarDecl *Var = CI.getVariable();
1697 unsigned F = Flags.getBitMask();
1698 if (F & BLOCK_FIELD_IS_BYREF) {
1699 Name += "r";
1700 if (F & BLOCK_FIELD_IS_WEAK)
1701 Name += "w";
1702 else {
1703 if (IsCopyHelper) {
1704 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1705 Name += "c";
1706 } else {
1707 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1708 Name += "d";
1709 }
1710 }
1711 } else {
1712 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1713 if (F == BLOCK_FIELD_IS_BLOCK)
1714 Name += "b";
1715 else
1716 Name += "o";
1717 }
1718 break;
1719 }
1720 case BlockCaptureEntityKind::NonTrivialCStruct: {
1721 bool IsVolatile = CaptureTy.isVolatileQualified();
1722 CharUnits Alignment =
1723 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1724
1725 Name += "n";
1726 std::string Str;
1727 if (IsCopyHelper)
1728 Str = CodeGenFunction::getNonTrivialCopyConstructorStr(
1729 CaptureTy, Alignment, IsVolatile, Ctx);
1730 else
1731 Str = CodeGenFunction::getNonTrivialDestructorStr(CaptureTy, Alignment,
1732 IsVolatile, Ctx);
1733 // The underscore is necessary here because non-trivial copy constructor
1734 // and destructor strings can start with a number.
1735 Name += llvm::to_string(Str.size()) + "_" + Str;
1736 break;
1737 }
1738 case BlockCaptureEntityKind::None:
1739 llvm_unreachable("unexpected block capture kind");
1740 }
1741 }
1742
1743 return Name;
1744}
1745
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001746static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1747 Address Field, QualType CaptureType,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001748 BlockFieldFlags Flags, bool ForCopyHelper,
1749 VarDecl *Var, CodeGenFunction &CGF) {
1750 bool EHOnly = ForCopyHelper;
1751
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001752 switch (CaptureKind) {
1753 case BlockCaptureEntityKind::CXXRecord:
1754 case BlockCaptureEntityKind::ARCWeak:
1755 case BlockCaptureEntityKind::NonTrivialCStruct:
1756 case BlockCaptureEntityKind::ARCStrong: {
1757 if (CaptureType.isDestructedType() &&
1758 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1759 CodeGenFunction::Destroyer *Destroyer =
1760 CaptureKind == BlockCaptureEntityKind::ARCStrong
1761 ? CodeGenFunction::destroyARCStrongImprecise
1762 : CGF.getDestroyer(CaptureType.isDestructedType());
1763 CleanupKind Kind =
1764 EHOnly ? EHCleanup
1765 : CGF.getCleanupKind(CaptureType.isDestructedType());
1766 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1767 }
1768 break;
1769 }
1770 case BlockCaptureEntityKind::BlockObject: {
1771 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1772 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001773 // Calls to _Block_object_dispose along the EH path in the copy helper
1774 // function don't throw as newly-copied __block variables always have a
1775 // reference count of 2.
1776 bool CanThrow =
1777 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1778 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1779 CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001780 }
1781 break;
1782 }
1783 case BlockCaptureEntityKind::None:
1784 llvm_unreachable("unexpected BlockCaptureEntityKind");
1785 }
1786}
1787
Akira Hatanaka9978da32018-08-10 15:09:24 +00001788static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1789 llvm::Function *Fn,
1790 const CGFunctionInfo &FI,
1791 CodeGenModule &CGM) {
1792 if (CapturesNonExternalType) {
1793 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1794 } else {
1795 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1796 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1797 CGM.SetLLVMFunctionAttributes(nullptr, FI, Fn);
1798 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1799 }
1800}
John McCallf593b102013-01-22 03:56:22 +00001801/// Generate the copy-helper function for a block closure object:
1802/// static void block_copy_helper(block_t *dst, block_t *src);
1803/// The runtime will have previously initialized 'dst' by doing a
1804/// bit-copy of 'src'.
1805///
1806/// Note that this copies an entire block closure object to the heap;
1807/// it should not be confused with a 'byref copy helper', which moves
1808/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001809llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001810CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001811 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1812 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1813 computeCopyInfoForBlockCapture);
1814 std::string FuncName =
1815 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
1816 /*IsCopyHelper*/ true, CGM);
1817
1818 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1819 return Func;
1820
John McCall351762c2011-02-07 10:33:21 +00001821 ASTContext &C = getContext();
1822
1823 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001824 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1825 ImplicitParamDecl::Other);
1826 args.push_back(&DstDecl);
1827 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1828 ImplicitParamDecl::Other);
1829 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001830
John McCallc56a8b32016-03-11 04:30:31 +00001831 const CGFunctionInfo &FI =
1832 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001833
John McCall351762c2011-02-07 10:33:21 +00001834 // FIXME: it would be nice if these were mergeable with things with
1835 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001836 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001837
1838 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00001839 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1840 FuncName, &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001841
1842 IdentifierInfo *II
Akira Hatanaka9978da32018-08-10 15:09:24 +00001843 = &CGM.getContext().Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00001844
John McCall351762c2011-02-07 10:33:21 +00001845 FunctionDecl *FD = FunctionDecl::Create(C,
1846 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001847 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001848 SourceLocation(), II, C.VoidTy,
1849 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001850 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001851 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001852
Akira Hatanaka9978da32018-08-10 15:09:24 +00001853 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1854 CGM);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001855 StartFunction(FD, C.VoidTy, Fn, FI, args);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001856 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Chris Lattner2192fe52011-07-18 04:24:23 +00001857 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001858
Alexey Bataev56223232017-06-09 13:40:18 +00001859 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001860 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001861 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001862
Alexey Bataev56223232017-06-09 13:40:18 +00001863 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001864 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001865 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001866
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001867 for (const auto &CopiedCapture : CopiedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001868 const BlockDecl::Capture &CI = *CopiedCapture.CI;
1869 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001870 QualType captureType = CI.getVariable()->getType();
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001871 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001872
1873 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001874 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1875 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001876
1877 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001878 if (CI.getCopyExpr()) {
1879 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1880 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1881 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001882 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001883 // If this is a C struct that requires non-trivial copy construction, emit a
1884 // call to its copy constructor.
1885 } else if (CopiedCapture.Kind ==
1886 BlockCaptureEntityKind::NonTrivialCStruct) {
1887 QualType varType = CI.getVariable()->getType();
1888 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1889 MakeAddrLValue(srcField, varType));
John McCall351762c2011-02-07 10:33:21 +00001890 } else {
1891 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001892 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001893 // At -O0, store null into the destination field (so that the
1894 // storeStrong doesn't over-release) and then call storeStrong.
1895 // This is a workaround to not having an initStrong call.
1896 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001897 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001898 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1899 Builder.CreateStore(null, dstField);
1900 EmitARCStoreStrongCall(dstField, srcValue, true);
1901
1902 // With optimization enabled, take advantage of the fact that
1903 // the blocks runtime guarantees a memcpy of the block data, and
1904 // just emit a retain of the src field.
1905 } else {
1906 EmitARCRetainNonBlock(srcValue);
1907
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001908 // Unless EH cleanup is required, we don't need this anymore, so kill
1909 // it. It's not quite worth the annoyance to avoid creating it in the
1910 // first place.
1911 if (!needsEHCleanup(captureType.isDestructedType()))
1912 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001913 }
1914 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001915 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001916 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001917 llvm::Value *dstAddr =
1918 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001919 llvm::Value *args[] = {
1920 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1921 };
1922
Akira Hatanaka9978da32018-08-10 15:09:24 +00001923 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
John McCall882987f2013-02-28 19:01:20 +00001924 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001925 else
John McCall882987f2013-02-28 19:01:20 +00001926 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
John McCalle68b8f42012-10-17 02:28:37 +00001927 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001928 }
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001929
1930 // Ensure that we destroy the copied object if an exception is thrown later
1931 // in the helper function.
Akira Hatanaka9978da32018-08-10 15:09:24 +00001932 pushCaptureCleanup(CopiedCapture.Kind, dstField, captureType, flags,
1933 /*ForCopyHelper*/ true, CI.getVariable(), *this);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001934 }
1935
John McCallad7c5c12011-02-08 08:22:06 +00001936 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001937
John McCalle3dc1702011-02-15 09:22:45 +00001938 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001939}
1940
Akira Hatanaka7275da02018-02-28 07:15:55 +00001941static BlockFieldFlags
1942getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
1943 QualType T) {
1944 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
1945 if (T->isBlockPointerType())
1946 Flags = BLOCK_FIELD_IS_BLOCK;
1947 return Flags;
1948}
1949
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001950static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1951computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1952 const LangOptions &LangOpts) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001953 if (CI.isByRef()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00001954 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001955 if (T.isObjCGCWeak())
1956 Flags |= BLOCK_FIELD_IS_WEAK;
1957 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1958 }
1959
Akira Hatanaka7275da02018-02-28 07:15:55 +00001960 switch (T.isDestructedType()) {
1961 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001962 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00001963 case QualType::DK_objc_strong_lifetime:
1964 // Use objc_storeStrong for __strong direct captures; the
1965 // dynamic tools really like it when we do this.
1966 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
1967 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1968 case QualType::DK_objc_weak_lifetime:
1969 // Support __weak direct captures.
1970 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
1971 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1972 case QualType::DK_nontrivial_c_struct:
1973 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1974 BlockFieldFlags());
1975 case QualType::DK_none: {
1976 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1977 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
1978 !LangOpts.ObjCAutoRefCount)
1979 return std::make_pair(BlockCaptureEntityKind::BlockObject,
1980 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1981 // Otherwise, we have nothing to do.
1982 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001983 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001984 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001985 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001986}
1987
John McCallf593b102013-01-22 03:56:22 +00001988/// Generate the destroy-helper function for a block closure object:
1989/// static void block_destroy_helper(block_t *theBlock);
1990///
1991/// Note that this destroys a heap-allocated block closure object;
1992/// it should not be confused with a 'byref destroy helper', which
1993/// destroys the heap-allocated contents of an individual __block
1994/// variable.
John McCall351762c2011-02-07 10:33:21 +00001995llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001996CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001997 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1998 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1999 computeDestroyInfoForBlockCapture);
2000 std::string FuncName =
2001 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
2002 /*IsCopyHelper*/ false, CGM);
2003
2004 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2005 return Func;
2006
John McCall351762c2011-02-07 10:33:21 +00002007 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00002008
John McCall351762c2011-02-07 10:33:21 +00002009 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002010 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
2011 ImplicitParamDecl::Other);
2012 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002013
John McCallc56a8b32016-03-11 04:30:31 +00002014 const CGFunctionInfo &FI =
2015 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00002016
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002017 // FIXME: We'd like to put these into a mergable by content, with
2018 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00002019 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00002020
2021 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00002022 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2023 FuncName, &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00002024
2025 IdentifierInfo *II
Akira Hatanaka9978da32018-08-10 15:09:24 +00002026 = &CGM.getContext().Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00002027
John McCall351762c2011-02-07 10:33:21 +00002028 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002029 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002030 SourceLocation(), II, C.VoidTy,
2031 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00002032 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002033
Akira Hatanaka9978da32018-08-10 15:09:24 +00002034 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2035 CGM);
Adrian Prantl22e66b42014-04-11 01:13:04 +00002036 StartFunction(FD, C.VoidTy, Fn, FI, args);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002037 markAsIgnoreThreadCheckingAtRuntime(Fn);
2038
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002039 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Mike Stump6f7d9f82009-03-07 02:53:18 +00002040
Chris Lattner2192fe52011-07-18 04:24:23 +00002041 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00002042
Alexey Bataev56223232017-06-09 13:40:18 +00002043 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002044 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002045 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00002046
John McCallad7c5c12011-02-08 08:22:06 +00002047 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00002048
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002049 for (const auto &DestroyedCapture : DestroyedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002050 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2051 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002052 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00002053
John McCall7f416cc2015-09-08 08:05:57 +00002054 Address srcField =
2055 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00002056
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002057 pushCaptureCleanup(DestroyedCapture.Kind, srcField,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002058 CI.getVariable()->getType(), flags,
2059 /*ForCopyHelper*/ false, CI.getVariable(), *this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00002060 }
2061
John McCall351762c2011-02-07 10:33:21 +00002062 cleanups.ForceCleanup();
2063
John McCallad7c5c12011-02-08 08:22:06 +00002064 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002065
John McCalle3dc1702011-02-15 09:22:45 +00002066 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00002067}
2068
John McCallf9b056b2011-03-31 08:03:29 +00002069namespace {
2070
2071/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00002072class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002073 BlockFieldFlags Flags;
2074
2075public:
2076 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00002077 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00002078
John McCall7f416cc2015-09-08 08:05:57 +00002079 void emitCopy(CodeGenFunction &CGF, Address destField,
2080 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002081 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2082
2083 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2084 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2085
2086 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2087
2088 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2089 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00002090
John McCall7f416cc2015-09-08 08:05:57 +00002091 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00002092 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00002093 }
2094
John McCall7f416cc2015-09-08 08:05:57 +00002095 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002096 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2097 llvm::Value *value = CGF.Builder.CreateLoad(field);
2098
Akira Hatanaka9978da32018-08-10 15:09:24 +00002099 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
John McCallf9b056b2011-03-31 08:03:29 +00002100 }
2101
Craig Topper4f12f102014-03-12 06:41:41 +00002102 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002103 id.AddInteger(Flags.getBitMask());
2104 }
2105};
2106
John McCall31168b02011-06-15 23:02:42 +00002107/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00002108class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002109public:
John McCall7f416cc2015-09-08 08:05:57 +00002110 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002111
John McCall7f416cc2015-09-08 08:05:57 +00002112 void emitCopy(CodeGenFunction &CGF, Address destField,
2113 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002114 CGF.EmitARCMoveWeak(destField, srcField);
2115 }
2116
John McCall7f416cc2015-09-08 08:05:57 +00002117 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00002118 CGF.EmitARCDestroyWeak(field);
2119 }
2120
Craig Topper4f12f102014-03-12 06:41:41 +00002121 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002122 // 0 is distinguishable from all pointers and byref flags
2123 id.AddInteger(0);
2124 }
2125};
2126
2127/// Emits the copy/dispose helpers for an ARC __block __strong variable
2128/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002129class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002130public:
John McCall7f416cc2015-09-08 08:05:57 +00002131 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002132
John McCall7f416cc2015-09-08 08:05:57 +00002133 void emitCopy(CodeGenFunction &CGF, Address destField,
2134 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002135 // Do a "move" by copying the value and then zeroing out the old
2136 // variable.
2137
John McCall7f416cc2015-09-08 08:05:57 +00002138 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002139
John McCall31168b02011-06-15 23:02:42 +00002140 llvm::Value *null =
2141 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00002142
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002143 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002144 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002145 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2146 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2147 return;
2148 }
John McCall7f416cc2015-09-08 08:05:57 +00002149 CGF.Builder.CreateStore(value, destField);
2150 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00002151 }
2152
John McCall7f416cc2015-09-08 08:05:57 +00002153 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002154 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00002155 }
2156
Craig Topper4f12f102014-03-12 06:41:41 +00002157 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002158 // 1 is distinguishable from all pointers and byref flags
2159 id.AddInteger(1);
2160 }
2161};
2162
John McCall3a237aa2011-11-09 03:17:26 +00002163/// Emits the copy/dispose helpers for an ARC __block __strong
2164/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002165class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00002166public:
John McCall7f416cc2015-09-08 08:05:57 +00002167 ARCStrongBlockByrefHelpers(CharUnits alignment)
2168 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00002169
John McCall7f416cc2015-09-08 08:05:57 +00002170 void emitCopy(CodeGenFunction &CGF, Address destField,
2171 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00002172 // Do the copy with objc_retainBlock; that's all that
2173 // _Block_object_assign would do anyway, and we'd have to pass the
2174 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00002175 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00002176 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00002177 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00002178 }
2179
John McCall7f416cc2015-09-08 08:05:57 +00002180 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002181 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00002182 }
2183
Craig Topper4f12f102014-03-12 06:41:41 +00002184 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00002185 // 2 is distinguishable from all pointers and byref flags
2186 id.AddInteger(2);
2187 }
2188};
2189
John McCallf9b056b2011-03-31 08:03:29 +00002190/// Emits the copy/dispose helpers for a __block variable with a
2191/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002192class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002193 QualType VarType;
2194 const Expr *CopyExpr;
2195
2196public:
2197 CXXByrefHelpers(CharUnits alignment, QualType type,
2198 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002199 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002200
Craig Topper8a13c412014-05-21 05:09:00 +00002201 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002202 void emitCopy(CodeGenFunction &CGF, Address destField,
2203 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002204 if (!CopyExpr) return;
2205 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2206 }
2207
John McCall7f416cc2015-09-08 08:05:57 +00002208 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002209 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2210 CGF.PushDestructorCleanup(VarType, field);
2211 CGF.PopCleanupBlocks(cleanupDepth);
2212 }
2213
Craig Topper4f12f102014-03-12 06:41:41 +00002214 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002215 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2216 }
2217};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002218
2219/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2220/// C struct.
2221class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2222 QualType VarType;
2223
2224public:
2225 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2226 : BlockByrefHelpers(alignment), VarType(type) {}
2227
2228 void emitCopy(CodeGenFunction &CGF, Address destField,
2229 Address srcField) override {
2230 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2231 CGF.MakeAddrLValue(srcField, VarType));
2232 }
2233
2234 bool needsDispose() const override {
2235 return VarType.isDestructedType();
2236 }
2237
2238 void emitDispose(CodeGenFunction &CGF, Address field) override {
2239 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2240 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2241 CGF.PopCleanupBlocks(cleanupDepth);
2242 }
2243
2244 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2245 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2246 }
2247};
John McCallf9b056b2011-03-31 08:03:29 +00002248} // end anonymous namespace
2249
2250static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002251generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2252 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002253 ASTContext &Context = CGF.getContext();
2254
2255 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002256
John McCalla738c252011-03-09 04:27:21 +00002257 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002258 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2259 ImplicitParamDecl::Other);
2260 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002261
Alexey Bataev56223232017-06-09 13:40:18 +00002262 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2263 ImplicitParamDecl::Other);
2264 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002265
John McCallc56a8b32016-03-11 04:30:31 +00002266 const CGFunctionInfo &FI =
2267 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002268
John McCall7f416cc2015-09-08 08:05:57 +00002269 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002270
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002271 // FIXME: We'd like to put these into a mergable by content, with
2272 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002273 llvm::Function *Fn =
2274 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002275 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002276
2277 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002278 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002279
John McCallf9b056b2011-03-31 08:03:29 +00002280 FunctionDecl *FD = FunctionDecl::Create(Context,
2281 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002282 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002283 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002284 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002285 false, false);
John McCall31168b02011-06-15 23:02:42 +00002286
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002287 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002288
Adrian Prantl22e66b42014-04-11 01:13:04 +00002289 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002290
John McCall7f416cc2015-09-08 08:05:57 +00002291 if (generator.needsCopy()) {
2292 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002293
John McCallf9b056b2011-03-31 08:03:29 +00002294 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002295 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002296 destField = Address(CGF.Builder.CreateLoad(destField),
2297 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002298 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002299 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2300 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002301
John McCallf9b056b2011-03-31 08:03:29 +00002302 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002303 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002304 srcField = Address(CGF.Builder.CreateLoad(srcField),
2305 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002306 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002307 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2308 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002309
John McCall7f416cc2015-09-08 08:05:57 +00002310 generator.emitCopy(CGF, destField, srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002311 }
John McCallf9b056b2011-03-31 08:03:29 +00002312
2313 CGF.FinishFunction();
2314
2315 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002316}
2317
John McCallf9b056b2011-03-31 08:03:29 +00002318/// Build the copy helper for a __block variable.
2319static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002320 const BlockByrefInfo &byrefInfo,
2321 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002322 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002323 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002324}
2325
2326/// Generate code for a __block variable's dispose helper.
2327static llvm::Constant *
2328generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002329 const BlockByrefInfo &byrefInfo,
2330 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002331 ASTContext &Context = CGF.getContext();
2332 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002333
John McCalla738c252011-03-09 04:27:21 +00002334 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002335 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2336 ImplicitParamDecl::Other);
2337 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002338
John McCallc56a8b32016-03-11 04:30:31 +00002339 const CGFunctionInfo &FI =
2340 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002341
John McCall7f416cc2015-09-08 08:05:57 +00002342 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002343
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002344 // FIXME: We'd like to put these into a mergable by content, with
2345 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002346 llvm::Function *Fn =
2347 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002348 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002349 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002350
2351 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002352 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002353
John McCallf9b056b2011-03-31 08:03:29 +00002354 FunctionDecl *FD = FunctionDecl::Create(Context,
2355 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002356 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002357 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002358 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002359 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002360
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002361 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002362
Adrian Prantl22e66b42014-04-11 01:13:04 +00002363 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002364
John McCall7f416cc2015-09-08 08:05:57 +00002365 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002366 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002367 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2368 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2369 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2370 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002371
John McCall7f416cc2015-09-08 08:05:57 +00002372 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002373 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002374
John McCallf9b056b2011-03-31 08:03:29 +00002375 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002376
John McCallf9b056b2011-03-31 08:03:29 +00002377 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002378}
2379
John McCallf9b056b2011-03-31 08:03:29 +00002380/// Build the dispose helper for a __block variable.
2381static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002382 const BlockByrefInfo &byrefInfo,
2383 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002384 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002385 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002386}
2387
John McCallf593b102013-01-22 03:56:22 +00002388/// Lazily build the copy and dispose helpers for a __block variable
2389/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002390template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002391static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2392 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002393 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002394 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002395
2396 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002397 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002398 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2399 if (node) return static_cast<T*>(node);
2400
John McCall7f416cc2015-09-08 08:05:57 +00002401 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2402 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002403
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002404 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002405 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2406 return copy;
2407}
2408
John McCallf593b102013-01-22 03:56:22 +00002409/// Build the copy and dispose helpers for the given __block variable
2410/// emission. Places the helpers in the global cache. Returns null
2411/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002412BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002413CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002414 const AutoVarEmission &emission) {
2415 const VarDecl &var = *emission.Variable;
2416 QualType type = var.getType();
2417
John McCall7f416cc2015-09-08 08:05:57 +00002418 auto &byrefInfo = getBlockByrefInfo(&var);
2419
2420 // The alignment we care about for the purposes of uniquing byref
2421 // helpers is the alignment of the actual byref value field.
2422 CharUnits valueAlignment =
2423 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002424
John McCallf9b056b2011-03-31 08:03:29 +00002425 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002426 const Expr *copyExpr =
2427 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002428 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002429
David Blaikie92551612015-08-13 23:53:09 +00002430 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002431 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002432 }
2433
Akira Hatanaka7275da02018-02-28 07:15:55 +00002434 // If type is a non-trivial C struct type that is non-trivial to
2435 // destructly move or destroy, build the copy and dispose helpers.
2436 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2437 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2438 return ::buildByrefHelpers(
2439 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2440
John McCall31168b02011-06-15 23:02:42 +00002441 // Otherwise, if we don't have a retainable type, there's nothing to do.
2442 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002443 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002444
2445 Qualifiers qs = type.getQualifiers();
2446
2447 // If we have lifetime, that dominates.
2448 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002449 switch (lifetime) {
2450 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2451
2452 // These are just bits as far as the runtime is concerned.
2453 case Qualifiers::OCL_ExplicitNone:
2454 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002455 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002456
2457 // Tell the runtime that this is ARC __weak, called by the
2458 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002459 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002460 return ::buildByrefHelpers(CGM, byrefInfo,
2461 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002462
2463 // ARC __strong __block variables need to be retained.
2464 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002465 // Block pointers need to be copied, and there's no direct
2466 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002467 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002468 return ::buildByrefHelpers(CGM, byrefInfo,
2469 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002470
2471 // Otherwise, we transfer ownership of the retain from the stack
2472 // to the heap.
2473 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002474 return ::buildByrefHelpers(CGM, byrefInfo,
2475 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002476 }
2477 }
2478 llvm_unreachable("fell out of lifetime switch!");
2479 }
2480
John McCallf9b056b2011-03-31 08:03:29 +00002481 BlockFieldFlags flags;
2482 if (type->isBlockPointerType()) {
2483 flags |= BLOCK_FIELD_IS_BLOCK;
Fangrui Song6907ce22018-07-30 19:24:48 +00002484 } else if (CGM.getContext().isObjCNSObjectType(type) ||
John McCallf9b056b2011-03-31 08:03:29 +00002485 type->isObjCObjectPointerType()) {
2486 flags |= BLOCK_FIELD_IS_OBJECT;
2487 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002488 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002489 }
2490
2491 if (type.isObjCGCWeak())
2492 flags |= BLOCK_FIELD_IS_WEAK;
2493
John McCall7f416cc2015-09-08 08:05:57 +00002494 return ::buildByrefHelpers(CGM, byrefInfo,
2495 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002496}
2497
John McCall7f416cc2015-09-08 08:05:57 +00002498Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2499 const VarDecl *var,
2500 bool followForward) {
2501 auto &info = getBlockByrefInfo(var);
2502 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002503}
2504
John McCall7f416cc2015-09-08 08:05:57 +00002505Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2506 const BlockByrefInfo &info,
2507 bool followForward,
2508 const llvm::Twine &name) {
2509 // Chase the forwarding address if requested.
2510 if (followForward) {
2511 Address forwardingAddr =
2512 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2513 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2514 }
2515
2516 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2517 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002518}
2519
John McCall7f416cc2015-09-08 08:05:57 +00002520/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002521/// into:
2522///
2523/// struct {
2524/// void *__isa;
2525/// void *__forwarding;
2526/// int32_t __flags;
2527/// int32_t __size;
2528/// void *__copy_helper; // only if needed
2529/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002530/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002531/// char padding[X]; // only if needed
2532/// T x;
2533/// } x
2534///
John McCall7f416cc2015-09-08 08:05:57 +00002535const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2536 auto it = BlockByrefInfos.find(D);
2537 if (it != BlockByrefInfos.end())
2538 return it->second;
John McCall73064872011-03-31 01:59:53 +00002539
John McCall7f416cc2015-09-08 08:05:57 +00002540 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002541 llvm::StructType::create(getLLVMContext(),
2542 "struct.__block_byref_" + D->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00002543
John McCall7f416cc2015-09-08 08:05:57 +00002544 QualType Ty = D->getType();
2545
2546 CharUnits size;
2547 SmallVector<llvm::Type *, 8> types;
Fangrui Song6907ce22018-07-30 19:24:48 +00002548
John McCall73064872011-03-31 01:59:53 +00002549 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002550 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002551 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002552
John McCall73064872011-03-31 01:59:53 +00002553 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002554 types.push_back(llvm::PointerType::getUnqual(byrefType));
2555 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002556
John McCall73064872011-03-31 01:59:53 +00002557 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002558 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002559 size += CharUnits::fromQuantity(4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002560
John McCall73064872011-03-31 01:59:53 +00002561 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002562 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002563 size += CharUnits::fromQuantity(4);
2564
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002565 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002566 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2567 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002568 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002569 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002570 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002571
John McCall73064872011-03-31 01:59:53 +00002572 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002573 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002574 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002575 }
John McCall7f416cc2015-09-08 08:05:57 +00002576
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002577 bool HasByrefExtendedLayout = false;
2578 Qualifiers::ObjCLifetime Lifetime;
2579 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002580 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002581 /// void *__byref_variable_layout;
2582 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002583 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002584 }
2585
2586 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002587 llvm::Type *varTy = ConvertTypeForMem(Ty);
2588
2589 bool packed = false;
2590 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002591 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002592
2593 // We may have to insert padding.
2594 if (varOffset != size) {
2595 llvm::Type *paddingTy =
2596 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2597
2598 types.push_back(paddingTy);
2599 size = varOffset;
2600
2601 // Conversely, we might have to prevent LLVM from inserting padding.
2602 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2603 > varAlign.getQuantity()) {
2604 packed = true;
2605 }
2606 types.push_back(varTy);
2607
2608 byrefType->setBody(types, packed);
2609
2610 BlockByrefInfo info;
2611 info.Type = byrefType;
2612 info.FieldIndex = types.size() - 1;
2613 info.FieldOffset = varOffset;
2614 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2615
2616 auto pair = BlockByrefInfos.insert({D, info});
2617 assert(pair.second && "info was inserted recursively?");
2618 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002619}
2620
2621/// Initialize the structural components of a __block variable, i.e.
2622/// everything but the actual object.
2623void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002624 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002625 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002626
John McCallf9b056b2011-03-31 08:03:29 +00002627 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002628 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002629 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2630
2631 unsigned nextHeaderIndex = 0;
2632 CharUnits nextHeaderOffset;
2633 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2634 const Twine &name) {
2635 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2636 nextHeaderOffset, name);
2637 Builder.CreateStore(value, fieldAddr);
2638
2639 nextHeaderIndex++;
2640 nextHeaderOffset += fieldSize;
2641 };
John McCallf9b056b2011-03-31 08:03:29 +00002642
2643 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002644 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002645
2646 const VarDecl &D = *emission.Variable;
2647 QualType type = D.getType();
2648
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002649 bool HasByrefExtendedLayout;
2650 Qualifiers::ObjCLifetime ByrefLifetime;
2651 bool ByRefHasLifetime =
2652 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002653
John McCallf9b056b2011-03-31 08:03:29 +00002654 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002655
2656 // Initialize the 'isa', which is just 0 or 1.
2657 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002658 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002659 isa = 1;
2660 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002661 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002662
2663 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002664 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002665
2666 // Blocks ABI:
2667 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002668 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002669 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002670 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2671 if (ByRefHasLifetime) {
2672 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2673 else switch (ByrefLifetime) {
2674 case Qualifiers::OCL_Strong:
2675 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2676 break;
2677 case Qualifiers::OCL_Weak:
2678 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2679 break;
2680 case Qualifiers::OCL_ExplicitNone:
2681 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2682 break;
2683 case Qualifiers::OCL_None:
2684 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2685 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2686 break;
2687 default:
2688 break;
2689 }
2690 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2691 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2692 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2693 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2694 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2695 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2696 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2697 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2698 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2699 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2700 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2701 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2702 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2703 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2704 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2705 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2706 }
2707 printf("\n");
2708 }
2709 }
John McCall7f416cc2015-09-08 08:05:57 +00002710 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2711 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002712
John McCallf9b056b2011-03-31 08:03:29 +00002713 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2714 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002715 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002716
John McCallf9b056b2011-03-31 08:03:29 +00002717 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002718 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2719 "byref.copyHelper");
2720 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2721 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002722 }
John McCall7f416cc2015-09-08 08:05:57 +00002723
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002724 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002725 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2726 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002727 }
John McCall73064872011-03-31 01:59:53 +00002728}
2729
Akira Hatanaka9978da32018-08-10 15:09:24 +00002730void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2731 bool CanThrow) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002732 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002733 llvm::Value *args[] = {
2734 Builder.CreateBitCast(V, Int8PtrTy),
2735 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2736 };
Akira Hatanaka9978da32018-08-10 15:09:24 +00002737
2738 if (CanThrow)
2739 EmitRuntimeCallOrInvoke(F, args);
2740 else
2741 EmitNounwindRuntimeCall(F, args);
Mike Stump626aecc2009-03-05 01:23:13 +00002742}
John McCall73064872011-03-31 01:59:53 +00002743
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002744void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2745 BlockFieldFlags Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002746 bool LoadBlockVarAddr, bool CanThrow) {
2747 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2748 CanThrow);
John McCall73064872011-03-31 01:59:53 +00002749}
John McCall7959fee2011-09-09 20:41:01 +00002750
2751/// Adjust the declaration of something from the blocks API.
2752static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2753 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002754 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002755
2756 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2757 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2758 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2759 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2760
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002761 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2762 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2763 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002764
2765 const NamedDecl *ND = nullptr;
2766 for (const auto &Result : DC->lookup(&II))
2767 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2768 (ND = dyn_cast<VarDecl>(Result)))
2769 break;
2770
2771 // TODO: support static blocks runtime
2772 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2773 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2774 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2775 } else {
2776 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2777 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2778 }
2779 }
2780
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002781 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2782 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002783 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002784
2785 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002786}
2787
2788llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2789 if (BlockObjectDispose)
2790 return BlockObjectDispose;
2791
2792 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2793 llvm::FunctionType *fty
2794 = llvm::FunctionType::get(VoidTy, args, false);
2795 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2796 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2797 return BlockObjectDispose;
2798}
2799
2800llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2801 if (BlockObjectAssign)
2802 return BlockObjectAssign;
2803
2804 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2805 llvm::FunctionType *fty
2806 = llvm::FunctionType::get(VoidTy, args, false);
2807 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2808 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2809 return BlockObjectAssign;
2810}
2811
2812llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2813 if (NSConcreteGlobalBlock)
2814 return NSConcreteGlobalBlock;
2815
2816 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002817 Int8PtrTy->getPointerTo(),
2818 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002819 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2820 return NSConcreteGlobalBlock;
2821}
2822
2823llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2824 if (NSConcreteStackBlock)
2825 return NSConcreteStackBlock;
2826
2827 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002828 Int8PtrTy->getPointerTo(),
2829 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002830 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002831 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002832}