blob: 617856a7b43ed9ac63834906791578d45d073f5d [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000021#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000022#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000023#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000024#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000029#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000030
Anders Carlsson2437cbf2009-02-12 00:39:25 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall08ef4662011-11-10 08:15:53 +000034CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
35 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000036 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000037 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000038 DominatingIP(nullptr) {
39
John McCall08ef4662011-11-10 08:15:53 +000040 // Skip asm prefix, if any. 'name' is usually taken directly from
41 // the mangled name of the enclosing function.
42 if (!name.empty() && name[0] == '\01')
43 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000044}
45
John McCallf9b056b2011-03-31 08:03:29 +000046// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000047BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000048
John McCall351762c2011-02-07 10:33:21 +000049/// Build the given block as a global block.
50static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo,
52 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000053
John McCall351762c2011-02-07 10:33:21 +000054/// Build the helper function to copy a block.
55static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
58}
59
Alp Tokerf6a24ce2013-12-05 16:25:25 +000060/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000061static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
62 const CGBlockInfo &blockInfo) {
63 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
64}
65
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000066/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
67/// buildBlockDescriptor is accessed from 5th field of the Block_literal
68/// meta-data and contains stationary information about the block literal.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000069/// Its definition will have 4 (or optionally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000070/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000071/// struct Block_descriptor {
72/// unsigned long reserved;
73/// unsigned long size; // size of Block_literal metadata in bytes.
74/// void *copy_func_helper_decl; // optional copy helper.
75/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000077/// void *block_layout_info; // encoding of captured block variables.
78/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000079/// \endcode
John McCall351762c2011-02-07 10:33:21 +000080static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
81 const CGBlockInfo &blockInfo) {
82 ASTContext &C = CGM.getContext();
83
John McCall6c9f1fdb2016-11-19 08:17:24 +000084 llvm::IntegerType *ulong =
85 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
86 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000087 if (CGM.getLangOpts().OpenCL)
88 i8p =
89 llvm::Type::getInt8PtrTy(
90 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
91 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000092 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000093
John McCall23c9dc62016-11-28 22:18:27 +000094 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000098 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000099
100 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000101 // FIXME: What is the right way to say this doesn't fit? We should give
102 // a user diagnostic in that case. Better fix would be to change the
103 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000104 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000105
John McCall351762c2011-02-07 10:33:21 +0000106 // Optional copy/dispose helpers.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000107 if (blockInfo.needsCopyDisposeHelpers()) {
Mike Stump85284ba2009-02-13 16:19:19 +0000108 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110
111 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000112 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000113 }
114
John McCall351762c2011-02-07 10:33:21 +0000115 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
116 std::string typeAtEncoding =
117 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000118 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000119 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000120
John McCall351762c2011-02-07 10:33:21 +0000121 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 if (C.getLangOpts().ObjC1) {
123 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000124 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000127 }
John McCall351762c2011-02-07 10:33:21 +0000128 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000129 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000130
Joey Goulyddbda402016-08-10 15:57:02 +0000131 unsigned AddrSpace = 0;
132 if (C.getLangOpts().OpenCL)
133 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000134
John McCall351762c2011-02-07 10:33:21 +0000135 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000136 elements.finishAndCreateGlobal("__block_descriptor_tmp",
137 CGM.getPointerAlign(),
138 /*constant*/ true,
139 llvm::GlobalValue::InternalLinkage,
140 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000141
John McCall351762c2011-02-07 10:33:21 +0000142 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000143}
144
John McCall351762c2011-02-07 10:33:21 +0000145/*
146 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000147
John McCall351762c2011-02-07 10:33:21 +0000148 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
149 struct Block_literal {
150 /// Initialized to one of:
151 /// extern void *_NSConcreteStackBlock[];
152 /// extern void *_NSConcreteGlobalBlock[];
153 ///
154 /// In theory, we could start one off malloc'ed by setting
155 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
156 /// this isa:
157 /// extern void *_NSConcreteMallocBlock[];
158 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000159
John McCall351762c2011-02-07 10:33:21 +0000160 /// These are the flags (with corresponding bit number) that the
161 /// compiler is actually supposed to know about.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000162 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
John McCall351762c2011-02-07 10:33:21 +0000163 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
164 /// descriptor provides copy and dispose helper functions
165 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
166 /// object with a nontrivial destructor or copy constructor
167 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
168 /// as global memory
169 /// 29. BLOCK_USE_STRET - indicates that the block function
170 /// uses stret, which objc_msgSend needs to know about
171 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
172 /// @encoded signature string
173 /// And we're not supposed to manipulate these:
174 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
175 /// to malloc'ed memory
176 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
177 /// to GC-allocated memory
178 /// Additionally, the bottom 16 bits are a reference count which
179 /// should be zero on the stack.
180 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000181
John McCall351762c2011-02-07 10:33:21 +0000182 /// Reserved; should be zero-initialized.
183 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000184
John McCall351762c2011-02-07 10:33:21 +0000185 /// Function pointer generated from block literal.
186 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000187
John McCall351762c2011-02-07 10:33:21 +0000188 /// Block description metadata generated from block literal.
189 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000190
John McCall351762c2011-02-07 10:33:21 +0000191 /// Captured values follow.
192 _CapturesTypes captures...;
193 };
194 */
David Chisnall950a9512009-11-17 19:33:30 +0000195
John McCall351762c2011-02-07 10:33:21 +0000196namespace {
197 /// A chunk of data that we actually have to capture in the block.
198 struct BlockLayoutChunk {
199 CharUnits Alignment;
200 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000201 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000202 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000203 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000204 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000205
John McCall351762c2011-02-07 10:33:21 +0000206 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000207 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000208 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000209 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000210 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000211 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000212
John McCall351762c2011-02-07 10:33:21 +0000213 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000214 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
215 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000216 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000217 info.CXXThisOffset = offset;
218 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000219 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
220 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000221 }
John McCall87fe5d52010-05-20 01:18:31 +0000222 }
John McCall351762c2011-02-07 10:33:21 +0000223 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000224
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000225 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
226 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000227 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000228 if (left.Alignment != right.Alignment)
229 return left.Alignment > right.Alignment;
230
231 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000232 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000233 return 1;
234 if (chunk.Lifetime == Qualifiers::OCL_Strong)
235 return 0;
236 if (chunk.Lifetime == Qualifiers::OCL_Weak)
237 return 2;
238 return 3;
239 };
240
241 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000242 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000243} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000244
John McCallb0a3ecb2011-02-08 03:07:00 +0000245/// Determines if the given type is safe for constant capture in C++.
246static bool isSafeForCXXConstantCapture(QualType type) {
247 const RecordType *recordType =
248 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
249
250 // Only records can be unsafe.
251 if (!recordType) return true;
252
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000253 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000254
255 // Maintain semantics for classes with non-trivial dtors or copy ctors.
256 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000257 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000258
259 // Otherwise, we just have to make sure there aren't any mutable
260 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000261 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000262}
263
John McCall351762c2011-02-07 10:33:21 +0000264/// It is illegal to modify a const object after initialization.
265/// Therefore, if a const object has a constant initializer, we don't
266/// actually need to keep storage for it in the block; we'll just
267/// rematerialize it at the start of the block function. This is
268/// acceptable because we make no promises about address stability of
269/// captured variables.
270static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000271 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000272 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000273 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000274 // rematerialize default arguments of function parameters.
275 if (isa<ParmVarDecl>(var))
276 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000277
John McCall351762c2011-02-07 10:33:21 +0000278 QualType type = var->getType();
279
280 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000281 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000282
John McCallb0a3ecb2011-02-08 03:07:00 +0000283 // Furthermore, in C++ we have to worry about mutable fields:
284 // C++ [dcl.type.cv]p4:
285 // Except that any class member declared mutable can be
286 // modified, any attempt to modify a const object during its
287 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000289 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000290
291 // If the variable doesn't have any initializer (shouldn't this be
292 // invalid?), it's not clear what we should do. Maybe capture as
293 // zero?
294 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000295 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000296
John McCallde0fe072017-08-15 21:42:52 +0000297 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000298}
299
300/// Get the low bit of a nonzero character count. This is the
301/// alignment of the nth byte if the 0th byte is universally aligned.
302static CharUnits getLowBit(CharUnits v) {
303 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
304}
305
306static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000307 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000308
309 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000310 if (CGM.getLangOpts().OpenCL) {
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000311 // The header is basically 'struct { int; int;
Yaxun Liu10712d92017-10-04 20:32:17 +0000312 // custom_fields; }'. Assert that struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000313 elementTypes.push_back(CGM.IntTy); /* total size */
314 elementTypes.push_back(CGM.IntTy); /* align */
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000315 unsigned Offset = 2 * CGM.getIntSize().getQuantity();
316 unsigned BlockAlign = CGM.getIntAlign().getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000317 if (auto *Helper =
318 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
319 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
320 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
321 // If necessary, add padding fields to the custom fields.
322 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
323 if (BlockAlign < Align)
324 BlockAlign = Align;
325 assert(Offset % Align == 0);
326 Offset += CGM.getDataLayout().getTypeAllocSize(I);
327 elementTypes.push_back(I);
328 }
329 }
330 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
331 info.BlockSize = CharUnits::fromQuantity(Offset);
332 } else {
333 // The header is basically 'struct { void *; int; int; void *; void *; }'.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000334 // Assert that the struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000335 assert(CGM.getIntSize() <= CGM.getPointerSize());
336 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
337 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
338 info.BlockAlign = CGM.getPointerAlign();
339 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
340 elementTypes.push_back(CGM.VoidPtrTy);
341 elementTypes.push_back(CGM.IntTy);
342 elementTypes.push_back(CGM.IntTy);
343 elementTypes.push_back(CGM.VoidPtrTy);
344 elementTypes.push_back(CGM.getBlockDescriptorType());
345 }
John McCall351762c2011-02-07 10:33:21 +0000346}
347
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000348static QualType getCaptureFieldType(const CodeGenFunction &CGF,
349 const BlockDecl::Capture &CI) {
350 const VarDecl *VD = CI.getVariable();
351
352 // If the variable is captured by an enclosing block or lambda expression,
353 // use the type of the capture field.
354 if (CGF.BlockInfo && CI.isNested())
355 return CGF.BlockInfo->getCapture(VD).fieldType();
356 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
357 return FD->getType();
358 return VD->getType();
359}
360
John McCall351762c2011-02-07 10:33:21 +0000361/// Compute the layout of the given block. Attempts to lay the block
362/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000363static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
364 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000365 ASTContext &C = CGM.getContext();
366 const BlockDecl *block = info.getBlockDecl();
367
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000368 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000369 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000370 bool hasNonConstantCustomFields = false;
371 if (auto *OpenCLHelper =
372 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
373 hasNonConstantCustomFields =
374 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
375 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000376 info.StructureType =
377 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
378 info.CanBeGlobal = true;
379 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000380 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000381 else if (C.getLangOpts().ObjC1 &&
382 CGM.getLangOpts().getGC() == LangOptions::NonGC)
383 info.HasCapturedVariableLayout = true;
384
John McCall351762c2011-02-07 10:33:21 +0000385 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000386 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000387 layout.reserve(block->capturesCXXThis() +
388 (block->capture_end() - block->capture_begin()));
389
390 CharUnits maxFieldAlign;
391
392 // First, 'this'.
393 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000394 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
395 "Can't capture 'this' outside a method");
396 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000397
John McCall7f416cc2015-09-08 08:05:57 +0000398 // Theoretically, this could be in a different address space, so
399 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000400 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000401 std::pair<CharUnits,CharUnits> tinfo
402 = CGM.getContext().getTypeInfoInChars(thisType);
403 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
404
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000405 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
406 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000407 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000408 }
409
410 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000411 for (const auto &CI : block->captures()) {
412 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000413
Aaron Ballman9371dd22014-03-14 18:34:04 +0000414 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000415 // We have to copy/dispose of the __block reference.
416 info.NeedsCopyDispose = true;
417
John McCall351762c2011-02-07 10:33:21 +0000418 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000419 CharUnits align = CGM.getPointerAlign();
420 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000421
John McCall7f416cc2015-09-08 08:05:57 +0000422 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
423 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000424 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000425 continue;
426 }
427
428 // Otherwise, build a layout chunk with the size and alignment of
429 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000430 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000431 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
432 continue;
433 }
434
John McCall31168b02011-06-15 23:02:42 +0000435 // If we have a lifetime qualifier, honor it for capture purposes.
436 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000437 Qualifiers::ObjCLifetime lifetime =
438 variable->getType().getObjCLifetime();
439 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000440 switch (lifetime) {
441 case Qualifiers::OCL_None: llvm_unreachable("impossible");
442 case Qualifiers::OCL_ExplicitNone:
443 case Qualifiers::OCL_Autoreleasing:
444 break;
John McCall351762c2011-02-07 10:33:21 +0000445
John McCall31168b02011-06-15 23:02:42 +0000446 case Qualifiers::OCL_Strong:
447 case Qualifiers::OCL_Weak:
448 info.NeedsCopyDispose = true;
449 }
450
451 // Block pointers require copy/dispose. So do Objective-C pointers.
452 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000453 // But honor the inert __unsafe_unretained qualifier, which doesn't
454 // actually make it into the type system.
455 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
456 lifetime = Qualifiers::OCL_ExplicitNone;
457 } else {
458 info.NeedsCopyDispose = true;
459 // used for mrr below.
460 lifetime = Qualifiers::OCL_Strong;
461 }
John McCall351762c2011-02-07 10:33:21 +0000462
463 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000464 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000465 info.NeedsCopyDispose = true;
466 info.HasCXXObject = true;
467
Akira Hatanaka7275da02018-02-28 07:15:55 +0000468 // So do C structs that require non-trivial copy construction or
469 // destruction.
470 } else if (variable->getType().isNonTrivialToPrimitiveCopy() ==
471 QualType::PCK_Struct ||
472 variable->getType().isDestructedType() ==
473 QualType::DK_nontrivial_c_struct) {
474 info.NeedsCopyDispose = true;
475
John McCall351762c2011-02-07 10:33:21 +0000476 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000477 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000478 if (const CXXRecordDecl *record =
479 variable->getType()->getAsCXXRecordDecl()) {
480 if (!record->hasTrivialDestructor()) {
481 info.HasCXXObject = true;
482 info.NeedsCopyDispose = true;
483 }
484 }
485 }
486
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000487 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000488 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000489 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000490
John McCall351762c2011-02-07 10:33:21 +0000491 maxFieldAlign = std::max(maxFieldAlign, align);
492
Jay Foad7c57be32011-07-11 09:56:20 +0000493 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000494 CGM.getTypes().ConvertTypeForMem(VT);
495
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000496 layout.push_back(
497 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000498 }
499
500 // If that was everything, we're done here.
501 if (layout.empty()) {
502 info.StructureType =
503 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
504 info.CanBeGlobal = true;
505 return;
506 }
507
508 // Sort the layout by alignment. We have to use a stable sort here
509 // to get reproducible results. There should probably be an
510 // llvm::array_pod_stable_sort.
511 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000512
513 // Needed for blocks layout info.
514 info.BlockHeaderForcedGapOffset = info.BlockSize;
515 info.BlockHeaderForcedGapSize = CharUnits::Zero();
516
John McCall351762c2011-02-07 10:33:21 +0000517 CharUnits &blockSize = info.BlockSize;
518 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
519
520 // Assuming that the first byte in the header is maximally aligned,
521 // get the alignment of the first byte following the header.
522 CharUnits endAlign = getLowBit(blockSize);
523
524 // If the end of the header isn't satisfactorily aligned for the
525 // maximum thing, look for things that are okay with the header-end
526 // alignment, and keep appending them until we get something that's
527 // aligned right. This algorithm is only guaranteed optimal if
528 // that condition is satisfied at some point; otherwise we can get
529 // things like:
530 // header // next byte has alignment 4
531 // something_with_size_5; // next byte has alignment 1
532 // something_with_alignment_8;
533 // which has 7 bytes of padding, as opposed to the naive solution
534 // which might have less (?).
535 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000537 li = layout.begin() + 1, le = layout.end();
538
539 // Look for something that the header end is already
540 // satisfactorily aligned for.
541 for (; li != le && endAlign < li->Alignment; ++li)
542 ;
543
544 // If we found something that's naturally aligned for the end of
545 // the header, keep adding things...
546 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000547 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000548 for (; li != le; ++li) {
549 assert(endAlign >= li->Alignment);
550
John McCall7f416cc2015-09-08 08:05:57 +0000551 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000552 elementTypes.push_back(li->Type);
553 blockSize += li->Size;
554 endAlign = getLowBit(blockSize);
555
556 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000557 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000558 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000559 }
John McCall351762c2011-02-07 10:33:21 +0000560 }
John McCall351762c2011-02-07 10:33:21 +0000561 // Don't re-append everything we just appended.
562 layout.erase(first, li);
563 }
564 }
565
John McCallac0350a2012-04-26 21:14:42 +0000566 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000567
John McCall351762c2011-02-07 10:33:21 +0000568 // At this point, we just have to add padding if the end align still
569 // isn't aligned right.
570 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000571 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000572 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000573
John McCall7f416cc2015-09-08 08:05:57 +0000574 // If we haven't yet added any fields, remember that there was an
575 // initial gap; this need to go into the block layout bit map.
576 if (blockSize == info.BlockHeaderForcedGapOffset) {
577 info.BlockHeaderForcedGapSize = padding;
578 }
579
John McCalle3dc1702011-02-15 09:22:45 +0000580 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
581 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000582 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000583 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000584 }
585
John McCall1db0a2f2012-05-01 20:28:00 +0000586 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000587 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000588 // Slam everything else on now. This works because they have
589 // strictly decreasing alignment and we expect that size is always a
590 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000592 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000593 if (endAlign < li->Alignment) {
594 // size may not be multiple of alignment. This can only happen with
595 // an over-aligned variable. We will be adding a padding field to
596 // make the size be multiple of alignment.
597 CharUnits padding = li->Alignment - endAlign;
598 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
599 padding.getQuantity()));
600 blockSize += padding;
601 endAlign = getLowBit(blockSize);
602 }
John McCall351762c2011-02-07 10:33:21 +0000603 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000604 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000605 elementTypes.push_back(li->Type);
606 blockSize += li->Size;
607 endAlign = getLowBit(blockSize);
608 }
609
610 info.StructureType =
611 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
612}
613
John McCall08ef4662011-11-10 08:15:53 +0000614/// Enter the scope of a block. This should be run at the entrance to
615/// a full-expression so that the block's cleanups are pushed at the
616/// right place in the stack.
617static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000618 assert(CGF.HaveInsertPoint());
619
John McCall08ef4662011-11-10 08:15:53 +0000620 // Allocate the block info and place it at the head of the list.
621 CGBlockInfo &blockInfo =
622 *new CGBlockInfo(block, CGF.CurFn->getName());
623 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
624 CGF.FirstBlockInfo = &blockInfo;
625
626 // Compute information about the layout, etc., of this block,
627 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000628 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000629
630 // Nothing else to do if it can be global.
631 if (blockInfo.CanBeGlobal) return;
632
633 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000634 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
635 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000636
637 // If there are cleanups to emit, enter them (but inactive).
638 if (!blockInfo.NeedsCopyDispose) return;
639
640 // Walk through the captures (in order) and find the ones not
641 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000642 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000643 // Ignore __block captures; there's nothing special in the
644 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000645 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000646
647 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000648 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000649 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
650 if (capture.isConstant()) continue;
651
652 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000653 QualType VT = getCaptureFieldType(CGF, CI);
654 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000655 if (dtorKind == QualType::DK_none) continue;
656
657 CodeGenFunction::Destroyer *destroyer;
658
659 // Block captures count as local values and have imprecise semantics.
660 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000661 //
662 // For const-qualified captures, emit clang.arc.use to ensure the captured
663 // object doesn't get released while we are still depending on its validity
664 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000665 if (VT.isConstQualified() &&
666 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
667 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
668 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
669 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000670 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000671 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000672 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000673 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000674 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000675 }
676
677 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000678 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
679 capture.getIndex(),
680 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000681
John McCallf4beacd2011-11-10 10:43:54 +0000682 // We can use that GEP as the dominating IP.
683 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000684 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000685
John McCall08ef4662011-11-10 08:15:53 +0000686 CleanupKind cleanupKind = InactiveNormalCleanup;
687 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
688 if (useArrayEHCleanup)
689 cleanupKind = InactiveNormalAndEHCleanup;
690
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000691 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000692 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000693
694 // Remember where that cleanup was.
695 capture.setCleanup(CGF.EHStack.stable_begin());
696 }
697}
698
699/// Enter a full-expression with a non-trivial number of objects to
700/// clean up. This is in this file because, at the moment, the only
701/// kind of cleanup object is a BlockDecl*.
702void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
703 assert(E->getNumObjects() != 0);
George Burgess IV8b93a592018-03-02 20:10:38 +0000704 for (const ExprWithCleanups::CleanupObject &C : E->getObjects())
705 enterBlockScope(*this, C);
John McCall08ef4662011-11-10 08:15:53 +0000706}
707
708/// Find the layout for the given block in a linked list and remove it.
709static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
710 const BlockDecl *block) {
711 while (true) {
712 assert(head && *head);
713 CGBlockInfo *cur = *head;
714
715 // If this is the block we're looking for, splice it out of the list.
716 if (cur->getBlockDecl() == block) {
717 *head = cur->NextBlockInfo;
718 return cur;
719 }
720
721 head = &cur->NextBlockInfo;
722 }
723}
724
725/// Destroy a chain of block layouts.
726void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
727 assert(head && "destroying an empty chain");
728 do {
729 CGBlockInfo *cur = head;
730 head = cur->NextBlockInfo;
731 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000732 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000733}
734
John McCall351762c2011-02-07 10:33:21 +0000735/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000736llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000737 // If the block has no captures, we won't have a pre-computed
738 // layout for it.
739 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000740 // The block literal is emitted as a global variable, and the block invoke
741 // function has to be extracted from its initializer.
742 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
George Burgess IVe3763372016-12-22 02:50:20 +0000743 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000744 }
John McCall08ef4662011-11-10 08:15:53 +0000745 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000746 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000747 blockInfo.BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000748 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000749 }
John McCall351762c2011-02-07 10:33:21 +0000750
John McCall08ef4662011-11-10 08:15:53 +0000751 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000752 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000753 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
754 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000755
John McCall08ef4662011-11-10 08:15:53 +0000756 blockInfo->BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000757 return EmitBlockLiteral(*blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000758}
759
Yaxun Liufa13d012018-02-15 16:39:19 +0000760llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000761 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
John McCall08ef4662011-11-10 08:15:53 +0000762 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000763 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000764 CodeGenFunction BlockCGF{CGM, true};
765 BlockCGF.SanOpts = SanOpts;
766 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000767 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
John McCall351762c2011-02-07 10:33:21 +0000768
769 // If there is nothing to capture, we can emit this as a global block.
770 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000771 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000772
773 // Otherwise, we have to emit this as a local block.
774
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address blockAddr = blockInfo.LocalAddress;
776 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000777
Yaxun Liu10712d92017-10-04 20:32:17 +0000778 llvm::Constant *isa;
779 llvm::Constant *descriptor;
780 BlockFlags flags;
781 if (!IsOpenCL) {
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000782 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
783 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
784 // block just returns the original block and releasing it is a no-op.
785 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
786 ? CGM.getNSConcreteGlobalBlock()
787 : CGM.getNSConcreteStackBlock();
788 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
Yaxun Liu10712d92017-10-04 20:32:17 +0000789
790 // Build the block descriptor.
791 descriptor = buildBlockDescriptor(CGM, blockInfo);
792
793 // Compute the initial on-stack block flags.
794 flags = BLOCK_HAS_SIGNATURE;
795 if (blockInfo.HasCapturedVariableLayout)
796 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000797 if (blockInfo.needsCopyDisposeHelpers())
Yaxun Liu10712d92017-10-04 20:32:17 +0000798 flags |= BLOCK_HAS_COPY_DISPOSE;
799 if (blockInfo.HasCXXObject)
800 flags |= BLOCK_HAS_CXX_OBJ;
801 if (blockInfo.UsesStret)
802 flags |= BLOCK_USE_STRET;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000803 if (blockInfo.getBlockDecl()->doesNotEscape())
804 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
Yaxun Liu10712d92017-10-04 20:32:17 +0000805 }
John McCall351762c2011-02-07 10:33:21 +0000806
John McCall7f416cc2015-09-08 08:05:57 +0000807 auto projectField =
808 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
809 return Builder.CreateStructGEP(blockAddr, index, offset, name);
810 };
811 auto storeField =
812 [&](llvm::Value *value, unsigned index, CharUnits offset,
813 const Twine &name) {
814 Builder.CreateStore(value, projectField(index, offset, name));
815 };
816
817 // Initialize the block header.
818 {
819 // We assume all the header fields are densely packed.
820 unsigned index = 0;
821 CharUnits offset;
822 auto addHeaderField =
823 [&](llvm::Value *value, CharUnits size, const Twine &name) {
824 storeField(value, index, offset, name);
825 offset += size;
826 index++;
827 };
828
Yaxun Liu10712d92017-10-04 20:32:17 +0000829 if (!IsOpenCL) {
830 addHeaderField(isa, getPointerSize(), "block.isa");
831 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
832 getIntSize(), "block.flags");
833 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
834 "block.reserved");
835 } else {
836 addHeaderField(
837 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
838 getIntSize(), "block.size");
839 addHeaderField(
840 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
841 getIntSize(), "block.align");
842 }
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000843 if (!IsOpenCL) {
844 addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
845 getPointerSize(), "block.invoke");
Yaxun Liu10712d92017-10-04 20:32:17 +0000846 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000847 } else if (auto *Helper =
848 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000849 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
850 addHeaderField(
851 I.first,
852 CharUnits::fromQuantity(
853 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
854 I.second);
855 }
856 }
John McCall7f416cc2015-09-08 08:05:57 +0000857 }
John McCall351762c2011-02-07 10:33:21 +0000858
859 // Finally, capture all the values into the block.
860 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
861
862 // First, 'this'.
863 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000864 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
865 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000866 Builder.CreateStore(LoadCXXThis(), addr);
867 }
868
869 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000870 for (const auto &CI : blockDecl->captures()) {
871 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000872 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
873
874 // Ignore constant captures.
875 if (capture.isConstant()) continue;
876
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000877 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000878
879 // This will be a [[type]]*, except that a byref entry will just be
880 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000881 Address blockField =
882 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000883
884 // Compute the address of the thing we're going to move into the
885 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000886 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000887
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000888 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000889 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000890 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000891 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000892 } else if (CI.isByRef()) {
893 if (BlockInfo && CI.isNested()) {
894 // We need to use the capture from the enclosing block.
895 const CGBlockInfo::Capture &enclosingCapture =
896 BlockInfo->getCapture(variable);
897
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000898 // This is a [[type]]*, except that a byref entry will just be an i8**.
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000899 src = Builder.CreateStructGEP(LoadBlockStruct(),
900 enclosingCapture.getIndex(),
901 enclosingCapture.getOffset(),
902 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000903 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000904 auto I = LocalDeclMap.find(variable);
905 assert(I != LocalDeclMap.end());
906 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000907 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000908 } else {
909 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
910 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
911 type.getNonReferenceType(), VK_LValue,
912 SourceLocation());
913 src = EmitDeclRefLValue(&declRef).getAddress();
914 };
John McCall351762c2011-02-07 10:33:21 +0000915
916 // For byrefs, we just write the pointer to the byref struct into
917 // the block field. There's no need to chase the forwarding
918 // pointer at this point, since we're building something that will
919 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000920 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000921 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000922 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000923 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000924 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000925 else
John McCall7f416cc2015-09-08 08:05:57 +0000926 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000927
John McCalle3dc1702011-02-15 09:22:45 +0000928 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000929 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000930
931 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000932 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000933 if (blockDecl->isConversionFromLambda()) {
934 // If we have a lambda conversion, emit the expression
935 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000936 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000937 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000938 AggValueSlot::IsDestructed,
939 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000940 AggValueSlot::IsNotAliased,
941 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000942 EmitAggExpr(copyExpr, Slot);
943 } else {
944 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
945 }
John McCall351762c2011-02-07 10:33:21 +0000946
947 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000948 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000949 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000950
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000951 // If type is const-qualified, copy the value into the block field.
952 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000953 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
954 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000955 llvm::Value *value = Builder.CreateLoad(src, "captured");
956 Builder.CreateStore(value, blockField);
957
John McCall4d14a902013-04-08 23:27:49 +0000958 // If this is an ARC __strong block-pointer variable, don't do a
959 // block copy.
960 //
961 // TODO: this can be generalized into the normal initialization logic:
962 // we should never need to do a block-copy when initializing a local
963 // variable, because the local variable's lifetime should be strictly
964 // contained within the stack block's.
965 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
966 type->isBlockPointerType()) {
967 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000968 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000969 value = EmitARCRetainNonBlock(value);
970
971 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000972 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000973
974 // Otherwise, fake up a POD copy into the block field.
975 } else {
John McCall31168b02011-06-15 23:02:42 +0000976 // Fake up a new variable so that EmitScalarInit doesn't think
977 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000978 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
979 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000980
John McCall93be3f72011-02-07 18:37:40 +0000981 // We use one of these or the other depending on whether the
982 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000983 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
984 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
985 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000986
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000987 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000988 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000989 // FIXME: Pass a specific location for the expr init so that the store is
990 // attributed to a reasonable location - otherwise it may be attributed to
991 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +0000992 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000993 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000994 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000995 }
996
John McCall08ef4662011-11-10 08:15:53 +0000997 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000998 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000999 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1000 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +00001001 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +00001002 }
John McCall351762c2011-02-07 10:33:21 +00001003 }
1004
1005 // Cast to the converted block-pointer type, which happens (somewhat
1006 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001007 llvm::Value *result = Builder.CreatePointerCast(
1008 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001009
Yaxun Liufa13d012018-02-15 16:39:19 +00001010 if (IsOpenCL) {
1011 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1012 result);
1013 }
1014
John McCall351762c2011-02-07 10:33:21 +00001015 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001016}
1017
1018
Chris Lattnera5f58b02011-07-09 17:41:47 +00001019llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001020 if (BlockDescriptorType)
1021 return BlockDescriptorType;
1022
Chris Lattnera5f58b02011-07-09 17:41:47 +00001023 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001024 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001025
Mike Stump650c9322009-02-13 15:16:56 +00001026 // struct __block_descriptor {
1027 // unsigned long reserved;
1028 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001029 //
1030 // // later, the following will be added
1031 //
1032 // struct {
1033 // void (*copyHelper)();
1034 // void (*copyHelper)();
1035 // } helpers; // !!! optional
1036 //
1037 // const char *signature; // the block signature
1038 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001039 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001040 BlockDescriptorType = llvm::StructType::create(
1041 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001042
John McCall351762c2011-02-07 10:33:21 +00001043 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001044 unsigned AddrSpace = 0;
1045 if (getLangOpts().OpenCL)
1046 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1047 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001048 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001049}
1050
Chris Lattnera5f58b02011-07-09 17:41:47 +00001051llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001052 assert(!getLangOpts().OpenCL && "OpenCL does not need this");
1053
Mike Stump005c9a62009-02-13 15:25:34 +00001054 if (GenericBlockLiteralType)
1055 return GenericBlockLiteralType;
1056
Chris Lattnera5f58b02011-07-09 17:41:47 +00001057 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001058
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001059 // struct __block_literal_generic {
1060 // void *__isa;
1061 // int __flags;
1062 // int __reserved;
1063 // void (*__invoke)(void *);
1064 // struct __block_descriptor *__descriptor;
1065 // };
1066 GenericBlockLiteralType =
1067 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1068 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001069
Mike Stump005c9a62009-02-13 15:25:34 +00001070 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001071}
1072
Yaxun Liu10712d92017-10-04 20:32:17 +00001073RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001074 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001075 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001076 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001077
John McCallb92ab1a2016-10-26 23:46:34 +00001078 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001079 llvm::Value *FuncPtr;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001080
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001081 if (!CGM.getLangOpts().OpenCL) {
1082 // Get a pointer to the generic block literal.
1083 llvm::Type *BlockLiteralTy =
1084 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), 0);
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001085
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001086 // Bitcast the callee to a block literal.
1087 BlockPtr =
1088 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001089
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001090 // Get the function pointer from the literal.
1091 FuncPtr =
1092 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
1093 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001094
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001095 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001096 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001097
1098 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1099 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1100 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001101 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001102 VoidPtrQualTy =
1103 getContext().getPointerType(getContext().getAddrSpaceQualType(
1104 getContext().VoidTy, LangAS::opencl_generic));
1105 }
1106
1107 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1108 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001109
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001110 QualType FnType = BPT->getPointeeType();
1111
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001112 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001113 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001114
Anders Carlsson5f50c652009-04-07 22:10:22 +00001115 // Load the function.
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001116 llvm::Value *Func;
1117 if (CGM.getLangOpts().OpenCL)
1118 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1119 else
1120 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001121
John McCall85915252011-03-09 08:39:33 +00001122 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001123 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001124 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Anders Carlsson5f50c652009-04-07 22:10:22 +00001126 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001127 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattner2192fe52011-07-18 04:24:23 +00001129 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001130 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001131
John McCallb92ab1a2016-10-26 23:46:34 +00001132 // Prepare the callee.
1133 CGCallee Callee(CGCalleeInfo(), Func);
1134
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001135 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001136 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001137}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001138
John McCall7f416cc2015-09-08 08:05:57 +00001139Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1140 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001141 assert(BlockInfo && "evaluating block ref without block information?");
1142 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001143
John McCall351762c2011-02-07 10:33:21 +00001144 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001145 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001146
John McCall7f416cc2015-09-08 08:05:57 +00001147 Address addr =
1148 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1149 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001150
John McCall351762c2011-02-07 10:33:21 +00001151 if (isByRef) {
1152 // addr should be a void** right now. Load, then cast the result
1153 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001154
John McCall7f416cc2015-09-08 08:05:57 +00001155 auto &byrefInfo = getBlockByrefInfo(variable);
1156 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001157
John McCall7f416cc2015-09-08 08:05:57 +00001158 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1159 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001160
John McCall7f416cc2015-09-08 08:05:57 +00001161 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1162 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001163 }
1164
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001165 if (capture.fieldType()->isReferenceType())
1166 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001167
John McCall351762c2011-02-07 10:33:21 +00001168 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001169}
1170
George Burgess IVe3763372016-12-22 02:50:20 +00001171void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1172 llvm::Constant *Addr) {
1173 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1174 (void)Ok;
1175 assert(Ok && "Trying to replace an already-existing global block!");
1176}
1177
Mike Stump2d5a2872009-02-14 22:16:35 +00001178llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001179CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1180 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001181 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1182 return Block;
1183
George Burgess IV70d15b32016-11-03 02:21:43 +00001184 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1185 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001186
John McCall351762c2011-02-07 10:33:21 +00001187 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001188 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001189
John McCall351762c2011-02-07 10:33:21 +00001190 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001191 {
John McCall7f416cc2015-09-08 08:05:57 +00001192 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001193 CodeGenFunction(*this).GenerateBlockFunction(
1194 GlobalDecl(), blockInfo, LocalDeclMap,
1195 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001196 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001197
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001198 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001199}
1200
John McCall351762c2011-02-07 10:33:21 +00001201static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1202 const CGBlockInfo &blockInfo,
1203 llvm::Constant *blockFn) {
1204 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001205 // Callers should detect this case on their own: calling this function
1206 // generally requires computing layout information, which is a waste of time
1207 // if we've already emitted this block.
1208 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1209 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001210
1211 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001212 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001213 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001214
Yaxun Liu10712d92017-10-04 20:32:17 +00001215 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1216 if (!IsOpenCL) {
1217 // isa
1218 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001219
Yaxun Liu10712d92017-10-04 20:32:17 +00001220 // __flags
1221 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1222 if (blockInfo.UsesStret)
1223 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001224
Yaxun Liu10712d92017-10-04 20:32:17 +00001225 fields.addInt(CGM.IntTy, flags.getBitMask());
1226
1227 // Reserved
1228 fields.addInt(CGM.IntTy, 0);
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001229
1230 // Function
1231 fields.add(blockFn);
Yaxun Liu10712d92017-10-04 20:32:17 +00001232 } else {
1233 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1234 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1235 }
John McCall351762c2011-02-07 10:33:21 +00001236
Yaxun Liu10712d92017-10-04 20:32:17 +00001237 if (!IsOpenCL) {
1238 // Descriptor
1239 fields.add(buildBlockDescriptor(CGM, blockInfo));
1240 } else if (auto *Helper =
1241 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1242 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1243 fields.add(I);
1244 }
1245 }
John McCall351762c2011-02-07 10:33:21 +00001246
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001247 unsigned AddrSpace = 0;
1248 if (CGM.getContext().getLangOpts().OpenCL)
1249 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1250
1251 llvm::Constant *literal = fields.finishAndCreateGlobal(
1252 "__block_literal_global", blockInfo.BlockAlign,
1253 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001254
1255 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001256 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001257 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001258 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001259 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001260 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001261 if (CGM.getContext().getLangOpts().OpenCL)
1262 CGM.getOpenCLRuntime().recordBlockInfo(
1263 blockInfo.BlockExpression,
1264 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001265 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001266}
1267
John McCall7f416cc2015-09-08 08:05:57 +00001268void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1269 unsigned argNum,
1270 llvm::Value *arg) {
1271 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1272
Adrian Prantl356347b2017-10-26 20:08:52 +00001273 // Allocate a stack slot like for any local variable to guarantee optimal
1274 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1275 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1276 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001277 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001278 if (CGM.getCodeGenOpts().getDebugInfo() >=
1279 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001280 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001281 DI->EmitDeclareOfBlockLiteralArgVariable(
1282 *BlockInfo, D->getName(), argNum,
1283 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001284 }
1285 }
1286
1287 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1288 ApplyDebugLocation Scope(*this, StartLoc);
1289
1290 // Instead of messing around with LocalDeclMap, just set the value
1291 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001292 BlockPointer = Builder.CreatePointerCast(
1293 arg,
1294 BlockInfo->StructureType->getPointerTo(
1295 getContext().getLangOpts().OpenCL
1296 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1297 : 0),
1298 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001299}
1300
1301Address CodeGenFunction::LoadBlockStruct() {
1302 assert(BlockInfo && "not in a block invocation function!");
1303 assert(BlockPointer && "no block pointer set!");
1304 return Address(BlockPointer, BlockInfo->BlockAlign);
1305}
1306
Mike Stump4446dcf2009-03-05 08:32:30 +00001307llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001308CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1309 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001310 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001311 bool IsLambdaConversionToBlock,
1312 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001313 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001314
Fariborz Jahanian63628032012-06-26 16:06:38 +00001315 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001316
1317 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001318
John McCall351762c2011-02-07 10:33:21 +00001319 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Mike Stump5469f292009-03-13 23:34:28 +00001321 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001322 // to be local to this function as well, in case they're directly
1323 // referenced in a block.
1324 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001325 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001326 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001327 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001328 }
1329
John McCall351762c2011-02-07 10:33:21 +00001330 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001331
John McCall351762c2011-02-07 10:33:21 +00001332 // Build the argument list.
1333 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001334
John McCall351762c2011-02-07 10:33:21 +00001335 // The first argument is the block pointer. Just take it as a void*
1336 // and cast it later.
1337 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001338
1339 // For OpenCL passed block pointer can be private AS local variable or
1340 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001341 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001342 // generic AS in one implementation.
1343 if (getLangOpts().OpenCL)
1344 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1345 getContext().VoidTy, LangAS::opencl_generic));
1346
Mike Stump7fe9cc12009-10-21 03:49:08 +00001347 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001348
Alexey Bataev56223232017-06-09 13:40:18 +00001349 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1350 SourceLocation(), II, selfTy,
1351 ImplicitParamDecl::ObjCSelf);
1352 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001353
John McCall351762c2011-02-07 10:33:21 +00001354 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001355 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001356
John McCall351762c2011-02-07 10:33:21 +00001357 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001358 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001359 const CGFunctionInfo &fnInfo =
1360 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001361 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001362 blockInfo.UsesStret = true;
1363
John McCalla729c622012-02-17 03:33:10 +00001364 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001365
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001366 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001367 llvm::Function *fn = llvm::Function::Create(
1368 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001369 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001370
Yaxun Liu10712d92017-10-04 20:32:17 +00001371 if (BuildGlobalBlock) {
1372 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1373 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1374 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001375 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001376 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1377 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001378
John McCall351762c2011-02-07 10:33:21 +00001379 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001380 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001381 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001382 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001383
John McCall147d0212011-02-22 22:38:33 +00001384 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001385
Adrian Prantl0f6df002013-03-29 19:20:35 +00001386 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1387 // won't delete the dbg.declare intrinsics for captured variables.
1388 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1389 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1390 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001391 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1392 getPointerAlign(),
1393 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001394 // Set the DebugLocation to empty, so the store is recognized as a
1395 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001396 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001397 Builder.CreateStore(BlockPointer, Alloca);
1398 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001399 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001400
John McCall87fe5d52010-05-20 01:18:31 +00001401 // If we have a C++ 'this' reference, go ahead and force it into
1402 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001403 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001404 Address addr =
1405 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1406 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001407 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001408 }
1409
John McCall351762c2011-02-07 10:33:21 +00001410 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001411 for (const auto &CI : blockDecl->captures()) {
1412 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001413 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1414 if (!capture.isConstant()) continue;
1415
John McCall7f416cc2015-09-08 08:05:57 +00001416 CharUnits align = getContext().getDeclAlign(variable);
1417 Address alloca =
1418 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001419
John McCall7f416cc2015-09-08 08:05:57 +00001420 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001421
John McCall7f416cc2015-09-08 08:05:57 +00001422 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001423 }
1424
John McCall113bee02012-03-10 09:33:50 +00001425 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001426 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1427 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1428 --entry_ptr;
1429
Eli Friedman2495ab02012-02-25 02:48:22 +00001430 if (IsLambdaConversionToBlock)
1431 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001432 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001433 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001434 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001435 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001436 }
Mike Stump017460a2009-10-01 22:29:41 +00001437
Mike Stump7d699112009-10-01 00:27:30 +00001438 // Remember where we were...
1439 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001440
Mike Stump7d699112009-10-01 00:27:30 +00001441 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001442 ++entry_ptr;
1443 Builder.SetInsertPoint(entry, entry_ptr);
1444
John McCall113bee02012-03-10 09:33:50 +00001445 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001446 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001447 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001448 for (const auto &CI : blockDecl->captures()) {
1449 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001450 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001451
Benjamin Kramer8c305922016-02-02 11:06:51 +00001452 if (CGM.getCodeGenOpts().getDebugInfo() >=
1453 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001454 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1455 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001456 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001457 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1458 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001459 continue;
1460 }
John McCall351762c2011-02-07 10:33:21 +00001461
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001462 DI->EmitDeclareOfBlockDeclRefVariable(
1463 variable, BlockPointerDbgLoc, Builder, blockInfo,
1464 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001465 }
Mike Stump2e722b92009-09-30 02:43:10 +00001466 }
Manman Renab08a9a2013-01-04 18:51:35 +00001467 // Recover location if it was changed in the above loop.
1468 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001469 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001470 }
John McCall351762c2011-02-07 10:33:21 +00001471
Mike Stump7d699112009-10-01 00:27:30 +00001472 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001473 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001474 Builder.ClearInsertionPoint();
1475 else
1476 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001477
John McCall351762c2011-02-07 10:33:21 +00001478 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001479
John McCall351762c2011-02-07 10:33:21 +00001480 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001481}
Mike Stump1db7d042009-02-28 09:07:16 +00001482
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001483namespace {
1484
1485/// Represents a type of copy/destroy operation that should be performed for an
1486/// entity that's captured by a block.
1487enum class BlockCaptureEntityKind {
1488 CXXRecord, // Copy or destroy
1489 ARCWeak,
1490 ARCStrong,
Akira Hatanaka7275da02018-02-28 07:15:55 +00001491 NonTrivialCStruct,
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001492 BlockObject, // Assign or release
1493 None
1494};
1495
1496/// Represents a captured entity that requires extra operations in order for
1497/// this entity to be copied or destroyed correctly.
1498struct BlockCaptureManagedEntity {
1499 BlockCaptureEntityKind Kind;
1500 BlockFieldFlags Flags;
1501 const BlockDecl::Capture &CI;
1502 const CGBlockInfo::Capture &Capture;
1503
1504 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1505 const BlockDecl::Capture &CI,
1506 const CGBlockInfo::Capture &Capture)
1507 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1508};
1509
1510} // end anonymous namespace
1511
1512static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1513computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1514 const LangOptions &LangOpts) {
1515 if (CI.getCopyExpr()) {
1516 assert(!CI.isByRef());
1517 // don't bother computing flags
1518 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1519 }
1520 BlockFieldFlags Flags;
1521 if (CI.isByRef()) {
1522 Flags = BLOCK_FIELD_IS_BYREF;
1523 if (T.isObjCGCWeak())
1524 Flags |= BLOCK_FIELD_IS_WEAK;
1525 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1526 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001527
1528 Flags = BLOCK_FIELD_IS_OBJECT;
1529 bool isBlockPointer = T->isBlockPointerType();
1530 if (isBlockPointer)
1531 Flags = BLOCK_FIELD_IS_BLOCK;
1532
Akira Hatanaka7275da02018-02-28 07:15:55 +00001533 switch (T.isNonTrivialToPrimitiveCopy()) {
1534 case QualType::PCK_Struct:
1535 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1536 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001537 case QualType::PCK_ARCWeak:
1538 // We need to register __weak direct captures with the runtime.
1539 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001540 case QualType::PCK_ARCStrong:
1541 // We need to retain the copied value for __strong direct captures.
1542 // If it's a block pointer, we have to copy the block and assign that to
1543 // the destination pointer, so we might as well use _Block_object_assign.
1544 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001545 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1546 : BlockCaptureEntityKind::BlockObject,
1547 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001548 case QualType::PCK_Trivial:
1549 case QualType::PCK_VolatileTrivial: {
1550 if (!T->isObjCRetainableType())
1551 // For all other types, the memcpy is fine.
1552 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1553
1554 // Special rules for ARC captures:
1555 Qualifiers QS = T.getQualifiers();
1556
Akira Hatanaka7275da02018-02-28 07:15:55 +00001557 // Non-ARC captures of retainable pointers are strong and
1558 // therefore require a call to _Block_object_assign.
1559 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1560 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1561
1562 // Otherwise the memcpy is fine.
1563 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001564 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001565 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001566 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001567}
1568
1569/// Find the set of block captures that need to be explicitly copied or destroy.
1570static void findBlockCapturedManagedEntities(
1571 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1572 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1573 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1574 const BlockDecl::Capture &, QualType, const LangOptions &)>
1575 Predicate) {
1576 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1577 const VarDecl *Variable = CI.getVariable();
1578 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1579 if (Capture.isConstant())
1580 continue;
1581
1582 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1583 if (Info.first != BlockCaptureEntityKind::None)
1584 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1585 }
1586}
1587
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001588namespace {
1589/// Release a __block variable.
1590struct CallBlockRelease final : EHScopeStack::Cleanup {
1591 Address Addr;
1592 BlockFieldFlags FieldFlags;
1593 bool LoadBlockVarAddr;
1594
1595 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue)
1596 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue) {}
1597
1598 void Emit(CodeGenFunction &CGF, Flags flags) override {
1599 llvm::Value *BlockVarAddr;
1600 if (LoadBlockVarAddr) {
1601 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1602 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1603 } else {
1604 BlockVarAddr = Addr.getPointer();
1605 }
1606
1607 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags);
1608 }
1609};
1610} // end anonymous namespace
1611
1612static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1613 Address Field, QualType CaptureType,
1614 BlockFieldFlags Flags, bool EHOnly,
1615 CodeGenFunction &CGF) {
1616 switch (CaptureKind) {
1617 case BlockCaptureEntityKind::CXXRecord:
1618 case BlockCaptureEntityKind::ARCWeak:
1619 case BlockCaptureEntityKind::NonTrivialCStruct:
1620 case BlockCaptureEntityKind::ARCStrong: {
1621 if (CaptureType.isDestructedType() &&
1622 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1623 CodeGenFunction::Destroyer *Destroyer =
1624 CaptureKind == BlockCaptureEntityKind::ARCStrong
1625 ? CodeGenFunction::destroyARCStrongImprecise
1626 : CGF.getDestroyer(CaptureType.isDestructedType());
1627 CleanupKind Kind =
1628 EHOnly ? EHCleanup
1629 : CGF.getCleanupKind(CaptureType.isDestructedType());
1630 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1631 }
1632 break;
1633 }
1634 case BlockCaptureEntityKind::BlockObject: {
1635 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1636 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1637 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true);
1638 }
1639 break;
1640 }
1641 case BlockCaptureEntityKind::None:
1642 llvm_unreachable("unexpected BlockCaptureEntityKind");
1643 }
1644}
1645
John McCallf593b102013-01-22 03:56:22 +00001646/// Generate the copy-helper function for a block closure object:
1647/// static void block_copy_helper(block_t *dst, block_t *src);
1648/// The runtime will have previously initialized 'dst' by doing a
1649/// bit-copy of 'src'.
1650///
1651/// Note that this copies an entire block closure object to the heap;
1652/// it should not be confused with a 'byref copy helper', which moves
1653/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001654llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001655CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001656 ASTContext &C = getContext();
1657
1658 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001659 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1660 ImplicitParamDecl::Other);
1661 args.push_back(&DstDecl);
1662 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1663 ImplicitParamDecl::Other);
1664 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001665
John McCallc56a8b32016-03-11 04:30:31 +00001666 const CGFunctionInfo &FI =
1667 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001668
John McCall351762c2011-02-07 10:33:21 +00001669 // FIXME: it would be nice if these were mergeable with things with
1670 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001671 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001672
1673 llvm::Function *Fn =
1674 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001675 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001676
1677 IdentifierInfo *II
1678 = &CGM.getContext().Idents.get("__copy_helper_block_");
1679
John McCall351762c2011-02-07 10:33:21 +00001680 FunctionDecl *FD = FunctionDecl::Create(C,
1681 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001682 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001683 SourceLocation(), II, C.VoidTy,
1684 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001685 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001686 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001687
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001688 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001689
Adrian Prantl22e66b42014-04-11 01:13:04 +00001690 StartFunction(FD, C.VoidTy, Fn, FI, args);
Vedant Kumar9c6b6822017-10-26 21:27:24 +00001691 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
Chris Lattner2192fe52011-07-18 04:24:23 +00001692 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001693
Alexey Bataev56223232017-06-09 13:40:18 +00001694 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001695 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001696 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001697
Alexey Bataev56223232017-06-09 13:40:18 +00001698 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001699 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001700 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001701
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001702 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1703 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1704 computeCopyInfoForBlockCapture);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001705
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001706 for (const auto &CopiedCapture : CopiedCaptures) {
1707 const BlockDecl::Capture &CI = CopiedCapture.CI;
1708 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001709 QualType captureType = CI.getVariable()->getType();
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001710 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001711
1712 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001713 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1714 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001715
1716 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001717 if (CI.getCopyExpr()) {
1718 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1719 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1720 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001721 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001722 // If this is a C struct that requires non-trivial copy construction, emit a
1723 // call to its copy constructor.
1724 } else if (CopiedCapture.Kind ==
1725 BlockCaptureEntityKind::NonTrivialCStruct) {
1726 QualType varType = CI.getVariable()->getType();
1727 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1728 MakeAddrLValue(srcField, varType));
John McCall351762c2011-02-07 10:33:21 +00001729 } else {
1730 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001731 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001732 // At -O0, store null into the destination field (so that the
1733 // storeStrong doesn't over-release) and then call storeStrong.
1734 // This is a workaround to not having an initStrong call.
1735 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001736 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001737 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1738 Builder.CreateStore(null, dstField);
1739 EmitARCStoreStrongCall(dstField, srcValue, true);
1740
1741 // With optimization enabled, take advantage of the fact that
1742 // the blocks runtime guarantees a memcpy of the block data, and
1743 // just emit a retain of the src field.
1744 } else {
1745 EmitARCRetainNonBlock(srcValue);
1746
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001747 // Unless EH cleanup is required, we don't need this anymore, so kill
1748 // it. It's not quite worth the annoyance to avoid creating it in the
1749 // first place.
1750 if (!needsEHCleanup(captureType.isDestructedType()))
1751 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001752 }
1753 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001754 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001755 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001756 llvm::Value *dstAddr =
1757 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001758 llvm::Value *args[] = {
1759 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1760 };
1761
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001762 const VarDecl *variable = CI.getVariable();
John McCall882987f2013-02-28 19:01:20 +00001763 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001764 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001765 const Expr *copyExpr =
1766 CGM.getContext().getBlockVarCopyInits(variable);
1767 if (copyExpr) {
1768 copyCanThrow = true; // FIXME: reuse the noexcept logic
1769 }
1770 }
1771
1772 if (copyCanThrow) {
1773 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1774 } else {
1775 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1776 }
John McCalle68b8f42012-10-17 02:28:37 +00001777 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001778 }
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001779
1780 // Ensure that we destroy the copied object if an exception is thrown later
1781 // in the helper function.
1782 pushCaptureCleanup(CopiedCapture.Kind, dstField, captureType, flags, /*EHOnly*/ true,
1783 *this);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001784 }
1785
John McCallad7c5c12011-02-08 08:22:06 +00001786 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001787
John McCalle3dc1702011-02-15 09:22:45 +00001788 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001789}
1790
Akira Hatanaka7275da02018-02-28 07:15:55 +00001791static BlockFieldFlags
1792getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
1793 QualType T) {
1794 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
1795 if (T->isBlockPointerType())
1796 Flags = BLOCK_FIELD_IS_BLOCK;
1797 return Flags;
1798}
1799
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001800static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1801computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1802 const LangOptions &LangOpts) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001803 if (CI.isByRef()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00001804 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001805 if (T.isObjCGCWeak())
1806 Flags |= BLOCK_FIELD_IS_WEAK;
1807 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1808 }
1809
Akira Hatanaka7275da02018-02-28 07:15:55 +00001810 switch (T.isDestructedType()) {
1811 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001812 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00001813 case QualType::DK_objc_strong_lifetime:
1814 // Use objc_storeStrong for __strong direct captures; the
1815 // dynamic tools really like it when we do this.
1816 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
1817 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1818 case QualType::DK_objc_weak_lifetime:
1819 // Support __weak direct captures.
1820 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
1821 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1822 case QualType::DK_nontrivial_c_struct:
1823 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1824 BlockFieldFlags());
1825 case QualType::DK_none: {
1826 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1827 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
1828 !LangOpts.ObjCAutoRefCount)
1829 return std::make_pair(BlockCaptureEntityKind::BlockObject,
1830 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1831 // Otherwise, we have nothing to do.
1832 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001833 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001834 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001835 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001836}
1837
John McCallf593b102013-01-22 03:56:22 +00001838/// Generate the destroy-helper function for a block closure object:
1839/// static void block_destroy_helper(block_t *theBlock);
1840///
1841/// Note that this destroys a heap-allocated block closure object;
1842/// it should not be confused with a 'byref destroy helper', which
1843/// destroys the heap-allocated contents of an individual __block
1844/// variable.
John McCall351762c2011-02-07 10:33:21 +00001845llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001846CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001847 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001848
John McCall351762c2011-02-07 10:33:21 +00001849 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001850 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1851 ImplicitParamDecl::Other);
1852 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001853
John McCallc56a8b32016-03-11 04:30:31 +00001854 const CGFunctionInfo &FI =
1855 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001856
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001857 // FIXME: We'd like to put these into a mergable by content, with
1858 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001859 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001860
1861 llvm::Function *Fn =
1862 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001863 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001864
1865 IdentifierInfo *II
1866 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1867
John McCall351762c2011-02-07 10:33:21 +00001868 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001869 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001870 SourceLocation(), II, C.VoidTy,
1871 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001872 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001873
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001874 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001875
Adrian Prantl22e66b42014-04-11 01:13:04 +00001876 StartFunction(FD, C.VoidTy, Fn, FI, args);
Vedant Kumar9c6b6822017-10-26 21:27:24 +00001877 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
Mike Stump6f7d9f82009-03-07 02:53:18 +00001878
Chris Lattner2192fe52011-07-18 04:24:23 +00001879 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001880
Alexey Bataev56223232017-06-09 13:40:18 +00001881 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001882 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001883 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001884
John McCallad7c5c12011-02-08 08:22:06 +00001885 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001886
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001887 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1888 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1889 computeDestroyInfoForBlockCapture);
John McCall351762c2011-02-07 10:33:21 +00001890
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001891 for (const auto &DestroyedCapture : DestroyedCaptures) {
1892 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1893 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1894 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001895
John McCall7f416cc2015-09-08 08:05:57 +00001896 Address srcField =
1897 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001898
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001899 pushCaptureCleanup(DestroyedCapture.Kind, srcField,
1900 CI.getVariable()->getType(), flags, /*EHOnly*/ false, *this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001901 }
1902
John McCall351762c2011-02-07 10:33:21 +00001903 cleanups.ForceCleanup();
1904
John McCallad7c5c12011-02-08 08:22:06 +00001905 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001906
John McCalle3dc1702011-02-15 09:22:45 +00001907 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001908}
1909
John McCallf9b056b2011-03-31 08:03:29 +00001910namespace {
1911
1912/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001913class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001914 BlockFieldFlags Flags;
1915
1916public:
1917 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001918 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001919
John McCall7f416cc2015-09-08 08:05:57 +00001920 void emitCopy(CodeGenFunction &CGF, Address destField,
1921 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001922 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1923
1924 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1925 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1926
1927 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1928
1929 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1930 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001931
John McCall7f416cc2015-09-08 08:05:57 +00001932 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001933 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001934 }
1935
John McCall7f416cc2015-09-08 08:05:57 +00001936 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001937 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1938 llvm::Value *value = CGF.Builder.CreateLoad(field);
1939
1940 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1941 }
1942
Craig Topper4f12f102014-03-12 06:41:41 +00001943 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001944 id.AddInteger(Flags.getBitMask());
1945 }
1946};
1947
John McCall31168b02011-06-15 23:02:42 +00001948/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001949class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001950public:
John McCall7f416cc2015-09-08 08:05:57 +00001951 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001952
John McCall7f416cc2015-09-08 08:05:57 +00001953 void emitCopy(CodeGenFunction &CGF, Address destField,
1954 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001955 CGF.EmitARCMoveWeak(destField, srcField);
1956 }
1957
John McCall7f416cc2015-09-08 08:05:57 +00001958 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001959 CGF.EmitARCDestroyWeak(field);
1960 }
1961
Craig Topper4f12f102014-03-12 06:41:41 +00001962 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001963 // 0 is distinguishable from all pointers and byref flags
1964 id.AddInteger(0);
1965 }
1966};
1967
1968/// Emits the copy/dispose helpers for an ARC __block __strong variable
1969/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001970class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001971public:
John McCall7f416cc2015-09-08 08:05:57 +00001972 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001973
John McCall7f416cc2015-09-08 08:05:57 +00001974 void emitCopy(CodeGenFunction &CGF, Address destField,
1975 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001976 // Do a "move" by copying the value and then zeroing out the old
1977 // variable.
1978
John McCall7f416cc2015-09-08 08:05:57 +00001979 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001980
John McCall31168b02011-06-15 23:02:42 +00001981 llvm::Value *null =
1982 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001983
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001984 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001985 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001986 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1987 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1988 return;
1989 }
John McCall7f416cc2015-09-08 08:05:57 +00001990 CGF.Builder.CreateStore(value, destField);
1991 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001992 }
1993
John McCall7f416cc2015-09-08 08:05:57 +00001994 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001995 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001996 }
1997
Craig Topper4f12f102014-03-12 06:41:41 +00001998 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001999 // 1 is distinguishable from all pointers and byref flags
2000 id.AddInteger(1);
2001 }
2002};
2003
John McCall3a237aa2011-11-09 03:17:26 +00002004/// Emits the copy/dispose helpers for an ARC __block __strong
2005/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002006class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00002007public:
John McCall7f416cc2015-09-08 08:05:57 +00002008 ARCStrongBlockByrefHelpers(CharUnits alignment)
2009 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00002010
John McCall7f416cc2015-09-08 08:05:57 +00002011 void emitCopy(CodeGenFunction &CGF, Address destField,
2012 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00002013 // Do the copy with objc_retainBlock; that's all that
2014 // _Block_object_assign would do anyway, and we'd have to pass the
2015 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00002016 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00002017 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00002018 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00002019 }
2020
John McCall7f416cc2015-09-08 08:05:57 +00002021 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002022 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00002023 }
2024
Craig Topper4f12f102014-03-12 06:41:41 +00002025 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00002026 // 2 is distinguishable from all pointers and byref flags
2027 id.AddInteger(2);
2028 }
2029};
2030
John McCallf9b056b2011-03-31 08:03:29 +00002031/// Emits the copy/dispose helpers for a __block variable with a
2032/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002033class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002034 QualType VarType;
2035 const Expr *CopyExpr;
2036
2037public:
2038 CXXByrefHelpers(CharUnits alignment, QualType type,
2039 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002040 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002041
Craig Topper8a13c412014-05-21 05:09:00 +00002042 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002043 void emitCopy(CodeGenFunction &CGF, Address destField,
2044 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002045 if (!CopyExpr) return;
2046 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2047 }
2048
John McCall7f416cc2015-09-08 08:05:57 +00002049 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002050 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2051 CGF.PushDestructorCleanup(VarType, field);
2052 CGF.PopCleanupBlocks(cleanupDepth);
2053 }
2054
Craig Topper4f12f102014-03-12 06:41:41 +00002055 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002056 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2057 }
2058};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002059
2060/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2061/// C struct.
2062class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2063 QualType VarType;
2064
2065public:
2066 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2067 : BlockByrefHelpers(alignment), VarType(type) {}
2068
2069 void emitCopy(CodeGenFunction &CGF, Address destField,
2070 Address srcField) override {
2071 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2072 CGF.MakeAddrLValue(srcField, VarType));
2073 }
2074
2075 bool needsDispose() const override {
2076 return VarType.isDestructedType();
2077 }
2078
2079 void emitDispose(CodeGenFunction &CGF, Address field) override {
2080 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2081 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2082 CGF.PopCleanupBlocks(cleanupDepth);
2083 }
2084
2085 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2086 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2087 }
2088};
John McCallf9b056b2011-03-31 08:03:29 +00002089} // end anonymous namespace
2090
2091static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002092generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2093 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002094 ASTContext &Context = CGF.getContext();
2095
2096 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002097
John McCalla738c252011-03-09 04:27:21 +00002098 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002099 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2100 ImplicitParamDecl::Other);
2101 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002102
Alexey Bataev56223232017-06-09 13:40:18 +00002103 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2104 ImplicitParamDecl::Other);
2105 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCallc56a8b32016-03-11 04:30:31 +00002107 const CGFunctionInfo &FI =
2108 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002109
John McCall7f416cc2015-09-08 08:05:57 +00002110 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002111
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002112 // FIXME: We'd like to put these into a mergable by content, with
2113 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002114 llvm::Function *Fn =
2115 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002116 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002117
2118 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002119 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002120
John McCallf9b056b2011-03-31 08:03:29 +00002121 FunctionDecl *FD = FunctionDecl::Create(Context,
2122 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002123 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002124 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002125 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002126 false, false);
John McCall31168b02011-06-15 23:02:42 +00002127
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002128 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002129
Adrian Prantl22e66b42014-04-11 01:13:04 +00002130 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002131
John McCall7f416cc2015-09-08 08:05:57 +00002132 if (generator.needsCopy()) {
2133 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002134
John McCallf9b056b2011-03-31 08:03:29 +00002135 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002136 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002137 destField = Address(CGF.Builder.CreateLoad(destField),
2138 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002139 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002140 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2141 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002142
John McCallf9b056b2011-03-31 08:03:29 +00002143 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002144 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002145 srcField = Address(CGF.Builder.CreateLoad(srcField),
2146 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002147 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002148 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2149 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002150
John McCall7f416cc2015-09-08 08:05:57 +00002151 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00002152 }
2153
2154 CGF.FinishFunction();
2155
2156 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002157}
2158
John McCallf9b056b2011-03-31 08:03:29 +00002159/// Build the copy helper for a __block variable.
2160static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002161 const BlockByrefInfo &byrefInfo,
2162 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002163 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002164 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002165}
2166
2167/// Generate code for a __block variable's dispose helper.
2168static llvm::Constant *
2169generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002170 const BlockByrefInfo &byrefInfo,
2171 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002172 ASTContext &Context = CGF.getContext();
2173 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002174
John McCalla738c252011-03-09 04:27:21 +00002175 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002176 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2177 ImplicitParamDecl::Other);
2178 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002179
John McCallc56a8b32016-03-11 04:30:31 +00002180 const CGFunctionInfo &FI =
2181 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002182
John McCall7f416cc2015-09-08 08:05:57 +00002183 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002184
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002185 // FIXME: We'd like to put these into a mergable by content, with
2186 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002187 llvm::Function *Fn =
2188 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002189 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002190 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002191
2192 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002193 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002194
John McCallf9b056b2011-03-31 08:03:29 +00002195 FunctionDecl *FD = FunctionDecl::Create(Context,
2196 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002197 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002198 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002199 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002200 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002201
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002202 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002203
Adrian Prantl22e66b42014-04-11 01:13:04 +00002204 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002205
John McCall7f416cc2015-09-08 08:05:57 +00002206 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002207 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002208 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2209 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2210 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2211 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002212
John McCall7f416cc2015-09-08 08:05:57 +00002213 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002214 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002215
John McCallf9b056b2011-03-31 08:03:29 +00002216 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002217
John McCallf9b056b2011-03-31 08:03:29 +00002218 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002219}
2220
John McCallf9b056b2011-03-31 08:03:29 +00002221/// Build the dispose helper for a __block variable.
2222static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002223 const BlockByrefInfo &byrefInfo,
2224 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002225 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002226 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002227}
2228
John McCallf593b102013-01-22 03:56:22 +00002229/// Lazily build the copy and dispose helpers for a __block variable
2230/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002231template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002232static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2233 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002234 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002235 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002236
2237 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002238 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002239 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2240 if (node) return static_cast<T*>(node);
2241
John McCall7f416cc2015-09-08 08:05:57 +00002242 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2243 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002244
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002245 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002246 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2247 return copy;
2248}
2249
John McCallf593b102013-01-22 03:56:22 +00002250/// Build the copy and dispose helpers for the given __block variable
2251/// emission. Places the helpers in the global cache. Returns null
2252/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002253BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002254CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002255 const AutoVarEmission &emission) {
2256 const VarDecl &var = *emission.Variable;
2257 QualType type = var.getType();
2258
John McCall7f416cc2015-09-08 08:05:57 +00002259 auto &byrefInfo = getBlockByrefInfo(&var);
2260
2261 // The alignment we care about for the purposes of uniquing byref
2262 // helpers is the alignment of the actual byref value field.
2263 CharUnits valueAlignment =
2264 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002265
John McCallf9b056b2011-03-31 08:03:29 +00002266 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2267 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002268 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002269
David Blaikie92551612015-08-13 23:53:09 +00002270 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002271 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002272 }
2273
Akira Hatanaka7275da02018-02-28 07:15:55 +00002274 // If type is a non-trivial C struct type that is non-trivial to
2275 // destructly move or destroy, build the copy and dispose helpers.
2276 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2277 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2278 return ::buildByrefHelpers(
2279 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2280
John McCall31168b02011-06-15 23:02:42 +00002281 // Otherwise, if we don't have a retainable type, there's nothing to do.
2282 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002283 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002284
2285 Qualifiers qs = type.getQualifiers();
2286
2287 // If we have lifetime, that dominates.
2288 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002289 switch (lifetime) {
2290 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2291
2292 // These are just bits as far as the runtime is concerned.
2293 case Qualifiers::OCL_ExplicitNone:
2294 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002295 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002296
2297 // Tell the runtime that this is ARC __weak, called by the
2298 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002299 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002300 return ::buildByrefHelpers(CGM, byrefInfo,
2301 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002302
2303 // ARC __strong __block variables need to be retained.
2304 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002305 // Block pointers need to be copied, and there's no direct
2306 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002307 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002308 return ::buildByrefHelpers(CGM, byrefInfo,
2309 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002310
2311 // Otherwise, we transfer ownership of the retain from the stack
2312 // to the heap.
2313 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002314 return ::buildByrefHelpers(CGM, byrefInfo,
2315 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002316 }
2317 }
2318 llvm_unreachable("fell out of lifetime switch!");
2319 }
2320
John McCallf9b056b2011-03-31 08:03:29 +00002321 BlockFieldFlags flags;
2322 if (type->isBlockPointerType()) {
2323 flags |= BLOCK_FIELD_IS_BLOCK;
2324 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2325 type->isObjCObjectPointerType()) {
2326 flags |= BLOCK_FIELD_IS_OBJECT;
2327 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002328 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002329 }
2330
2331 if (type.isObjCGCWeak())
2332 flags |= BLOCK_FIELD_IS_WEAK;
2333
John McCall7f416cc2015-09-08 08:05:57 +00002334 return ::buildByrefHelpers(CGM, byrefInfo,
2335 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002336}
2337
John McCall7f416cc2015-09-08 08:05:57 +00002338Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2339 const VarDecl *var,
2340 bool followForward) {
2341 auto &info = getBlockByrefInfo(var);
2342 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002343}
2344
John McCall7f416cc2015-09-08 08:05:57 +00002345Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2346 const BlockByrefInfo &info,
2347 bool followForward,
2348 const llvm::Twine &name) {
2349 // Chase the forwarding address if requested.
2350 if (followForward) {
2351 Address forwardingAddr =
2352 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2353 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2354 }
2355
2356 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2357 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002358}
2359
John McCall7f416cc2015-09-08 08:05:57 +00002360/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002361/// into:
2362///
2363/// struct {
2364/// void *__isa;
2365/// void *__forwarding;
2366/// int32_t __flags;
2367/// int32_t __size;
2368/// void *__copy_helper; // only if needed
2369/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002370/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002371/// char padding[X]; // only if needed
2372/// T x;
2373/// } x
2374///
John McCall7f416cc2015-09-08 08:05:57 +00002375const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2376 auto it = BlockByrefInfos.find(D);
2377 if (it != BlockByrefInfos.end())
2378 return it->second;
John McCall73064872011-03-31 01:59:53 +00002379
John McCall7f416cc2015-09-08 08:05:57 +00002380 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002381 llvm::StructType::create(getLLVMContext(),
2382 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002383
John McCall7f416cc2015-09-08 08:05:57 +00002384 QualType Ty = D->getType();
2385
2386 CharUnits size;
2387 SmallVector<llvm::Type *, 8> types;
2388
John McCall73064872011-03-31 01:59:53 +00002389 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002390 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002391 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002392
2393 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002394 types.push_back(llvm::PointerType::getUnqual(byrefType));
2395 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002396
2397 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002398 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002399 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002400
2401 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002402 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002403 size += CharUnits::fromQuantity(4);
2404
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002405 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002406 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2407 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002408 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002409 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002410 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002411
2412 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002413 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002414 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002415 }
John McCall7f416cc2015-09-08 08:05:57 +00002416
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002417 bool HasByrefExtendedLayout = false;
2418 Qualifiers::ObjCLifetime Lifetime;
2419 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002420 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002421 /// void *__byref_variable_layout;
2422 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002423 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002424 }
2425
2426 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002427 llvm::Type *varTy = ConvertTypeForMem(Ty);
2428
2429 bool packed = false;
2430 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002431 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002432
2433 // We may have to insert padding.
2434 if (varOffset != size) {
2435 llvm::Type *paddingTy =
2436 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2437
2438 types.push_back(paddingTy);
2439 size = varOffset;
2440
2441 // Conversely, we might have to prevent LLVM from inserting padding.
2442 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2443 > varAlign.getQuantity()) {
2444 packed = true;
2445 }
2446 types.push_back(varTy);
2447
2448 byrefType->setBody(types, packed);
2449
2450 BlockByrefInfo info;
2451 info.Type = byrefType;
2452 info.FieldIndex = types.size() - 1;
2453 info.FieldOffset = varOffset;
2454 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2455
2456 auto pair = BlockByrefInfos.insert({D, info});
2457 assert(pair.second && "info was inserted recursively?");
2458 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002459}
2460
2461/// Initialize the structural components of a __block variable, i.e.
2462/// everything but the actual object.
2463void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002464 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002465 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002466
John McCallf9b056b2011-03-31 08:03:29 +00002467 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002468 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002469 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2470
2471 unsigned nextHeaderIndex = 0;
2472 CharUnits nextHeaderOffset;
2473 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2474 const Twine &name) {
2475 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2476 nextHeaderOffset, name);
2477 Builder.CreateStore(value, fieldAddr);
2478
2479 nextHeaderIndex++;
2480 nextHeaderOffset += fieldSize;
2481 };
John McCallf9b056b2011-03-31 08:03:29 +00002482
2483 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002484 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002485
2486 const VarDecl &D = *emission.Variable;
2487 QualType type = D.getType();
2488
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002489 bool HasByrefExtendedLayout;
2490 Qualifiers::ObjCLifetime ByrefLifetime;
2491 bool ByRefHasLifetime =
2492 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002493
John McCallf9b056b2011-03-31 08:03:29 +00002494 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002495
2496 // Initialize the 'isa', which is just 0 or 1.
2497 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002498 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002499 isa = 1;
2500 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002501 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002502
2503 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002504 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002505
2506 // Blocks ABI:
2507 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002508 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002509 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002510 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2511 if (ByRefHasLifetime) {
2512 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2513 else switch (ByrefLifetime) {
2514 case Qualifiers::OCL_Strong:
2515 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2516 break;
2517 case Qualifiers::OCL_Weak:
2518 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2519 break;
2520 case Qualifiers::OCL_ExplicitNone:
2521 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2522 break;
2523 case Qualifiers::OCL_None:
2524 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2525 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2526 break;
2527 default:
2528 break;
2529 }
2530 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2531 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2532 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2533 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2534 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2535 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2536 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2537 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2538 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2539 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2540 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2541 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2542 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2543 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2544 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2545 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2546 }
2547 printf("\n");
2548 }
2549 }
John McCall7f416cc2015-09-08 08:05:57 +00002550 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2551 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002552
John McCallf9b056b2011-03-31 08:03:29 +00002553 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2554 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002555 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002556
John McCallf9b056b2011-03-31 08:03:29 +00002557 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002558 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2559 "byref.copyHelper");
2560 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2561 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002562 }
John McCall7f416cc2015-09-08 08:05:57 +00002563
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002564 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002565 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2566 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002567 }
John McCall73064872011-03-31 01:59:53 +00002568}
2569
John McCallad7c5c12011-02-08 08:22:06 +00002570void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002571 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002572 llvm::Value *args[] = {
2573 Builder.CreateBitCast(V, Int8PtrTy),
2574 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2575 };
2576 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002577}
John McCall73064872011-03-31 01:59:53 +00002578
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002579void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2580 BlockFieldFlags Flags,
2581 bool LoadBlockVarAddr) {
2582 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr);
John McCall73064872011-03-31 01:59:53 +00002583}
John McCall7959fee2011-09-09 20:41:01 +00002584
2585/// Adjust the declaration of something from the blocks API.
2586static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2587 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002588 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002589
2590 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2591 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2592 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2593 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2594
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002595 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2596 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2597 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002598
2599 const NamedDecl *ND = nullptr;
2600 for (const auto &Result : DC->lookup(&II))
2601 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2602 (ND = dyn_cast<VarDecl>(Result)))
2603 break;
2604
2605 // TODO: support static blocks runtime
2606 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2607 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2608 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2609 } else {
2610 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2611 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2612 }
2613 }
2614
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002615 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2616 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002617 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002618
2619 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002620}
2621
2622llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2623 if (BlockObjectDispose)
2624 return BlockObjectDispose;
2625
2626 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2627 llvm::FunctionType *fty
2628 = llvm::FunctionType::get(VoidTy, args, false);
2629 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2630 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2631 return BlockObjectDispose;
2632}
2633
2634llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2635 if (BlockObjectAssign)
2636 return BlockObjectAssign;
2637
2638 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2639 llvm::FunctionType *fty
2640 = llvm::FunctionType::get(VoidTy, args, false);
2641 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2642 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2643 return BlockObjectAssign;
2644}
2645
2646llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2647 if (NSConcreteGlobalBlock)
2648 return NSConcreteGlobalBlock;
2649
2650 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002651 Int8PtrTy->getPointerTo(),
2652 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002653 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2654 return NSConcreteGlobalBlock;
2655}
2656
2657llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2658 if (NSConcreteStackBlock)
2659 return NSConcreteStackBlock;
2660
2661 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002662 Int8PtrTy->getPointerTo(),
2663 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002664 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002665 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002666}