blob: 50a6d61e7e53f995a556c876b42f2bb37e1083c0 [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"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
John McCall6c9f1fdb2016-11-19 08:17:24 +000019#include "ConstantBuilder.h"
Mike Stump692c6e32009-03-20 21:53:12 +000020#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000025#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000026#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000027
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall08ef4662011-11-10 08:15:53 +000031CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
32 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000033 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000034 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000035 DominatingIP(nullptr) {
36
John McCall08ef4662011-11-10 08:15:53 +000037 // Skip asm prefix, if any. 'name' is usually taken directly from
38 // the mangled name of the enclosing function.
39 if (!name.empty() && name[0] == '\01')
40 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000041}
42
John McCallf9b056b2011-03-31 08:03:29 +000043// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000044BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000045
John McCall351762c2011-02-07 10:33:21 +000046/// Build the given block as a global block.
47static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
48 const CGBlockInfo &blockInfo,
49 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000050
John McCall351762c2011-02-07 10:33:21 +000051/// Build the helper function to copy a block.
52static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
55}
56
Alp Tokerf6a24ce2013-12-05 16:25:25 +000057/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000058static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
61}
62
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000063/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
64/// buildBlockDescriptor is accessed from 5th field of the Block_literal
65/// meta-data and contains stationary information about the block literal.
66/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000067/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000068/// struct Block_descriptor {
69/// unsigned long reserved;
70/// unsigned long size; // size of Block_literal metadata in bytes.
71/// void *copy_func_helper_decl; // optional copy helper.
72/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000073/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000074/// void *block_layout_info; // encoding of captured block variables.
75/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// \endcode
John McCall351762c2011-02-07 10:33:21 +000077static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
78 const CGBlockInfo &blockInfo) {
79 ASTContext &C = CGM.getContext();
80
John McCall6c9f1fdb2016-11-19 08:17:24 +000081 llvm::IntegerType *ulong =
82 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
83 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000084 if (CGM.getLangOpts().OpenCL)
85 i8p =
86 llvm::Type::getInt8PtrTy(
87 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
88 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000089 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000090
John McCall23c9dc62016-11-28 22:18:27 +000091 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000092 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000098 // FIXME: What is the right way to say this doesn't fit? We should give
99 // a user diagnostic in that case. Better fix would be to change the
100 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000101 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000102
John McCall351762c2011-02-07 10:33:21 +0000103 // Optional copy/dispose helpers.
104 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000105 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000106 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000107
108 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110 }
111
John McCall351762c2011-02-07 10:33:21 +0000112 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
113 std::string typeAtEncoding =
114 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000115 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000116 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000117
John McCall351762c2011-02-07 10:33:21 +0000118 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000119 if (C.getLangOpts().ObjC1) {
120 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000121 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000123 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000124 }
John McCall351762c2011-02-07 10:33:21 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
Joey Goulyddbda402016-08-10 15:57:02 +0000128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000131
John McCall351762c2011-02-07 10:33:21 +0000132 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000133 elements.finishAndCreateGlobal("__block_descriptor_tmp",
134 CGM.getPointerAlign(),
135 /*constant*/ true,
136 llvm::GlobalValue::InternalLinkage,
137 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000138
John McCall351762c2011-02-07 10:33:21 +0000139 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000140}
141
John McCall351762c2011-02-07 10:33:21 +0000142/*
143 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000144
John McCall351762c2011-02-07 10:33:21 +0000145 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
146 struct Block_literal {
147 /// Initialized to one of:
148 /// extern void *_NSConcreteStackBlock[];
149 /// extern void *_NSConcreteGlobalBlock[];
150 ///
151 /// In theory, we could start one off malloc'ed by setting
152 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
153 /// this isa:
154 /// extern void *_NSConcreteMallocBlock[];
155 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000156
John McCall351762c2011-02-07 10:33:21 +0000157 /// These are the flags (with corresponding bit number) that the
158 /// compiler is actually supposed to know about.
159 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
160 /// descriptor provides copy and dispose helper functions
161 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
162 /// object with a nontrivial destructor or copy constructor
163 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
164 /// as global memory
165 /// 29. BLOCK_USE_STRET - indicates that the block function
166 /// uses stret, which objc_msgSend needs to know about
167 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
168 /// @encoded signature string
169 /// And we're not supposed to manipulate these:
170 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
171 /// to malloc'ed memory
172 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
173 /// to GC-allocated memory
174 /// Additionally, the bottom 16 bits are a reference count which
175 /// should be zero on the stack.
176 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Reserved; should be zero-initialized.
179 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Function pointer generated from block literal.
182 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Block description metadata generated from block literal.
185 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Captured values follow.
188 _CapturesTypes captures...;
189 };
190 */
David Chisnall950a9512009-11-17 19:33:30 +0000191
John McCall351762c2011-02-07 10:33:21 +0000192namespace {
193 /// A chunk of data that we actually have to capture in the block.
194 struct BlockLayoutChunk {
195 CharUnits Alignment;
196 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000197 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000198 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000199 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000200 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000201
John McCall351762c2011-02-07 10:33:21 +0000202 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000203 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000204 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000205 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000206 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000207 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000208
John McCall351762c2011-02-07 10:33:21 +0000209 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000210 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
211 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000212 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000213 info.CXXThisOffset = offset;
214 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000215 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
216 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000217 }
John McCall87fe5d52010-05-20 01:18:31 +0000218 }
John McCall351762c2011-02-07 10:33:21 +0000219 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000220
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000221 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
222 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000223 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000224 if (left.Alignment != right.Alignment)
225 return left.Alignment > right.Alignment;
226
227 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000228 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000229 return 1;
230 if (chunk.Lifetime == Qualifiers::OCL_Strong)
231 return 0;
232 if (chunk.Lifetime == Qualifiers::OCL_Weak)
233 return 2;
234 return 3;
235 };
236
237 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000238 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000239} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000240
John McCallb0a3ecb2011-02-08 03:07:00 +0000241/// Determines if the given type is safe for constant capture in C++.
242static bool isSafeForCXXConstantCapture(QualType type) {
243 const RecordType *recordType =
244 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
245
246 // Only records can be unsafe.
247 if (!recordType) return true;
248
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000249 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Maintain semantics for classes with non-trivial dtors or copy ctors.
252 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000253 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000254
255 // Otherwise, we just have to make sure there aren't any mutable
256 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000257 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000258}
259
John McCall351762c2011-02-07 10:33:21 +0000260/// It is illegal to modify a const object after initialization.
261/// Therefore, if a const object has a constant initializer, we don't
262/// actually need to keep storage for it in the block; we'll just
263/// rematerialize it at the start of the block function. This is
264/// acceptable because we make no promises about address stability of
265/// captured variables.
266static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000267 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000268 const VarDecl *var) {
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000269 // Return if this is a function paramter. We shouldn't try to
270 // rematerialize default arguments of function parameters.
271 if (isa<ParmVarDecl>(var))
272 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000273
John McCall351762c2011-02-07 10:33:21 +0000274 QualType type = var->getType();
275
276 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000277 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000278
John McCallb0a3ecb2011-02-08 03:07:00 +0000279 // Furthermore, in C++ we have to worry about mutable fields:
280 // C++ [dcl.type.cv]p4:
281 // Except that any class member declared mutable can be
282 // modified, any attempt to modify a const object during its
283 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000285 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000286
287 // If the variable doesn't have any initializer (shouldn't this be
288 // invalid?), it's not clear what we should do. Maybe capture as
289 // zero?
290 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000291 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000292
Richard Smithdafff942012-01-14 04:30:29 +0000293 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000294}
295
296/// Get the low bit of a nonzero character count. This is the
297/// alignment of the nth byte if the 0th byte is universally aligned.
298static CharUnits getLowBit(CharUnits v) {
299 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
300}
301
302static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000304 // The header is basically 'struct { void *; int; int; void *; void *; }'.
305 // Assert that that struct is packed.
306 assert(CGM.getIntSize() <= CGM.getPointerSize());
307 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
308 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000309
John McCall7f416cc2015-09-08 08:05:57 +0000310 info.BlockAlign = CGM.getPointerAlign();
311 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000312
313 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000314 elementTypes.push_back(CGM.VoidPtrTy);
315 elementTypes.push_back(CGM.IntTy);
316 elementTypes.push_back(CGM.IntTy);
317 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000318 elementTypes.push_back(CGM.getBlockDescriptorType());
John McCall351762c2011-02-07 10:33:21 +0000319}
320
321/// Compute the layout of the given block. Attempts to lay the block
322/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000323static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
324 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000325 ASTContext &C = CGM.getContext();
326 const BlockDecl *block = info.getBlockDecl();
327
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000329 initializeForBlockHeader(CGM, info, elementTypes);
330
331 if (!block->hasCaptures()) {
332 info.StructureType =
333 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
334 info.CanBeGlobal = true;
335 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000336 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000337 else if (C.getLangOpts().ObjC1 &&
338 CGM.getLangOpts().getGC() == LangOptions::NonGC)
339 info.HasCapturedVariableLayout = true;
340
John McCall351762c2011-02-07 10:33:21 +0000341 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000343 layout.reserve(block->capturesCXXThis() +
344 (block->capture_end() - block->capture_begin()));
345
346 CharUnits maxFieldAlign;
347
348 // First, 'this'.
349 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000350 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
351 "Can't capture 'this' outside a method");
352 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000353
John McCall7f416cc2015-09-08 08:05:57 +0000354 // Theoretically, this could be in a different address space, so
355 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000356 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000357 std::pair<CharUnits,CharUnits> tinfo
358 = CGM.getContext().getTypeInfoInChars(thisType);
359 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
360
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000361 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
362 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000363 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000364 }
365
366 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000367 for (const auto &CI : block->captures()) {
368 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000369
Aaron Ballman9371dd22014-03-14 18:34:04 +0000370 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000371 // We have to copy/dispose of the __block reference.
372 info.NeedsCopyDispose = true;
373
John McCall351762c2011-02-07 10:33:21 +0000374 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000375 CharUnits align = CGM.getPointerAlign();
376 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000377
John McCall7f416cc2015-09-08 08:05:57 +0000378 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
379 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000380 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000381 continue;
382 }
383
384 // Otherwise, build a layout chunk with the size and alignment of
385 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000386 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000387 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
388 continue;
389 }
390
John McCall31168b02011-06-15 23:02:42 +0000391 // If we have a lifetime qualifier, honor it for capture purposes.
392 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000393 Qualifiers::ObjCLifetime lifetime =
394 variable->getType().getObjCLifetime();
395 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000396 switch (lifetime) {
397 case Qualifiers::OCL_None: llvm_unreachable("impossible");
398 case Qualifiers::OCL_ExplicitNone:
399 case Qualifiers::OCL_Autoreleasing:
400 break;
John McCall351762c2011-02-07 10:33:21 +0000401
John McCall31168b02011-06-15 23:02:42 +0000402 case Qualifiers::OCL_Strong:
403 case Qualifiers::OCL_Weak:
404 info.NeedsCopyDispose = true;
405 }
406
407 // Block pointers require copy/dispose. So do Objective-C pointers.
408 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000409 // But honor the inert __unsafe_unretained qualifier, which doesn't
410 // actually make it into the type system.
411 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
412 lifetime = Qualifiers::OCL_ExplicitNone;
413 } else {
414 info.NeedsCopyDispose = true;
415 // used for mrr below.
416 lifetime = Qualifiers::OCL_Strong;
417 }
John McCall351762c2011-02-07 10:33:21 +0000418
419 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000420 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000421 info.NeedsCopyDispose = true;
422 info.HasCXXObject = true;
423
424 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000425 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000426 if (const CXXRecordDecl *record =
427 variable->getType()->getAsCXXRecordDecl()) {
428 if (!record->hasTrivialDestructor()) {
429 info.HasCXXObject = true;
430 info.NeedsCopyDispose = true;
431 }
432 }
433 }
434
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000435 QualType VT = variable->getType();
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000436
437 // If the variable is captured by an enclosing block or lambda expression,
438 // use the type of the capture field.
439 if (CGF->BlockInfo && CI.isNested())
440 VT = CGF->BlockInfo->getCapture(variable).fieldType();
441 else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
442 VT = FD->getType();
443
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000444 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000445 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000446
John McCall351762c2011-02-07 10:33:21 +0000447 maxFieldAlign = std::max(maxFieldAlign, align);
448
Jay Foad7c57be32011-07-11 09:56:20 +0000449 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000450 CGM.getTypes().ConvertTypeForMem(VT);
451
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000452 layout.push_back(
453 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000454 }
455
456 // If that was everything, we're done here.
457 if (layout.empty()) {
458 info.StructureType =
459 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460 info.CanBeGlobal = true;
461 return;
462 }
463
464 // Sort the layout by alignment. We have to use a stable sort here
465 // to get reproducible results. There should probably be an
466 // llvm::array_pod_stable_sort.
467 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000468
469 // Needed for blocks layout info.
470 info.BlockHeaderForcedGapOffset = info.BlockSize;
471 info.BlockHeaderForcedGapSize = CharUnits::Zero();
472
John McCall351762c2011-02-07 10:33:21 +0000473 CharUnits &blockSize = info.BlockSize;
474 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475
476 // Assuming that the first byte in the header is maximally aligned,
477 // get the alignment of the first byte following the header.
478 CharUnits endAlign = getLowBit(blockSize);
479
480 // If the end of the header isn't satisfactorily aligned for the
481 // maximum thing, look for things that are okay with the header-end
482 // alignment, and keep appending them until we get something that's
483 // aligned right. This algorithm is only guaranteed optimal if
484 // that condition is satisfied at some point; otherwise we can get
485 // things like:
486 // header // next byte has alignment 4
487 // something_with_size_5; // next byte has alignment 1
488 // something_with_alignment_8;
489 // which has 7 bytes of padding, as opposed to the naive solution
490 // which might have less (?).
491 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000493 li = layout.begin() + 1, le = layout.end();
494
495 // Look for something that the header end is already
496 // satisfactorily aligned for.
497 for (; li != le && endAlign < li->Alignment; ++li)
498 ;
499
500 // If we found something that's naturally aligned for the end of
501 // the header, keep adding things...
502 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000504 for (; li != le; ++li) {
505 assert(endAlign >= li->Alignment);
506
John McCall7f416cc2015-09-08 08:05:57 +0000507 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000508 elementTypes.push_back(li->Type);
509 blockSize += li->Size;
510 endAlign = getLowBit(blockSize);
511
512 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000513 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000514 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000515 }
John McCall351762c2011-02-07 10:33:21 +0000516 }
John McCall351762c2011-02-07 10:33:21 +0000517 // Don't re-append everything we just appended.
518 layout.erase(first, li);
519 }
520 }
521
John McCallac0350a2012-04-26 21:14:42 +0000522 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000523
John McCall351762c2011-02-07 10:33:21 +0000524 // At this point, we just have to add padding if the end align still
525 // isn't aligned right.
526 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000527 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000528 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000529
John McCall7f416cc2015-09-08 08:05:57 +0000530 // If we haven't yet added any fields, remember that there was an
531 // initial gap; this need to go into the block layout bit map.
532 if (blockSize == info.BlockHeaderForcedGapOffset) {
533 info.BlockHeaderForcedGapSize = padding;
534 }
535
John McCalle3dc1702011-02-15 09:22:45 +0000536 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
537 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000538 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000539 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000540 }
541
John McCall1db0a2f2012-05-01 20:28:00 +0000542 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000543 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000544 // Slam everything else on now. This works because they have
545 // strictly decreasing alignment and we expect that size is always a
546 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000547 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000548 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000549 if (endAlign < li->Alignment) {
550 // size may not be multiple of alignment. This can only happen with
551 // an over-aligned variable. We will be adding a padding field to
552 // make the size be multiple of alignment.
553 CharUnits padding = li->Alignment - endAlign;
554 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
555 padding.getQuantity()));
556 blockSize += padding;
557 endAlign = getLowBit(blockSize);
558 }
John McCall351762c2011-02-07 10:33:21 +0000559 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000560 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000561 elementTypes.push_back(li->Type);
562 blockSize += li->Size;
563 endAlign = getLowBit(blockSize);
564 }
565
566 info.StructureType =
567 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
568}
569
John McCall08ef4662011-11-10 08:15:53 +0000570/// Enter the scope of a block. This should be run at the entrance to
571/// a full-expression so that the block's cleanups are pushed at the
572/// right place in the stack.
573static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000574 assert(CGF.HaveInsertPoint());
575
John McCall08ef4662011-11-10 08:15:53 +0000576 // Allocate the block info and place it at the head of the list.
577 CGBlockInfo &blockInfo =
578 *new CGBlockInfo(block, CGF.CurFn->getName());
579 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
580 CGF.FirstBlockInfo = &blockInfo;
581
582 // Compute information about the layout, etc., of this block,
583 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000584 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000585
586 // Nothing else to do if it can be global.
587 if (blockInfo.CanBeGlobal) return;
588
589 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000590 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
591 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000592
593 // If there are cleanups to emit, enter them (but inactive).
594 if (!blockInfo.NeedsCopyDispose) return;
595
596 // Walk through the captures (in order) and find the ones not
597 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000598 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000599 // Ignore __block captures; there's nothing special in the
600 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000601 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000602
603 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000604 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000605 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606 if (capture.isConstant()) continue;
607
608 // Ignore objects that aren't destructed.
609 QualType::DestructionKind dtorKind =
610 variable->getType().isDestructedType();
611 if (dtorKind == QualType::DK_none) continue;
612
613 CodeGenFunction::Destroyer *destroyer;
614
615 // Block captures count as local values and have imprecise semantics.
616 // They also can't be arrays, so need to worry about that.
617 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000618 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000619 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000620 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000621 }
622
623 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000624 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
625 capture.getIndex(),
626 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000627
John McCallf4beacd2011-11-10 10:43:54 +0000628 // We can use that GEP as the dominating IP.
629 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000630 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000631
John McCall08ef4662011-11-10 08:15:53 +0000632 CleanupKind cleanupKind = InactiveNormalCleanup;
633 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
634 if (useArrayEHCleanup)
635 cleanupKind = InactiveNormalAndEHCleanup;
636
637 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000638 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000639
640 // Remember where that cleanup was.
641 capture.setCleanup(CGF.EHStack.stable_begin());
642 }
643}
644
645/// Enter a full-expression with a non-trivial number of objects to
646/// clean up. This is in this file because, at the moment, the only
647/// kind of cleanup object is a BlockDecl*.
648void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
649 assert(E->getNumObjects() != 0);
650 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
651 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
652 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
653 enterBlockScope(*this, *i);
654 }
655}
656
657/// Find the layout for the given block in a linked list and remove it.
658static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
659 const BlockDecl *block) {
660 while (true) {
661 assert(head && *head);
662 CGBlockInfo *cur = *head;
663
664 // If this is the block we're looking for, splice it out of the list.
665 if (cur->getBlockDecl() == block) {
666 *head = cur->NextBlockInfo;
667 return cur;
668 }
669
670 head = &cur->NextBlockInfo;
671 }
672}
673
674/// Destroy a chain of block layouts.
675void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
676 assert(head && "destroying an empty chain");
677 do {
678 CGBlockInfo *cur = head;
679 head = cur->NextBlockInfo;
680 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000681 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000682}
683
John McCall351762c2011-02-07 10:33:21 +0000684/// Emit a block literal expression in the current function.
685llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000686 // If the block has no captures, we won't have a pre-computed
687 // layout for it.
688 if (!blockExpr->getBlockDecl()->hasCaptures()) {
689 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000690 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000691 blockInfo.BlockExpression = blockExpr;
692 return EmitBlockLiteral(blockInfo);
693 }
John McCall351762c2011-02-07 10:33:21 +0000694
John McCall08ef4662011-11-10 08:15:53 +0000695 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000696 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000697 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
698 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000699
John McCall08ef4662011-11-10 08:15:53 +0000700 blockInfo->BlockExpression = blockExpr;
701 return EmitBlockLiteral(*blockInfo);
702}
703
704llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
705 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000706 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000707 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000708 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000709 LocalDeclMap,
710 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000711 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000712
713 // If there is nothing to capture, we can emit this as a global block.
714 if (blockInfo.CanBeGlobal)
715 return buildGlobalBlock(CGM, blockInfo, blockFn);
716
717 // Otherwise, we have to emit this as a local block.
718
719 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000720 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000721
722 // Build the block descriptor.
723 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
724
John McCall7f416cc2015-09-08 08:05:57 +0000725 Address blockAddr = blockInfo.LocalAddress;
726 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000727
728 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000729 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000730 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000731 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
732 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000733 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000734
John McCall7f416cc2015-09-08 08:05:57 +0000735 auto projectField =
736 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
737 return Builder.CreateStructGEP(blockAddr, index, offset, name);
738 };
739 auto storeField =
740 [&](llvm::Value *value, unsigned index, CharUnits offset,
741 const Twine &name) {
742 Builder.CreateStore(value, projectField(index, offset, name));
743 };
744
745 // Initialize the block header.
746 {
747 // We assume all the header fields are densely packed.
748 unsigned index = 0;
749 CharUnits offset;
750 auto addHeaderField =
751 [&](llvm::Value *value, CharUnits size, const Twine &name) {
752 storeField(value, index, offset, name);
753 offset += size;
754 index++;
755 };
756
757 addHeaderField(isa, getPointerSize(), "block.isa");
758 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
759 getIntSize(), "block.flags");
760 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
761 getIntSize(), "block.reserved");
762 addHeaderField(blockFn, getPointerSize(), "block.invoke");
763 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
764 }
John McCall351762c2011-02-07 10:33:21 +0000765
766 // Finally, capture all the values into the block.
767 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
768
769 // First, 'this'.
770 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000771 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
772 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000773 Builder.CreateStore(LoadCXXThis(), addr);
774 }
775
776 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000777 for (const auto &CI : blockDecl->captures()) {
778 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000779 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
780
781 // Ignore constant captures.
782 if (capture.isConstant()) continue;
783
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000784 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000785
786 // This will be a [[type]]*, except that a byref entry will just be
787 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000788 Address blockField =
789 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000790
791 // Compute the address of the thing we're going to move into the
792 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000793 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000794
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000795 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000796 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000797 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000798 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000799 } else if (CI.isByRef()) {
800 if (BlockInfo && CI.isNested()) {
801 // We need to use the capture from the enclosing block.
802 const CGBlockInfo::Capture &enclosingCapture =
803 BlockInfo->getCapture(variable);
804
805 // This is a [[type]]*, except that a byref entry wil just be an i8**.
806 src = Builder.CreateStructGEP(LoadBlockStruct(),
807 enclosingCapture.getIndex(),
808 enclosingCapture.getOffset(),
809 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000810 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000811 auto I = LocalDeclMap.find(variable);
812 assert(I != LocalDeclMap.end());
813 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000814 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000815 } else {
816 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
817 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
818 type.getNonReferenceType(), VK_LValue,
819 SourceLocation());
820 src = EmitDeclRefLValue(&declRef).getAddress();
821 };
John McCall351762c2011-02-07 10:33:21 +0000822
823 // For byrefs, we just write the pointer to the byref struct into
824 // the block field. There's no need to chase the forwarding
825 // pointer at this point, since we're building something that will
826 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000827 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000828 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000829 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000830 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000831 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000832 else
John McCall7f416cc2015-09-08 08:05:57 +0000833 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000834
John McCalle3dc1702011-02-15 09:22:45 +0000835 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000836 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000837
838 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000839 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000840 if (blockDecl->isConversionFromLambda()) {
841 // If we have a lambda conversion, emit the expression
842 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000843 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000844 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000845 AggValueSlot::IsDestructed,
846 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000847 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000848 EmitAggExpr(copyExpr, Slot);
849 } else {
850 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
851 }
John McCall351762c2011-02-07 10:33:21 +0000852
853 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000854 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000855 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000856
857 // If this is an ARC __strong block-pointer variable, don't do a
858 // block copy.
859 //
860 // TODO: this can be generalized into the normal initialization logic:
861 // we should never need to do a block-copy when initializing a local
862 // variable, because the local variable's lifetime should be strictly
863 // contained within the stack block's.
864 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
865 type->isBlockPointerType()) {
866 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000867 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000868 value = EmitARCRetainNonBlock(value);
869
870 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000871 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000872
873 // Otherwise, fake up a POD copy into the block field.
874 } else {
John McCall31168b02011-06-15 23:02:42 +0000875 // Fake up a new variable so that EmitScalarInit doesn't think
876 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000877 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
878 SourceLocation(), /*name*/ nullptr,
879 type);
John McCall31168b02011-06-15 23:02:42 +0000880
John McCall93be3f72011-02-07 18:37:40 +0000881 // We use one of these or the other depending on whether the
882 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000883 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
884 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
885 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000886
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000887 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000888 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000889 // FIXME: Pass a specific location for the expr init so that the store is
890 // attributed to a reasonable location - otherwise it may be attributed to
891 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000892 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000893 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000894 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000895 }
896
John McCall08ef4662011-11-10 08:15:53 +0000897 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000898 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000899 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
900 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000901 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000902 }
John McCall351762c2011-02-07 10:33:21 +0000903 }
904
905 // Cast to the converted block-pointer type, which happens (somewhat
906 // unfortunately) to be a pointer to function type.
907 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000908 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000909 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000910
John McCall351762c2011-02-07 10:33:21 +0000911 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000912}
913
914
Chris Lattnera5f58b02011-07-09 17:41:47 +0000915llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000916 if (BlockDescriptorType)
917 return BlockDescriptorType;
918
Chris Lattnera5f58b02011-07-09 17:41:47 +0000919 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000920 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000921
Mike Stump650c9322009-02-13 15:16:56 +0000922 // struct __block_descriptor {
923 // unsigned long reserved;
924 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000925 //
926 // // later, the following will be added
927 //
928 // struct {
929 // void (*copyHelper)();
930 // void (*copyHelper)();
931 // } helpers; // !!! optional
932 //
933 // const char *signature; // the block signature
934 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000935 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000936 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000937 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000938 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000939
John McCall351762c2011-02-07 10:33:21 +0000940 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +0000941 unsigned AddrSpace = 0;
942 if (getLangOpts().OpenCL)
943 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
944 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +0000945 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000946}
947
Chris Lattnera5f58b02011-07-09 17:41:47 +0000948llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000949 if (GenericBlockLiteralType)
950 return GenericBlockLiteralType;
951
Chris Lattnera5f58b02011-07-09 17:41:47 +0000952 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000953
Mike Stump005c9a62009-02-13 15:25:34 +0000954 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000955 // void *__isa;
956 // int __flags;
957 // int __reserved;
958 // void (*__invoke)(void *);
959 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000960 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000961 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000962 llvm::StructType::create("struct.__block_literal_generic",
963 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000964 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000965
Mike Stump005c9a62009-02-13 15:25:34 +0000966 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000967}
968
Nick Lewycky2d84e842013-10-02 02:29:49 +0000969RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000970 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000971 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000972 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000973
John McCallb92ab1a2016-10-26 23:46:34 +0000974 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000975
976 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000977 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000978 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000979
980 // Bitcast the callee to a block literal.
John McCallb92ab1a2016-10-26 23:46:34 +0000981 BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000982
983 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000984 llvm::Value *FuncPtr =
John McCallb92ab1a2016-10-26 23:46:34 +0000985 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000986
John McCallb92ab1a2016-10-26 23:46:34 +0000987 BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000988
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000989 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000990 CallArgList Args;
John McCallb92ab1a2016-10-26 23:46:34 +0000991 Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000992
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000993 QualType FnType = BPT->getPointeeType();
994
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000995 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +0000996 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +0000997
Anders Carlsson5f50c652009-04-07 22:10:22 +0000998 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +0000999 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001000
John McCall85915252011-03-09 08:39:33 +00001001 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001002 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001003 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Anders Carlsson5f50c652009-04-07 22:10:22 +00001005 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001006 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001007
Chris Lattner2192fe52011-07-18 04:24:23 +00001008 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +00001009 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001010
John McCallb92ab1a2016-10-26 23:46:34 +00001011 // Prepare the callee.
1012 CGCallee Callee(CGCalleeInfo(), Func);
1013
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001014 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001015 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001016}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001017
John McCall7f416cc2015-09-08 08:05:57 +00001018Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1019 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001020 assert(BlockInfo && "evaluating block ref without block information?");
1021 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001022
John McCall351762c2011-02-07 10:33:21 +00001023 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001024 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001025
John McCall7f416cc2015-09-08 08:05:57 +00001026 Address addr =
1027 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1028 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001029
John McCall351762c2011-02-07 10:33:21 +00001030 if (isByRef) {
1031 // addr should be a void** right now. Load, then cast the result
1032 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001033
John McCall7f416cc2015-09-08 08:05:57 +00001034 auto &byrefInfo = getBlockByrefInfo(variable);
1035 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001036
John McCall7f416cc2015-09-08 08:05:57 +00001037 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1038 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001039
John McCall7f416cc2015-09-08 08:05:57 +00001040 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1041 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001042 }
1043
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001044 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001045 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001046
John McCall351762c2011-02-07 10:33:21 +00001047 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001048}
1049
Mike Stump2d5a2872009-02-14 22:16:35 +00001050llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001051CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1052 StringRef Name) {
1053 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1054 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001055
John McCall351762c2011-02-07 10:33:21 +00001056 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001057 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001058
John McCall351762c2011-02-07 10:33:21 +00001059 // Using that metadata, generate the actual block function.
1060 llvm::Constant *blockFn;
1061 {
John McCall7f416cc2015-09-08 08:05:57 +00001062 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001063 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1064 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001065 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001066 false);
John McCall351762c2011-02-07 10:33:21 +00001067 }
John McCalle3dc1702011-02-15 09:22:45 +00001068 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001069
John McCallad7c5c12011-02-08 08:22:06 +00001070 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001071}
1072
John McCall351762c2011-02-07 10:33:21 +00001073static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1074 const CGBlockInfo &blockInfo,
1075 llvm::Constant *blockFn) {
1076 assert(blockInfo.CanBeGlobal);
1077
1078 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001079 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001080 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001081
1082 // isa
John McCall6c9f1fdb2016-11-19 08:17:24 +00001083 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001084
1085 // __flags
John McCall85915252011-03-09 08:39:33 +00001086 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1087 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1088
John McCall6c9f1fdb2016-11-19 08:17:24 +00001089 fields.addInt(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001090
1091 // Reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +00001092 fields.addInt(CGM.IntTy, 0);
John McCall351762c2011-02-07 10:33:21 +00001093
1094 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001095 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001096
1097 // Descriptor
John McCall6c9f1fdb2016-11-19 08:17:24 +00001098 fields.add(buildBlockDescriptor(CGM, blockInfo));
John McCall351762c2011-02-07 10:33:21 +00001099
John McCall6c9f1fdb2016-11-19 08:17:24 +00001100 llvm::Constant *literal =
1101 fields.finishAndCreateGlobal("__block_literal_global",
1102 blockInfo.BlockAlign,
1103 /*constant*/ true);
John McCall351762c2011-02-07 10:33:21 +00001104
1105 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001106 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001107 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1108 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001109}
1110
John McCall7f416cc2015-09-08 08:05:57 +00001111void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1112 unsigned argNum,
1113 llvm::Value *arg) {
1114 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1115
1116 llvm::Value *localAddr = nullptr;
1117 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1118 // Allocate a stack slot to let the debug info survive the RA.
1119 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1120 Builder.CreateStore(arg, alloc);
1121 localAddr = Builder.CreateLoad(alloc);
1122 }
1123
1124 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001125 if (CGM.getCodeGenOpts().getDebugInfo() >=
1126 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001127 DI->setLocation(D->getLocation());
1128 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1129 localAddr, Builder);
1130 }
1131 }
1132
1133 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1134 ApplyDebugLocation Scope(*this, StartLoc);
1135
1136 // Instead of messing around with LocalDeclMap, just set the value
1137 // directly as BlockPointer.
1138 BlockPointer = Builder.CreateBitCast(arg,
1139 BlockInfo->StructureType->getPointerTo(),
1140 "block");
1141}
1142
1143Address CodeGenFunction::LoadBlockStruct() {
1144 assert(BlockInfo && "not in a block invocation function!");
1145 assert(BlockPointer && "no block pointer set!");
1146 return Address(BlockPointer, BlockInfo->BlockAlign);
1147}
1148
Mike Stump4446dcf2009-03-05 08:32:30 +00001149llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001150CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1151 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001152 const DeclMapTy &ldm,
1153 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001154 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001155
Fariborz Jahanian63628032012-06-26 16:06:38 +00001156 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001157
1158 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001159
John McCall351762c2011-02-07 10:33:21 +00001160 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001161
Mike Stump5469f292009-03-13 23:34:28 +00001162 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001163 // to be local to this function as well, in case they're directly
1164 // referenced in a block.
1165 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001166 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001167 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001168 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001169 }
1170
John McCall351762c2011-02-07 10:33:21 +00001171 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001172
John McCall351762c2011-02-07 10:33:21 +00001173 // Build the argument list.
1174 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001175
John McCall351762c2011-02-07 10:33:21 +00001176 // The first argument is the block pointer. Just take it as a void*
1177 // and cast it later.
1178 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001179 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001180
Richard Smith053f6c62014-05-16 23:01:30 +00001181 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001182 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001183 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001184
John McCall351762c2011-02-07 10:33:21 +00001185 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001186 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001187
John McCall351762c2011-02-07 10:33:21 +00001188 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001189 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001190 const CGFunctionInfo &fnInfo =
1191 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001192 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001193 blockInfo.UsesStret = true;
1194
John McCalla729c622012-02-17 03:33:10 +00001195 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001196
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001197 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001198 llvm::Function *fn = llvm::Function::Create(
1199 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001200 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001201
John McCall351762c2011-02-07 10:33:21 +00001202 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001203 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001204 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001205 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001206
John McCall147d0212011-02-22 22:38:33 +00001207 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001208
Adrian Prantl0f6df002013-03-29 19:20:35 +00001209 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1210 // won't delete the dbg.declare intrinsics for captured variables.
1211 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1212 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1213 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001214 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1215 getPointerAlign(),
1216 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001217 // Set the DebugLocation to empty, so the store is recognized as a
1218 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001219 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001220 Builder.CreateStore(BlockPointer, Alloca);
1221 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001222 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001223
John McCall87fe5d52010-05-20 01:18:31 +00001224 // If we have a C++ 'this' reference, go ahead and force it into
1225 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001226 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001227 Address addr =
1228 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1229 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001230 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001231 }
1232
John McCall351762c2011-02-07 10:33:21 +00001233 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001234 for (const auto &CI : blockDecl->captures()) {
1235 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001236 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1237 if (!capture.isConstant()) continue;
1238
John McCall7f416cc2015-09-08 08:05:57 +00001239 CharUnits align = getContext().getDeclAlign(variable);
1240 Address alloca =
1241 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001242
John McCall7f416cc2015-09-08 08:05:57 +00001243 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001244
John McCall7f416cc2015-09-08 08:05:57 +00001245 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001246 }
1247
John McCall113bee02012-03-10 09:33:50 +00001248 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001249 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1250 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1251 --entry_ptr;
1252
Eli Friedman2495ab02012-02-25 02:48:22 +00001253 if (IsLambdaConversionToBlock)
1254 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001255 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001256 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001257 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001258 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001259 }
Mike Stump017460a2009-10-01 22:29:41 +00001260
Mike Stump7d699112009-10-01 00:27:30 +00001261 // Remember where we were...
1262 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001263
Mike Stump7d699112009-10-01 00:27:30 +00001264 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001265 ++entry_ptr;
1266 Builder.SetInsertPoint(entry, entry_ptr);
1267
John McCall113bee02012-03-10 09:33:50 +00001268 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001269 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001270 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001271 for (const auto &CI : blockDecl->captures()) {
1272 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001273 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001274
Benjamin Kramer8c305922016-02-02 11:06:51 +00001275 if (CGM.getCodeGenOpts().getDebugInfo() >=
1276 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001277 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1278 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001279 auto addr = LocalDeclMap.find(variable)->second;
1280 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001281 Builder);
1282 continue;
1283 }
John McCall351762c2011-02-07 10:33:21 +00001284
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001285 DI->EmitDeclareOfBlockDeclRefVariable(
1286 variable, BlockPointerDbgLoc, Builder, blockInfo,
1287 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001288 }
Mike Stump2e722b92009-09-30 02:43:10 +00001289 }
Manman Renab08a9a2013-01-04 18:51:35 +00001290 // Recover location if it was changed in the above loop.
1291 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001292 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001293 }
John McCall351762c2011-02-07 10:33:21 +00001294
Mike Stump7d699112009-10-01 00:27:30 +00001295 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001296 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001297 Builder.ClearInsertionPoint();
1298 else
1299 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001300
John McCall351762c2011-02-07 10:33:21 +00001301 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001302
John McCall351762c2011-02-07 10:33:21 +00001303 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001304}
Mike Stump1db7d042009-02-28 09:07:16 +00001305
John McCall351762c2011-02-07 10:33:21 +00001306/*
1307 notes.push_back(HelperInfo());
1308 HelperInfo &note = notes.back();
1309 note.index = capture.getIndex();
1310 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1311 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001312
John McCall351762c2011-02-07 10:33:21 +00001313 if (ci->isByRef()) {
1314 note.flag = BLOCK_FIELD_IS_BYREF;
1315 if (type.isObjCGCWeak())
1316 note.flag |= BLOCK_FIELD_IS_WEAK;
1317 } else if (type->isBlockPointerType()) {
1318 note.flag = BLOCK_FIELD_IS_BLOCK;
1319 } else {
1320 note.flag = BLOCK_FIELD_IS_OBJECT;
1321 }
1322 */
Mike Stump1db7d042009-02-28 09:07:16 +00001323
John McCallf593b102013-01-22 03:56:22 +00001324/// Generate the copy-helper function for a block closure object:
1325/// static void block_copy_helper(block_t *dst, block_t *src);
1326/// The runtime will have previously initialized 'dst' by doing a
1327/// bit-copy of 'src'.
1328///
1329/// Note that this copies an entire block closure object to the heap;
1330/// it should not be confused with a 'byref copy helper', which moves
1331/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001332llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001333CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001334 ASTContext &C = getContext();
1335
1336 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001337 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1338 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001339 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001340 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1341 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001342 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001343
John McCallc56a8b32016-03-11 04:30:31 +00001344 const CGFunctionInfo &FI =
1345 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001346
John McCall351762c2011-02-07 10:33:21 +00001347 // FIXME: it would be nice if these were mergeable with things with
1348 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001349 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001350
1351 llvm::Function *Fn =
1352 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001353 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001354
1355 IdentifierInfo *II
1356 = &CGM.getContext().Idents.get("__copy_helper_block_");
1357
John McCall351762c2011-02-07 10:33:21 +00001358 FunctionDecl *FD = FunctionDecl::Create(C,
1359 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001360 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001361 SourceLocation(), II, C.VoidTy,
1362 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001363 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001364 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001365
1366 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1367
Adrian Prantl95b24e92015-02-03 20:00:54 +00001368 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001369 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001370 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001371 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001372 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001373
John McCall7f416cc2015-09-08 08:05:57 +00001374 Address src = GetAddrOfLocalVar(&srcDecl);
1375 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001376 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001377
John McCall7f416cc2015-09-08 08:05:57 +00001378 Address dst = GetAddrOfLocalVar(&dstDecl);
1379 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001380 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001381
John McCall351762c2011-02-07 10:33:21 +00001382 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001383
Aaron Ballman9371dd22014-03-14 18:34:04 +00001384 for (const auto &CI : blockDecl->captures()) {
1385 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001386 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001387
John McCall351762c2011-02-07 10:33:21 +00001388 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1389 if (capture.isConstant()) continue;
1390
Aaron Ballman9371dd22014-03-14 18:34:04 +00001391 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001392 BlockFieldFlags flags;
1393
John McCalle68b8f42012-10-17 02:28:37 +00001394 bool useARCWeakCopy = false;
1395 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001396
1397 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001398 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001399 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001400
Aaron Ballman9371dd22014-03-14 18:34:04 +00001401 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001402 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001403 if (type.isObjCGCWeak())
1404 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001405
John McCall31168b02011-06-15 23:02:42 +00001406 } else if (type->isObjCRetainableType()) {
1407 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001408 bool isBlockPointer = type->isBlockPointerType();
1409 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001410 flags = BLOCK_FIELD_IS_BLOCK;
1411
1412 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001413 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001414
John McCall460ce582015-10-22 18:38:17 +00001415 // We need to register __weak direct captures with the runtime.
1416 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1417 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001418
John McCall460ce582015-10-22 18:38:17 +00001419 // We need to retain the copied value for __strong direct captures.
1420 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1421 // If it's a block pointer, we have to copy the block and
1422 // assign that to the destination pointer, so we might as
1423 // well use _Block_object_assign. Otherwise we can avoid that.
1424 if (!isBlockPointer)
1425 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001426
1427 // Non-ARC captures of retainable pointers are strong and
1428 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001429 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001430 // fall through
John McCall460ce582015-10-22 18:38:17 +00001431
1432 // Otherwise the memcpy is fine.
1433 } else {
1434 continue;
John McCall31168b02011-06-15 23:02:42 +00001435 }
John McCall460ce582015-10-22 18:38:17 +00001436
1437 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001438 } else {
1439 continue;
1440 }
John McCall351762c2011-02-07 10:33:21 +00001441
1442 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001443 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1444 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001445
1446 // If there's an explicit copy expression, we do that.
1447 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001448 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001449 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001450 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001451 } else {
1452 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001453 if (useARCStrongCopy) {
1454 // At -O0, store null into the destination field (so that the
1455 // storeStrong doesn't over-release) and then call storeStrong.
1456 // This is a workaround to not having an initStrong call.
1457 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001458 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001459 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1460 Builder.CreateStore(null, dstField);
1461 EmitARCStoreStrongCall(dstField, srcValue, true);
1462
1463 // With optimization enabled, take advantage of the fact that
1464 // the blocks runtime guarantees a memcpy of the block data, and
1465 // just emit a retain of the src field.
1466 } else {
1467 EmitARCRetainNonBlock(srcValue);
1468
1469 // We don't need this anymore, so kill it. It's not quite
1470 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001471 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001472 }
1473 } else {
1474 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001475 llvm::Value *dstAddr =
1476 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001477 llvm::Value *args[] = {
1478 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1479 };
1480
1481 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001482 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001483 const Expr *copyExpr =
1484 CGM.getContext().getBlockVarCopyInits(variable);
1485 if (copyExpr) {
1486 copyCanThrow = true; // FIXME: reuse the noexcept logic
1487 }
1488 }
1489
1490 if (copyCanThrow) {
1491 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1492 } else {
1493 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1494 }
John McCalle68b8f42012-10-17 02:28:37 +00001495 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001496 }
1497 }
1498
John McCallad7c5c12011-02-08 08:22:06 +00001499 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001500
John McCalle3dc1702011-02-15 09:22:45 +00001501 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001502}
1503
John McCallf593b102013-01-22 03:56:22 +00001504/// Generate the destroy-helper function for a block closure object:
1505/// static void block_destroy_helper(block_t *theBlock);
1506///
1507/// Note that this destroys a heap-allocated block closure object;
1508/// it should not be confused with a 'byref destroy helper', which
1509/// destroys the heap-allocated contents of an individual __block
1510/// variable.
John McCall351762c2011-02-07 10:33:21 +00001511llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001512CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001513 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001514
John McCall351762c2011-02-07 10:33:21 +00001515 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001516 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1517 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001518 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001519
John McCallc56a8b32016-03-11 04:30:31 +00001520 const CGFunctionInfo &FI =
1521 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001522
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001523 // FIXME: We'd like to put these into a mergable by content, with
1524 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001525 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001526
1527 llvm::Function *Fn =
1528 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001529 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001530
1531 IdentifierInfo *II
1532 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1533
John McCall351762c2011-02-07 10:33:21 +00001534 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001535 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001536 SourceLocation(), II, C.VoidTy,
1537 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001538 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001539
1540 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1541
Adrian Prantl49a78562013-07-24 20:34:39 +00001542 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001543 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001544 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001545 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001546
Chris Lattner2192fe52011-07-18 04:24:23 +00001547 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001548
John McCall7f416cc2015-09-08 08:05:57 +00001549 Address src = GetAddrOfLocalVar(&srcDecl);
1550 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001551 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001552
John McCall351762c2011-02-07 10:33:21 +00001553 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1554
John McCallad7c5c12011-02-08 08:22:06 +00001555 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001556
Aaron Ballman9371dd22014-03-14 18:34:04 +00001557 for (const auto &CI : blockDecl->captures()) {
1558 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001559 QualType type = variable->getType();
1560
1561 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1562 if (capture.isConstant()) continue;
1563
John McCallad7c5c12011-02-08 08:22:06 +00001564 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001565 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001566
John McCalle68b8f42012-10-17 02:28:37 +00001567 bool useARCWeakDestroy = false;
1568 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001569
Aaron Ballman9371dd22014-03-14 18:34:04 +00001570 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001571 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001572 if (type.isObjCGCWeak())
1573 flags |= BLOCK_FIELD_IS_WEAK;
1574 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1575 if (record->hasTrivialDestructor())
1576 continue;
1577 dtor = record->getDestructor();
1578 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001579 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001580 if (type->isBlockPointerType())
1581 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001582
John McCall31168b02011-06-15 23:02:42 +00001583 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001584 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001585
John McCall460ce582015-10-22 18:38:17 +00001586 // Use objc_storeStrong for __strong direct captures; the
1587 // dynamic tools really like it when we do this.
1588 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1589 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001590
John McCall460ce582015-10-22 18:38:17 +00001591 // Support __weak direct captures.
1592 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1593 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001594
John McCall460ce582015-10-22 18:38:17 +00001595 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1596 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1597 // fall through
1598
1599 // Otherwise, we have nothing to do.
1600 } else {
1601 continue;
John McCall31168b02011-06-15 23:02:42 +00001602 }
1603 } else {
1604 continue;
1605 }
John McCall351762c2011-02-07 10:33:21 +00001606
John McCall7f416cc2015-09-08 08:05:57 +00001607 Address srcField =
1608 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001609
1610 // If there's an explicit copy expression, we do that.
1611 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001612 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001613
John McCall31168b02011-06-15 23:02:42 +00001614 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001615 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001616 EmitARCDestroyWeak(srcField);
1617
John McCalle68b8f42012-10-17 02:28:37 +00001618 // Destroy strong objects with a call if requested.
1619 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001620 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001621
John McCall351762c2011-02-07 10:33:21 +00001622 // Otherwise we call _Block_object_dispose. It wouldn't be too
1623 // hard to just emit this as a cleanup if we wanted to make sure
1624 // that things were done in reverse.
1625 } else {
1626 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001627 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001628 BuildBlockRelease(value, flags);
1629 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001630 }
1631
John McCall351762c2011-02-07 10:33:21 +00001632 cleanups.ForceCleanup();
1633
John McCallad7c5c12011-02-08 08:22:06 +00001634 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001635
John McCalle3dc1702011-02-15 09:22:45 +00001636 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001637}
1638
John McCallf9b056b2011-03-31 08:03:29 +00001639namespace {
1640
1641/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001642class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001643 BlockFieldFlags Flags;
1644
1645public:
1646 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001647 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001648
John McCall7f416cc2015-09-08 08:05:57 +00001649 void emitCopy(CodeGenFunction &CGF, Address destField,
1650 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001651 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1652
1653 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1654 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1655
1656 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1657
1658 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1659 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001660
John McCall7f416cc2015-09-08 08:05:57 +00001661 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001662 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001663 }
1664
John McCall7f416cc2015-09-08 08:05:57 +00001665 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001666 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1667 llvm::Value *value = CGF.Builder.CreateLoad(field);
1668
1669 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1670 }
1671
Craig Topper4f12f102014-03-12 06:41:41 +00001672 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001673 id.AddInteger(Flags.getBitMask());
1674 }
1675};
1676
John McCall31168b02011-06-15 23:02:42 +00001677/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001678class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001679public:
John McCall7f416cc2015-09-08 08:05:57 +00001680 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001681
John McCall7f416cc2015-09-08 08:05:57 +00001682 void emitCopy(CodeGenFunction &CGF, Address destField,
1683 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001684 CGF.EmitARCMoveWeak(destField, srcField);
1685 }
1686
John McCall7f416cc2015-09-08 08:05:57 +00001687 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001688 CGF.EmitARCDestroyWeak(field);
1689 }
1690
Craig Topper4f12f102014-03-12 06:41:41 +00001691 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001692 // 0 is distinguishable from all pointers and byref flags
1693 id.AddInteger(0);
1694 }
1695};
1696
1697/// Emits the copy/dispose helpers for an ARC __block __strong variable
1698/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001699class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001700public:
John McCall7f416cc2015-09-08 08:05:57 +00001701 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001702
John McCall7f416cc2015-09-08 08:05:57 +00001703 void emitCopy(CodeGenFunction &CGF, Address destField,
1704 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001705 // Do a "move" by copying the value and then zeroing out the old
1706 // variable.
1707
John McCall7f416cc2015-09-08 08:05:57 +00001708 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001709
John McCall31168b02011-06-15 23:02:42 +00001710 llvm::Value *null =
1711 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001712
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001713 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001714 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001715 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1716 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1717 return;
1718 }
John McCall7f416cc2015-09-08 08:05:57 +00001719 CGF.Builder.CreateStore(value, destField);
1720 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001721 }
1722
John McCall7f416cc2015-09-08 08:05:57 +00001723 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001724 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001725 }
1726
Craig Topper4f12f102014-03-12 06:41:41 +00001727 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001728 // 1 is distinguishable from all pointers and byref flags
1729 id.AddInteger(1);
1730 }
1731};
1732
John McCall3a237aa2011-11-09 03:17:26 +00001733/// Emits the copy/dispose helpers for an ARC __block __strong
1734/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001735class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001736public:
John McCall7f416cc2015-09-08 08:05:57 +00001737 ARCStrongBlockByrefHelpers(CharUnits alignment)
1738 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001739
John McCall7f416cc2015-09-08 08:05:57 +00001740 void emitCopy(CodeGenFunction &CGF, Address destField,
1741 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001742 // Do the copy with objc_retainBlock; that's all that
1743 // _Block_object_assign would do anyway, and we'd have to pass the
1744 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001745 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001746 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001747 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001748 }
1749
John McCall7f416cc2015-09-08 08:05:57 +00001750 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001751 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001752 }
1753
Craig Topper4f12f102014-03-12 06:41:41 +00001754 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001755 // 2 is distinguishable from all pointers and byref flags
1756 id.AddInteger(2);
1757 }
1758};
1759
John McCallf9b056b2011-03-31 08:03:29 +00001760/// Emits the copy/dispose helpers for a __block variable with a
1761/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001762class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001763 QualType VarType;
1764 const Expr *CopyExpr;
1765
1766public:
1767 CXXByrefHelpers(CharUnits alignment, QualType type,
1768 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001769 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001770
Craig Topper8a13c412014-05-21 05:09:00 +00001771 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001772 void emitCopy(CodeGenFunction &CGF, Address destField,
1773 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001774 if (!CopyExpr) return;
1775 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1776 }
1777
John McCall7f416cc2015-09-08 08:05:57 +00001778 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001779 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1780 CGF.PushDestructorCleanup(VarType, field);
1781 CGF.PopCleanupBlocks(cleanupDepth);
1782 }
1783
Craig Topper4f12f102014-03-12 06:41:41 +00001784 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001785 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1786 }
1787};
1788} // end anonymous namespace
1789
1790static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001791generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1792 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001793 ASTContext &Context = CGF.getContext();
1794
1795 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001796
John McCalla738c252011-03-09 04:27:21 +00001797 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001798 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001799 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001800 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001801
Craig Topper8a13c412014-05-21 05:09:00 +00001802 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001803 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001804 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001805
John McCallc56a8b32016-03-11 04:30:31 +00001806 const CGFunctionInfo &FI =
1807 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001808
John McCall7f416cc2015-09-08 08:05:57 +00001809 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001810
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001811 // FIXME: We'd like to put these into a mergable by content, with
1812 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001813 llvm::Function *Fn =
1814 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001815 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001816
1817 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001818 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001819
John McCallf9b056b2011-03-31 08:03:29 +00001820 FunctionDecl *FD = FunctionDecl::Create(Context,
1821 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001822 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001823 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001824 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001825 false, false);
John McCall31168b02011-06-15 23:02:42 +00001826
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001827 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1828
Adrian Prantl22e66b42014-04-11 01:13:04 +00001829 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001830
John McCall7f416cc2015-09-08 08:05:57 +00001831 if (generator.needsCopy()) {
1832 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001833
John McCallf9b056b2011-03-31 08:03:29 +00001834 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001835 Address destField = CGF.GetAddrOfLocalVar(&dst);
1836 destField = Address(CGF.Builder.CreateLoad(destField),
1837 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001838 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001839 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1840 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001841
John McCallf9b056b2011-03-31 08:03:29 +00001842 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001843 Address srcField = CGF.GetAddrOfLocalVar(&src);
1844 srcField = Address(CGF.Builder.CreateLoad(srcField),
1845 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001846 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001847 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1848 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001849
John McCall7f416cc2015-09-08 08:05:57 +00001850 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001851 }
1852
1853 CGF.FinishFunction();
1854
1855 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001856}
1857
John McCallf9b056b2011-03-31 08:03:29 +00001858/// Build the copy helper for a __block variable.
1859static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001860 const BlockByrefInfo &byrefInfo,
1861 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001862 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001863 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001864}
1865
1866/// Generate code for a __block variable's dispose helper.
1867static llvm::Constant *
1868generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001869 const BlockByrefInfo &byrefInfo,
1870 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001871 ASTContext &Context = CGF.getContext();
1872 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001873
John McCalla738c252011-03-09 04:27:21 +00001874 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001875 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001876 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001877 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCallc56a8b32016-03-11 04:30:31 +00001879 const CGFunctionInfo &FI =
1880 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001881
John McCall7f416cc2015-09-08 08:05:57 +00001882 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001883
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001884 // FIXME: We'd like to put these into a mergable by content, with
1885 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001886 llvm::Function *Fn =
1887 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001888 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001889 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001890
1891 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001892 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001893
John McCallf9b056b2011-03-31 08:03:29 +00001894 FunctionDecl *FD = FunctionDecl::Create(Context,
1895 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001896 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001897 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001898 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001899 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001900
1901 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1902
Adrian Prantl22e66b42014-04-11 01:13:04 +00001903 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001904
John McCall7f416cc2015-09-08 08:05:57 +00001905 if (generator.needsDispose()) {
1906 Address addr = CGF.GetAddrOfLocalVar(&src);
1907 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1908 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1909 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1910 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001911
John McCall7f416cc2015-09-08 08:05:57 +00001912 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001913 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001914
John McCallf9b056b2011-03-31 08:03:29 +00001915 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001916
John McCallf9b056b2011-03-31 08:03:29 +00001917 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001918}
1919
John McCallf9b056b2011-03-31 08:03:29 +00001920/// Build the dispose helper for a __block variable.
1921static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001922 const BlockByrefInfo &byrefInfo,
1923 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001924 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001925 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001926}
1927
John McCallf593b102013-01-22 03:56:22 +00001928/// Lazily build the copy and dispose helpers for a __block variable
1929/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001930template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001931static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1932 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001933 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001934 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001935
1936 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001937 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001938 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1939 if (node) return static_cast<T*>(node);
1940
John McCall7f416cc2015-09-08 08:05:57 +00001941 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1942 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001943
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00001944 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001945 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1946 return copy;
1947}
1948
John McCallf593b102013-01-22 03:56:22 +00001949/// Build the copy and dispose helpers for the given __block variable
1950/// emission. Places the helpers in the global cache. Returns null
1951/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001952BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001953CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001954 const AutoVarEmission &emission) {
1955 const VarDecl &var = *emission.Variable;
1956 QualType type = var.getType();
1957
John McCall7f416cc2015-09-08 08:05:57 +00001958 auto &byrefInfo = getBlockByrefInfo(&var);
1959
1960 // The alignment we care about for the purposes of uniquing byref
1961 // helpers is the alignment of the actual byref value field.
1962 CharUnits valueAlignment =
1963 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001964
John McCallf9b056b2011-03-31 08:03:29 +00001965 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1966 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001967 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001968
David Blaikie92551612015-08-13 23:53:09 +00001969 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001970 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001971 }
1972
John McCall31168b02011-06-15 23:02:42 +00001973 // Otherwise, if we don't have a retainable type, there's nothing to do.
1974 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001975 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001976
1977 Qualifiers qs = type.getQualifiers();
1978
1979 // If we have lifetime, that dominates.
1980 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001981 switch (lifetime) {
1982 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1983
1984 // These are just bits as far as the runtime is concerned.
1985 case Qualifiers::OCL_ExplicitNone:
1986 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001987 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001988
1989 // Tell the runtime that this is ARC __weak, called by the
1990 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001991 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00001992 return ::buildByrefHelpers(CGM, byrefInfo,
1993 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001994
1995 // ARC __strong __block variables need to be retained.
1996 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001997 // Block pointers need to be copied, and there's no direct
1998 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001999 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002000 return ::buildByrefHelpers(CGM, byrefInfo,
2001 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002002
2003 // Otherwise, we transfer ownership of the retain from the stack
2004 // to the heap.
2005 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002006 return ::buildByrefHelpers(CGM, byrefInfo,
2007 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002008 }
2009 }
2010 llvm_unreachable("fell out of lifetime switch!");
2011 }
2012
John McCallf9b056b2011-03-31 08:03:29 +00002013 BlockFieldFlags flags;
2014 if (type->isBlockPointerType()) {
2015 flags |= BLOCK_FIELD_IS_BLOCK;
2016 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2017 type->isObjCObjectPointerType()) {
2018 flags |= BLOCK_FIELD_IS_OBJECT;
2019 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002020 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002021 }
2022
2023 if (type.isObjCGCWeak())
2024 flags |= BLOCK_FIELD_IS_WEAK;
2025
John McCall7f416cc2015-09-08 08:05:57 +00002026 return ::buildByrefHelpers(CGM, byrefInfo,
2027 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002028}
2029
John McCall7f416cc2015-09-08 08:05:57 +00002030Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2031 const VarDecl *var,
2032 bool followForward) {
2033 auto &info = getBlockByrefInfo(var);
2034 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002035}
2036
John McCall7f416cc2015-09-08 08:05:57 +00002037Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2038 const BlockByrefInfo &info,
2039 bool followForward,
2040 const llvm::Twine &name) {
2041 // Chase the forwarding address if requested.
2042 if (followForward) {
2043 Address forwardingAddr =
2044 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2045 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2046 }
2047
2048 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2049 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002050}
2051
John McCall7f416cc2015-09-08 08:05:57 +00002052/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002053/// into:
2054///
2055/// struct {
2056/// void *__isa;
2057/// void *__forwarding;
2058/// int32_t __flags;
2059/// int32_t __size;
2060/// void *__copy_helper; // only if needed
2061/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002062/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002063/// char padding[X]; // only if needed
2064/// T x;
2065/// } x
2066///
John McCall7f416cc2015-09-08 08:05:57 +00002067const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2068 auto it = BlockByrefInfos.find(D);
2069 if (it != BlockByrefInfos.end())
2070 return it->second;
John McCall73064872011-03-31 01:59:53 +00002071
John McCall7f416cc2015-09-08 08:05:57 +00002072 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002073 llvm::StructType::create(getLLVMContext(),
2074 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002075
John McCall7f416cc2015-09-08 08:05:57 +00002076 QualType Ty = D->getType();
2077
2078 CharUnits size;
2079 SmallVector<llvm::Type *, 8> types;
2080
John McCall73064872011-03-31 01:59:53 +00002081 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002082 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002083 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002084
2085 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002086 types.push_back(llvm::PointerType::getUnqual(byrefType));
2087 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002088
2089 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002090 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002091 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002092
2093 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002094 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002095 size += CharUnits::fromQuantity(4);
2096
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002097 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002098 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2099 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002100 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002101 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002102 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002103
2104 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002105 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002106 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002107 }
John McCall7f416cc2015-09-08 08:05:57 +00002108
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002109 bool HasByrefExtendedLayout = false;
2110 Qualifiers::ObjCLifetime Lifetime;
2111 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002112 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002113 /// void *__byref_variable_layout;
2114 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002115 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002116 }
2117
2118 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002119 llvm::Type *varTy = ConvertTypeForMem(Ty);
2120
2121 bool packed = false;
2122 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002123 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002124
2125 // We may have to insert padding.
2126 if (varOffset != size) {
2127 llvm::Type *paddingTy =
2128 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2129
2130 types.push_back(paddingTy);
2131 size = varOffset;
2132
2133 // Conversely, we might have to prevent LLVM from inserting padding.
2134 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2135 > varAlign.getQuantity()) {
2136 packed = true;
2137 }
2138 types.push_back(varTy);
2139
2140 byrefType->setBody(types, packed);
2141
2142 BlockByrefInfo info;
2143 info.Type = byrefType;
2144 info.FieldIndex = types.size() - 1;
2145 info.FieldOffset = varOffset;
2146 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2147
2148 auto pair = BlockByrefInfos.insert({D, info});
2149 assert(pair.second && "info was inserted recursively?");
2150 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002151}
2152
2153/// Initialize the structural components of a __block variable, i.e.
2154/// everything but the actual object.
2155void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002156 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002157 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002158
John McCallf9b056b2011-03-31 08:03:29 +00002159 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002160 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002161 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2162
2163 unsigned nextHeaderIndex = 0;
2164 CharUnits nextHeaderOffset;
2165 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2166 const Twine &name) {
2167 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2168 nextHeaderOffset, name);
2169 Builder.CreateStore(value, fieldAddr);
2170
2171 nextHeaderIndex++;
2172 nextHeaderOffset += fieldSize;
2173 };
John McCallf9b056b2011-03-31 08:03:29 +00002174
2175 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002176 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002177
2178 const VarDecl &D = *emission.Variable;
2179 QualType type = D.getType();
2180
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002181 bool HasByrefExtendedLayout;
2182 Qualifiers::ObjCLifetime ByrefLifetime;
2183 bool ByRefHasLifetime =
2184 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002185
John McCallf9b056b2011-03-31 08:03:29 +00002186 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002187
2188 // Initialize the 'isa', which is just 0 or 1.
2189 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002190 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002191 isa = 1;
2192 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002193 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002194
2195 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002196 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002197
2198 // Blocks ABI:
2199 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002200 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002201 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002202 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2203 if (ByRefHasLifetime) {
2204 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2205 else switch (ByrefLifetime) {
2206 case Qualifiers::OCL_Strong:
2207 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2208 break;
2209 case Qualifiers::OCL_Weak:
2210 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2211 break;
2212 case Qualifiers::OCL_ExplicitNone:
2213 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2214 break;
2215 case Qualifiers::OCL_None:
2216 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2217 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2218 break;
2219 default:
2220 break;
2221 }
2222 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2223 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2224 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2225 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2226 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2227 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2228 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2229 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2230 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2231 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2232 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2233 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2234 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2235 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2236 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2237 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2238 }
2239 printf("\n");
2240 }
2241 }
John McCall7f416cc2015-09-08 08:05:57 +00002242 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2243 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002244
John McCallf9b056b2011-03-31 08:03:29 +00002245 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2246 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002247 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002248
John McCallf9b056b2011-03-31 08:03:29 +00002249 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002250 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2251 "byref.copyHelper");
2252 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2253 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002254 }
John McCall7f416cc2015-09-08 08:05:57 +00002255
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002256 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002257 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2258 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002259 }
John McCall73064872011-03-31 01:59:53 +00002260}
2261
John McCallad7c5c12011-02-08 08:22:06 +00002262void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002263 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002264 llvm::Value *args[] = {
2265 Builder.CreateBitCast(V, Int8PtrTy),
2266 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2267 };
2268 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002269}
John McCall73064872011-03-31 01:59:53 +00002270
2271namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002272 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002273 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002274 llvm::Value *Addr;
2275 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2276
Craig Topper4f12f102014-03-12 06:41:41 +00002277 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002278 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002279 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2280 }
2281 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002282} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002283
2284/// Enter a cleanup to destroy a __block variable. Note that this
2285/// cleanup should be a no-op if the variable hasn't left the stack
2286/// yet; if a cleanup is required for the variable itself, that needs
2287/// to be done externally.
2288void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2289 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002290 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002291 return;
2292
John McCall7f416cc2015-09-08 08:05:57 +00002293 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2294 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002295}
John McCall7959fee2011-09-09 20:41:01 +00002296
2297/// Adjust the declaration of something from the blocks API.
2298static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2299 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002300 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002301
2302 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2303 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2304 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2305 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2306
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002307 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2308 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2309 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002310
2311 const NamedDecl *ND = nullptr;
2312 for (const auto &Result : DC->lookup(&II))
2313 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2314 (ND = dyn_cast<VarDecl>(Result)))
2315 break;
2316
2317 // TODO: support static blocks runtime
2318 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2319 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2320 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2321 } else {
2322 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2323 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2324 }
2325 }
2326
2327 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2328 return;
2329
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002330 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002331 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2332}
2333
2334llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2335 if (BlockObjectDispose)
2336 return BlockObjectDispose;
2337
2338 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2339 llvm::FunctionType *fty
2340 = llvm::FunctionType::get(VoidTy, args, false);
2341 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2342 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2343 return BlockObjectDispose;
2344}
2345
2346llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2347 if (BlockObjectAssign)
2348 return BlockObjectAssign;
2349
2350 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2351 llvm::FunctionType *fty
2352 = llvm::FunctionType::get(VoidTy, args, false);
2353 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2354 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2355 return BlockObjectAssign;
2356}
2357
2358llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2359 if (NSConcreteGlobalBlock)
2360 return NSConcreteGlobalBlock;
2361
2362 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002363 Int8PtrTy->getPointerTo(),
2364 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002365 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2366 return NSConcreteGlobalBlock;
2367}
2368
2369llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2370 if (NSConcreteStackBlock)
2371 return NSConcreteStackBlock;
2372
2373 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002374 Int8PtrTy->getPointerTo(),
2375 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002376 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002377 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002378}