blob: c4c5541e6a55d3b12c01a11c900a231ffc8fa9f8 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000021#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000022#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000023#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000024#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000029#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000030
Anders Carlsson2437cbf2009-02-12 00:39:25 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall08ef4662011-11-10 08:15:53 +000034CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
35 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000036 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000037 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000038 DominatingIP(nullptr) {
39
John McCall08ef4662011-11-10 08:15:53 +000040 // Skip asm prefix, if any. 'name' is usually taken directly from
41 // the mangled name of the enclosing function.
42 if (!name.empty() && name[0] == '\01')
43 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000044}
45
John McCallf9b056b2011-03-31 08:03:29 +000046// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000047BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000048
John McCall351762c2011-02-07 10:33:21 +000049/// Build the given block as a global block.
50static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo,
52 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000053
John McCall351762c2011-02-07 10:33:21 +000054/// Build the helper function to copy a block.
55static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
58}
59
Alp Tokerf6a24ce2013-12-05 16:25:25 +000060/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000061static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
62 const CGBlockInfo &blockInfo) {
63 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
64}
65
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000066/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
67/// buildBlockDescriptor is accessed from 5th field of the Block_literal
68/// meta-data and contains stationary information about the block literal.
69/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000070/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000071/// struct Block_descriptor {
72/// unsigned long reserved;
73/// unsigned long size; // size of Block_literal metadata in bytes.
74/// void *copy_func_helper_decl; // optional copy helper.
75/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000077/// void *block_layout_info; // encoding of captured block variables.
78/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000079/// \endcode
John McCall351762c2011-02-07 10:33:21 +000080static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
81 const CGBlockInfo &blockInfo) {
82 ASTContext &C = CGM.getContext();
83
John McCall6c9f1fdb2016-11-19 08:17:24 +000084 llvm::IntegerType *ulong =
85 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
86 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000087 if (CGM.getLangOpts().OpenCL)
88 i8p =
89 llvm::Type::getInt8PtrTy(
90 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
91 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000092 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000093
John McCall23c9dc62016-11-28 22:18:27 +000094 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000098 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000099
100 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000101 // FIXME: What is the right way to say this doesn't fit? We should give
102 // a user diagnostic in that case. Better fix would be to change the
103 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000104 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000105
John McCall351762c2011-02-07 10:33:21 +0000106 // Optional copy/dispose helpers.
107 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000108 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110
111 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000112 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000113 }
114
John McCall351762c2011-02-07 10:33:21 +0000115 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
116 std::string typeAtEncoding =
117 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000118 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000119 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000120
John McCall351762c2011-02-07 10:33:21 +0000121 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 if (C.getLangOpts().ObjC1) {
123 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000124 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000127 }
John McCall351762c2011-02-07 10:33:21 +0000128 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000129 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000130
Joey Goulyddbda402016-08-10 15:57:02 +0000131 unsigned AddrSpace = 0;
132 if (C.getLangOpts().OpenCL)
133 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000134
John McCall351762c2011-02-07 10:33:21 +0000135 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000136 elements.finishAndCreateGlobal("__block_descriptor_tmp",
137 CGM.getPointerAlign(),
138 /*constant*/ true,
139 llvm::GlobalValue::InternalLinkage,
140 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000141
John McCall351762c2011-02-07 10:33:21 +0000142 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000143}
144
John McCall351762c2011-02-07 10:33:21 +0000145/*
146 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000147
John McCall351762c2011-02-07 10:33:21 +0000148 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
149 struct Block_literal {
150 /// Initialized to one of:
151 /// extern void *_NSConcreteStackBlock[];
152 /// extern void *_NSConcreteGlobalBlock[];
153 ///
154 /// In theory, we could start one off malloc'ed by setting
155 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
156 /// this isa:
157 /// extern void *_NSConcreteMallocBlock[];
158 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000159
John McCall351762c2011-02-07 10:33:21 +0000160 /// These are the flags (with corresponding bit number) that the
161 /// compiler is actually supposed to know about.
162 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
163 /// descriptor provides copy and dispose helper functions
164 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
165 /// object with a nontrivial destructor or copy constructor
166 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
167 /// as global memory
168 /// 29. BLOCK_USE_STRET - indicates that the block function
169 /// uses stret, which objc_msgSend needs to know about
170 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
171 /// @encoded signature string
172 /// And we're not supposed to manipulate these:
173 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
174 /// to malloc'ed memory
175 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
176 /// to GC-allocated memory
177 /// Additionally, the bottom 16 bits are a reference count which
178 /// should be zero on the stack.
179 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Reserved; should be zero-initialized.
182 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Function pointer generated from block literal.
185 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Block description metadata generated from block literal.
188 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000189
John McCall351762c2011-02-07 10:33:21 +0000190 /// Captured values follow.
191 _CapturesTypes captures...;
192 };
193 */
David Chisnall950a9512009-11-17 19:33:30 +0000194
John McCall351762c2011-02-07 10:33:21 +0000195namespace {
196 /// A chunk of data that we actually have to capture in the block.
197 struct BlockLayoutChunk {
198 CharUnits Alignment;
199 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000200 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000201 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000202 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000203 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000206 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000207 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000208 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000209 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000210 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000211
John McCall351762c2011-02-07 10:33:21 +0000212 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000213 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
214 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000215 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000216 info.CXXThisOffset = offset;
217 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000218 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
219 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000220 }
John McCall87fe5d52010-05-20 01:18:31 +0000221 }
John McCall351762c2011-02-07 10:33:21 +0000222 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000223
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000224 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
225 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000226 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000227 if (left.Alignment != right.Alignment)
228 return left.Alignment > right.Alignment;
229
230 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000231 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000232 return 1;
233 if (chunk.Lifetime == Qualifiers::OCL_Strong)
234 return 0;
235 if (chunk.Lifetime == Qualifiers::OCL_Weak)
236 return 2;
237 return 3;
238 };
239
240 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000241 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000242} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000243
John McCallb0a3ecb2011-02-08 03:07:00 +0000244/// Determines if the given type is safe for constant capture in C++.
245static bool isSafeForCXXConstantCapture(QualType type) {
246 const RecordType *recordType =
247 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
248
249 // Only records can be unsafe.
250 if (!recordType) return true;
251
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000252 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000253
254 // Maintain semantics for classes with non-trivial dtors or copy ctors.
255 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000256 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000257
258 // Otherwise, we just have to make sure there aren't any mutable
259 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000260 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000261}
262
John McCall351762c2011-02-07 10:33:21 +0000263/// It is illegal to modify a const object after initialization.
264/// Therefore, if a const object has a constant initializer, we don't
265/// actually need to keep storage for it in the block; we'll just
266/// rematerialize it at the start of the block function. This is
267/// acceptable because we make no promises about address stability of
268/// captured variables.
269static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000270 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000271 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000272 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000273 // rematerialize default arguments of function parameters.
274 if (isa<ParmVarDecl>(var))
275 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000276
John McCall351762c2011-02-07 10:33:21 +0000277 QualType type = var->getType();
278
279 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000280 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000281
John McCallb0a3ecb2011-02-08 03:07:00 +0000282 // Furthermore, in C++ we have to worry about mutable fields:
283 // C++ [dcl.type.cv]p4:
284 // Except that any class member declared mutable can be
285 // modified, any attempt to modify a const object during its
286 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000288 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000289
290 // If the variable doesn't have any initializer (shouldn't this be
291 // invalid?), it's not clear what we should do. Maybe capture as
292 // zero?
293 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000294 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000295
John McCallde0fe072017-08-15 21:42:52 +0000296 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000297}
298
299/// Get the low bit of a nonzero character count. This is the
300/// alignment of the nth byte if the 0th byte is universally aligned.
301static CharUnits getLowBit(CharUnits v) {
302 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
303}
304
305static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000307
308 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000309 if (CGM.getLangOpts().OpenCL) {
310 // The header is basically 'struct { int; int; generic void *;
311 // custom_fields; }'. Assert that struct is packed.
312 auto GenPtrAlign = CharUnits::fromQuantity(
313 CGM.getTarget().getPointerAlign(LangAS::opencl_generic) / 8);
314 auto GenPtrSize = CharUnits::fromQuantity(
315 CGM.getTarget().getPointerWidth(LangAS::opencl_generic) / 8);
316 assert(CGM.getIntSize() <= GenPtrSize);
317 assert(CGM.getIntAlign() <= GenPtrAlign);
318 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
319 elementTypes.push_back(CGM.IntTy); /* total size */
320 elementTypes.push_back(CGM.IntTy); /* align */
321 elementTypes.push_back(
322 CGM.getOpenCLRuntime()
323 .getGenericVoidPointerType()); /* invoke function */
324 unsigned Offset =
325 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
326 unsigned BlockAlign = GenPtrAlign.getQuantity();
327 if (auto *Helper =
328 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
329 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
330 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
331 // If necessary, add padding fields to the custom fields.
332 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
333 if (BlockAlign < Align)
334 BlockAlign = Align;
335 assert(Offset % Align == 0);
336 Offset += CGM.getDataLayout().getTypeAllocSize(I);
337 elementTypes.push_back(I);
338 }
339 }
340 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
341 info.BlockSize = CharUnits::fromQuantity(Offset);
342 } else {
343 // The header is basically 'struct { void *; int; int; void *; void *; }'.
344 // Assert that that struct is packed.
345 assert(CGM.getIntSize() <= CGM.getPointerSize());
346 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
347 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
348 info.BlockAlign = CGM.getPointerAlign();
349 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
350 elementTypes.push_back(CGM.VoidPtrTy);
351 elementTypes.push_back(CGM.IntTy);
352 elementTypes.push_back(CGM.IntTy);
353 elementTypes.push_back(CGM.VoidPtrTy);
354 elementTypes.push_back(CGM.getBlockDescriptorType());
355 }
John McCall351762c2011-02-07 10:33:21 +0000356}
357
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000358static QualType getCaptureFieldType(const CodeGenFunction &CGF,
359 const BlockDecl::Capture &CI) {
360 const VarDecl *VD = CI.getVariable();
361
362 // If the variable is captured by an enclosing block or lambda expression,
363 // use the type of the capture field.
364 if (CGF.BlockInfo && CI.isNested())
365 return CGF.BlockInfo->getCapture(VD).fieldType();
366 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
367 return FD->getType();
368 return VD->getType();
369}
370
John McCall351762c2011-02-07 10:33:21 +0000371/// Compute the layout of the given block. Attempts to lay the block
372/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000373static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
374 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000375 ASTContext &C = CGM.getContext();
376 const BlockDecl *block = info.getBlockDecl();
377
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000378 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000379 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000380 bool hasNonConstantCustomFields = false;
381 if (auto *OpenCLHelper =
382 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
383 hasNonConstantCustomFields =
384 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
385 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000386 info.StructureType =
387 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
388 info.CanBeGlobal = true;
389 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000390 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000391 else if (C.getLangOpts().ObjC1 &&
392 CGM.getLangOpts().getGC() == LangOptions::NonGC)
393 info.HasCapturedVariableLayout = true;
394
John McCall351762c2011-02-07 10:33:21 +0000395 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000396 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000397 layout.reserve(block->capturesCXXThis() +
398 (block->capture_end() - block->capture_begin()));
399
400 CharUnits maxFieldAlign;
401
402 // First, 'this'.
403 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000404 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
405 "Can't capture 'this' outside a method");
406 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000407
John McCall7f416cc2015-09-08 08:05:57 +0000408 // Theoretically, this could be in a different address space, so
409 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000410 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000411 std::pair<CharUnits,CharUnits> tinfo
412 = CGM.getContext().getTypeInfoInChars(thisType);
413 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
414
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000415 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
416 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000417 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000418 }
419
420 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000421 for (const auto &CI : block->captures()) {
422 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000423
Aaron Ballman9371dd22014-03-14 18:34:04 +0000424 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000425 // We have to copy/dispose of the __block reference.
426 info.NeedsCopyDispose = true;
427
John McCall351762c2011-02-07 10:33:21 +0000428 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000429 CharUnits align = CGM.getPointerAlign();
430 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000431
John McCall7f416cc2015-09-08 08:05:57 +0000432 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
433 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000434 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000435 continue;
436 }
437
438 // Otherwise, build a layout chunk with the size and alignment of
439 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000440 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000441 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
442 continue;
443 }
444
John McCall31168b02011-06-15 23:02:42 +0000445 // If we have a lifetime qualifier, honor it for capture purposes.
446 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000447 Qualifiers::ObjCLifetime lifetime =
448 variable->getType().getObjCLifetime();
449 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000450 switch (lifetime) {
451 case Qualifiers::OCL_None: llvm_unreachable("impossible");
452 case Qualifiers::OCL_ExplicitNone:
453 case Qualifiers::OCL_Autoreleasing:
454 break;
John McCall351762c2011-02-07 10:33:21 +0000455
John McCall31168b02011-06-15 23:02:42 +0000456 case Qualifiers::OCL_Strong:
457 case Qualifiers::OCL_Weak:
458 info.NeedsCopyDispose = true;
459 }
460
461 // Block pointers require copy/dispose. So do Objective-C pointers.
462 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000463 // But honor the inert __unsafe_unretained qualifier, which doesn't
464 // actually make it into the type system.
465 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
466 lifetime = Qualifiers::OCL_ExplicitNone;
467 } else {
468 info.NeedsCopyDispose = true;
469 // used for mrr below.
470 lifetime = Qualifiers::OCL_Strong;
471 }
John McCall351762c2011-02-07 10:33:21 +0000472
473 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000474 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000475 info.NeedsCopyDispose = true;
476 info.HasCXXObject = true;
477
478 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000479 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000480 if (const CXXRecordDecl *record =
481 variable->getType()->getAsCXXRecordDecl()) {
482 if (!record->hasTrivialDestructor()) {
483 info.HasCXXObject = true;
484 info.NeedsCopyDispose = true;
485 }
486 }
487 }
488
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000489 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000490 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000491 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000492
John McCall351762c2011-02-07 10:33:21 +0000493 maxFieldAlign = std::max(maxFieldAlign, align);
494
Jay Foad7c57be32011-07-11 09:56:20 +0000495 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000496 CGM.getTypes().ConvertTypeForMem(VT);
497
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000498 layout.push_back(
499 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000500 }
501
502 // If that was everything, we're done here.
503 if (layout.empty()) {
504 info.StructureType =
505 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
506 info.CanBeGlobal = true;
507 return;
508 }
509
510 // Sort the layout by alignment. We have to use a stable sort here
511 // to get reproducible results. There should probably be an
512 // llvm::array_pod_stable_sort.
513 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000514
515 // Needed for blocks layout info.
516 info.BlockHeaderForcedGapOffset = info.BlockSize;
517 info.BlockHeaderForcedGapSize = CharUnits::Zero();
518
John McCall351762c2011-02-07 10:33:21 +0000519 CharUnits &blockSize = info.BlockSize;
520 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
521
522 // Assuming that the first byte in the header is maximally aligned,
523 // get the alignment of the first byte following the header.
524 CharUnits endAlign = getLowBit(blockSize);
525
526 // If the end of the header isn't satisfactorily aligned for the
527 // maximum thing, look for things that are okay with the header-end
528 // alignment, and keep appending them until we get something that's
529 // aligned right. This algorithm is only guaranteed optimal if
530 // that condition is satisfied at some point; otherwise we can get
531 // things like:
532 // header // next byte has alignment 4
533 // something_with_size_5; // next byte has alignment 1
534 // something_with_alignment_8;
535 // which has 7 bytes of padding, as opposed to the naive solution
536 // which might have less (?).
537 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000538 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000539 li = layout.begin() + 1, le = layout.end();
540
541 // Look for something that the header end is already
542 // satisfactorily aligned for.
543 for (; li != le && endAlign < li->Alignment; ++li)
544 ;
545
546 // If we found something that's naturally aligned for the end of
547 // the header, keep adding things...
548 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000549 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000550 for (; li != le; ++li) {
551 assert(endAlign >= li->Alignment);
552
John McCall7f416cc2015-09-08 08:05:57 +0000553 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000554 elementTypes.push_back(li->Type);
555 blockSize += li->Size;
556 endAlign = getLowBit(blockSize);
557
558 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000559 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000560 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000561 }
John McCall351762c2011-02-07 10:33:21 +0000562 }
John McCall351762c2011-02-07 10:33:21 +0000563 // Don't re-append everything we just appended.
564 layout.erase(first, li);
565 }
566 }
567
John McCallac0350a2012-04-26 21:14:42 +0000568 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000569
John McCall351762c2011-02-07 10:33:21 +0000570 // At this point, we just have to add padding if the end align still
571 // isn't aligned right.
572 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000573 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000574 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000575
John McCall7f416cc2015-09-08 08:05:57 +0000576 // If we haven't yet added any fields, remember that there was an
577 // initial gap; this need to go into the block layout bit map.
578 if (blockSize == info.BlockHeaderForcedGapOffset) {
579 info.BlockHeaderForcedGapSize = padding;
580 }
581
John McCalle3dc1702011-02-15 09:22:45 +0000582 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
583 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000584 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000585 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000586 }
587
John McCall1db0a2f2012-05-01 20:28:00 +0000588 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000589 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000590 // Slam everything else on now. This works because they have
591 // strictly decreasing alignment and we expect that size is always a
592 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000593 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000594 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000595 if (endAlign < li->Alignment) {
596 // size may not be multiple of alignment. This can only happen with
597 // an over-aligned variable. We will be adding a padding field to
598 // make the size be multiple of alignment.
599 CharUnits padding = li->Alignment - endAlign;
600 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
601 padding.getQuantity()));
602 blockSize += padding;
603 endAlign = getLowBit(blockSize);
604 }
John McCall351762c2011-02-07 10:33:21 +0000605 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000606 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000607 elementTypes.push_back(li->Type);
608 blockSize += li->Size;
609 endAlign = getLowBit(blockSize);
610 }
611
612 info.StructureType =
613 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
614}
615
John McCall08ef4662011-11-10 08:15:53 +0000616/// Enter the scope of a block. This should be run at the entrance to
617/// a full-expression so that the block's cleanups are pushed at the
618/// right place in the stack.
619static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000620 assert(CGF.HaveInsertPoint());
621
John McCall08ef4662011-11-10 08:15:53 +0000622 // Allocate the block info and place it at the head of the list.
623 CGBlockInfo &blockInfo =
624 *new CGBlockInfo(block, CGF.CurFn->getName());
625 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
626 CGF.FirstBlockInfo = &blockInfo;
627
628 // Compute information about the layout, etc., of this block,
629 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000630 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000631
632 // Nothing else to do if it can be global.
633 if (blockInfo.CanBeGlobal) return;
634
635 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000636 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
637 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000638
639 // If there are cleanups to emit, enter them (but inactive).
640 if (!blockInfo.NeedsCopyDispose) return;
641
642 // Walk through the captures (in order) and find the ones not
643 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000644 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000645 // Ignore __block captures; there's nothing special in the
646 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000647 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000648
649 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000650 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000651 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
652 if (capture.isConstant()) continue;
653
654 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000655 QualType VT = getCaptureFieldType(CGF, CI);
656 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000657 if (dtorKind == QualType::DK_none) continue;
658
659 CodeGenFunction::Destroyer *destroyer;
660
661 // Block captures count as local values and have imprecise semantics.
662 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000663 //
664 // For const-qualified captures, emit clang.arc.use to ensure the captured
665 // object doesn't get released while we are still depending on its validity
666 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000667 if (VT.isConstQualified() &&
668 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
669 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
670 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
671 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000672 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000673 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000674 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000675 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000676 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000677 }
678
679 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000680 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
681 capture.getIndex(),
682 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000683
John McCallf4beacd2011-11-10 10:43:54 +0000684 // We can use that GEP as the dominating IP.
685 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000686 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000687
John McCall08ef4662011-11-10 08:15:53 +0000688 CleanupKind cleanupKind = InactiveNormalCleanup;
689 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
690 if (useArrayEHCleanup)
691 cleanupKind = InactiveNormalAndEHCleanup;
692
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000693 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000694 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000695
696 // Remember where that cleanup was.
697 capture.setCleanup(CGF.EHStack.stable_begin());
698 }
699}
700
701/// Enter a full-expression with a non-trivial number of objects to
702/// clean up. This is in this file because, at the moment, the only
703/// kind of cleanup object is a BlockDecl*.
704void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
705 assert(E->getNumObjects() != 0);
706 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
707 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
708 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
709 enterBlockScope(*this, *i);
710 }
711}
712
713/// Find the layout for the given block in a linked list and remove it.
714static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
715 const BlockDecl *block) {
716 while (true) {
717 assert(head && *head);
718 CGBlockInfo *cur = *head;
719
720 // If this is the block we're looking for, splice it out of the list.
721 if (cur->getBlockDecl() == block) {
722 *head = cur->NextBlockInfo;
723 return cur;
724 }
725
726 head = &cur->NextBlockInfo;
727 }
728}
729
730/// Destroy a chain of block layouts.
731void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
732 assert(head && "destroying an empty chain");
733 do {
734 CGBlockInfo *cur = head;
735 head = cur->NextBlockInfo;
736 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000737 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000738}
739
John McCall351762c2011-02-07 10:33:21 +0000740/// Emit a block literal expression in the current function.
741llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000742 // If the block has no captures, we won't have a pre-computed
743 // layout for it.
744 if (!blockExpr->getBlockDecl()->hasCaptures()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000745 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
746 return Block;
John McCall08ef4662011-11-10 08:15:53 +0000747 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000748 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000749 blockInfo.BlockExpression = blockExpr;
750 return EmitBlockLiteral(blockInfo);
751 }
John McCall351762c2011-02-07 10:33:21 +0000752
John McCall08ef4662011-11-10 08:15:53 +0000753 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000754 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000755 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
756 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000757
John McCall08ef4662011-11-10 08:15:53 +0000758 blockInfo->BlockExpression = blockExpr;
759 return EmitBlockLiteral(*blockInfo);
760}
761
762llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000763 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
764 auto GenVoidPtrTy =
765 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
766 unsigned GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
767 auto GenVoidPtrSize = CharUnits::fromQuantity(
768 CGM.getTarget().getPointerWidth(GenVoidPtrAddr) / 8);
John McCall08ef4662011-11-10 08:15:53 +0000769 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000770 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Yaxun Liu10712d92017-10-04 20:32:17 +0000771 llvm::Constant *blockFn = CodeGenFunction(CGM, true).GenerateBlockFunction(
772 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
773 blockFn = llvm::ConstantExpr::getPointerCast(blockFn, GenVoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000774
775 // If there is nothing to capture, we can emit this as a global block.
776 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000777 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000778
779 // Otherwise, we have to emit this as a local block.
780
John McCall7f416cc2015-09-08 08:05:57 +0000781 Address blockAddr = blockInfo.LocalAddress;
782 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000783
Yaxun Liu10712d92017-10-04 20:32:17 +0000784 llvm::Constant *isa;
785 llvm::Constant *descriptor;
786 BlockFlags flags;
787 if (!IsOpenCL) {
788 isa = llvm::ConstantExpr::getBitCast(CGM.getNSConcreteStackBlock(),
789 VoidPtrTy);
790
791 // Build the block descriptor.
792 descriptor = buildBlockDescriptor(CGM, blockInfo);
793
794 // Compute the initial on-stack block flags.
795 flags = BLOCK_HAS_SIGNATURE;
796 if (blockInfo.HasCapturedVariableLayout)
797 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
798 if (blockInfo.NeedsCopyDispose)
799 flags |= BLOCK_HAS_COPY_DISPOSE;
800 if (blockInfo.HasCXXObject)
801 flags |= BLOCK_HAS_CXX_OBJ;
802 if (blockInfo.UsesStret)
803 flags |= BLOCK_USE_STRET;
804 }
John McCall351762c2011-02-07 10:33:21 +0000805
John McCall7f416cc2015-09-08 08:05:57 +0000806 auto projectField =
807 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
808 return Builder.CreateStructGEP(blockAddr, index, offset, name);
809 };
810 auto storeField =
811 [&](llvm::Value *value, unsigned index, CharUnits offset,
812 const Twine &name) {
813 Builder.CreateStore(value, projectField(index, offset, name));
814 };
815
816 // Initialize the block header.
817 {
818 // We assume all the header fields are densely packed.
819 unsigned index = 0;
820 CharUnits offset;
821 auto addHeaderField =
822 [&](llvm::Value *value, CharUnits size, const Twine &name) {
823 storeField(value, index, offset, name);
824 offset += size;
825 index++;
826 };
827
Yaxun Liu10712d92017-10-04 20:32:17 +0000828 if (!IsOpenCL) {
829 addHeaderField(isa, getPointerSize(), "block.isa");
830 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
831 getIntSize(), "block.flags");
832 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
833 "block.reserved");
834 } else {
835 addHeaderField(
836 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
837 getIntSize(), "block.size");
838 addHeaderField(
839 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
840 getIntSize(), "block.align");
841 }
842 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
843 if (!IsOpenCL)
844 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
845 else if (auto *Helper =
846 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
847 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
848 addHeaderField(
849 I.first,
850 CharUnits::fromQuantity(
851 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
852 I.second);
853 }
854 }
John McCall7f416cc2015-09-08 08:05:57 +0000855 }
John McCall351762c2011-02-07 10:33:21 +0000856
857 // Finally, capture all the values into the block.
858 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
859
860 // First, 'this'.
861 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000862 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
863 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000864 Builder.CreateStore(LoadCXXThis(), addr);
865 }
866
867 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000868 for (const auto &CI : blockDecl->captures()) {
869 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000870 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
871
872 // Ignore constant captures.
873 if (capture.isConstant()) continue;
874
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000875 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000876
877 // This will be a [[type]]*, except that a byref entry will just be
878 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000879 Address blockField =
880 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000881
882 // Compute the address of the thing we're going to move into the
883 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000884 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000885
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000886 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000887 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000888 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000889 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000890 } else if (CI.isByRef()) {
891 if (BlockInfo && CI.isNested()) {
892 // We need to use the capture from the enclosing block.
893 const CGBlockInfo::Capture &enclosingCapture =
894 BlockInfo->getCapture(variable);
895
896 // This is a [[type]]*, except that a byref entry wil just be an i8**.
897 src = Builder.CreateStructGEP(LoadBlockStruct(),
898 enclosingCapture.getIndex(),
899 enclosingCapture.getOffset(),
900 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000901 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000902 auto I = LocalDeclMap.find(variable);
903 assert(I != LocalDeclMap.end());
904 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000905 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000906 } else {
907 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
908 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
909 type.getNonReferenceType(), VK_LValue,
910 SourceLocation());
911 src = EmitDeclRefLValue(&declRef).getAddress();
912 };
John McCall351762c2011-02-07 10:33:21 +0000913
914 // For byrefs, we just write the pointer to the byref struct into
915 // the block field. There's no need to chase the forwarding
916 // pointer at this point, since we're building something that will
917 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000918 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000919 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000920 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000921 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000922 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000923 else
John McCall7f416cc2015-09-08 08:05:57 +0000924 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000925
John McCalle3dc1702011-02-15 09:22:45 +0000926 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000927 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000928
929 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000930 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000931 if (blockDecl->isConversionFromLambda()) {
932 // If we have a lambda conversion, emit the expression
933 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000934 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000935 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000936 AggValueSlot::IsDestructed,
937 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000938 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000939 EmitAggExpr(copyExpr, Slot);
940 } else {
941 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
942 }
John McCall351762c2011-02-07 10:33:21 +0000943
944 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000945 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000946 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000947
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000948 // If type is const-qualified, copy the value into the block field.
949 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000950 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
951 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000952 llvm::Value *value = Builder.CreateLoad(src, "captured");
953 Builder.CreateStore(value, blockField);
954
John McCall4d14a902013-04-08 23:27:49 +0000955 // If this is an ARC __strong block-pointer variable, don't do a
956 // block copy.
957 //
958 // TODO: this can be generalized into the normal initialization logic:
959 // we should never need to do a block-copy when initializing a local
960 // variable, because the local variable's lifetime should be strictly
961 // contained within the stack block's.
962 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
963 type->isBlockPointerType()) {
964 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000965 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000966 value = EmitARCRetainNonBlock(value);
967
968 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000969 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000970
971 // Otherwise, fake up a POD copy into the block field.
972 } else {
John McCall31168b02011-06-15 23:02:42 +0000973 // Fake up a new variable so that EmitScalarInit doesn't think
974 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000975 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
976 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000977
John McCall93be3f72011-02-07 18:37:40 +0000978 // We use one of these or the other depending on whether the
979 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000980 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
981 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
982 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000983
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000984 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000985 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000986 // FIXME: Pass a specific location for the expr init so that the store is
987 // attributed to a reasonable location - otherwise it may be attributed to
988 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +0000989 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000990 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000991 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000992 }
993
John McCall08ef4662011-11-10 08:15:53 +0000994 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000995 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000996 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
997 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000998 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000999 }
John McCall351762c2011-02-07 10:33:21 +00001000 }
1001
1002 // Cast to the converted block-pointer type, which happens (somewhat
1003 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001004 llvm::Value *result = Builder.CreatePointerCast(
1005 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001006
John McCall351762c2011-02-07 10:33:21 +00001007 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001008}
1009
1010
Chris Lattnera5f58b02011-07-09 17:41:47 +00001011llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001012 if (BlockDescriptorType)
1013 return BlockDescriptorType;
1014
Chris Lattnera5f58b02011-07-09 17:41:47 +00001015 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001016 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001017
Mike Stump650c9322009-02-13 15:16:56 +00001018 // struct __block_descriptor {
1019 // unsigned long reserved;
1020 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001021 //
1022 // // later, the following will be added
1023 //
1024 // struct {
1025 // void (*copyHelper)();
1026 // void (*copyHelper)();
1027 // } helpers; // !!! optional
1028 //
1029 // const char *signature; // the block signature
1030 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001031 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001032 BlockDescriptorType = llvm::StructType::create(
1033 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001034
John McCall351762c2011-02-07 10:33:21 +00001035 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001036 unsigned AddrSpace = 0;
1037 if (getLangOpts().OpenCL)
1038 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1039 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001040 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001041}
1042
Chris Lattnera5f58b02011-07-09 17:41:47 +00001043llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +00001044 if (GenericBlockLiteralType)
1045 return GenericBlockLiteralType;
1046
Chris Lattnera5f58b02011-07-09 17:41:47 +00001047 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001048
Yaxun Liu10712d92017-10-04 20:32:17 +00001049 if (getLangOpts().OpenCL) {
1050 // struct __opencl_block_literal_generic {
1051 // int __size;
1052 // int __align;
1053 // __generic void *__invoke;
1054 // /* custom fields */
1055 // };
1056 SmallVector<llvm::Type *, 8> StructFields(
1057 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1058 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1059 for (auto I : Helper->getCustomFieldTypes())
1060 StructFields.push_back(I);
1061 }
1062 GenericBlockLiteralType = llvm::StructType::create(
1063 StructFields, "struct.__opencl_block_literal_generic");
1064 } else {
1065 // struct __block_literal_generic {
1066 // void *__isa;
1067 // int __flags;
1068 // int __reserved;
1069 // void (*__invoke)(void *);
1070 // struct __block_descriptor *__descriptor;
1071 // };
1072 GenericBlockLiteralType =
1073 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1074 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1075 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001076
Mike Stump005c9a62009-02-13 15:25:34 +00001077 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001078}
1079
Yaxun Liu10712d92017-10-04 20:32:17 +00001080RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001081 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001082 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001083 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001084
John McCallb92ab1a2016-10-26 23:46:34 +00001085 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001086
1087 // Get a pointer to the generic block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001088 // For OpenCL we generate generic AS void ptr to be able to reuse the same
1089 // block definition for blocks with captures generated as private AS local
1090 // variables and without captures generated as global AS program scope
1091 // variables.
1092 unsigned AddrSpace = 0;
1093 if (getLangOpts().OpenCL)
1094 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1095
Chris Lattner2192fe52011-07-18 04:24:23 +00001096 llvm::Type *BlockLiteralTy =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001097 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001098
1099 // Bitcast the callee to a block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001100 BlockPtr =
1101 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001102
1103 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +00001104 llvm::Value *FuncPtr =
Yaxun Liu10712d92017-10-04 20:32:17 +00001105 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr,
1106 CGM.getLangOpts().OpenCL ? 2 : 3);
Mike Stumpb7074c02009-02-13 15:32:32 +00001107
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001108 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001109 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001110
1111 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1112 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1113 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001114 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001115 VoidPtrQualTy =
1116 getContext().getPointerType(getContext().getAddrSpaceQualType(
1117 getContext().VoidTy, LangAS::opencl_generic));
1118 }
1119
1120 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1121 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001122
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001123 QualType FnType = BPT->getPointeeType();
1124
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001125 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001126 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001127
Anders Carlsson5f50c652009-04-07 22:10:22 +00001128 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001129 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001130
John McCall85915252011-03-09 08:39:33 +00001131 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001132 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001133 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001134
Anders Carlsson5f50c652009-04-07 22:10:22 +00001135 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001136 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001137
Chris Lattner2192fe52011-07-18 04:24:23 +00001138 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001139 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001140
John McCallb92ab1a2016-10-26 23:46:34 +00001141 // Prepare the callee.
1142 CGCallee Callee(CGCalleeInfo(), Func);
1143
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001144 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001145 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001146}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001147
John McCall7f416cc2015-09-08 08:05:57 +00001148Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1149 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001150 assert(BlockInfo && "evaluating block ref without block information?");
1151 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001152
John McCall351762c2011-02-07 10:33:21 +00001153 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001154 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001155
John McCall7f416cc2015-09-08 08:05:57 +00001156 Address addr =
1157 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1158 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001159
John McCall351762c2011-02-07 10:33:21 +00001160 if (isByRef) {
1161 // addr should be a void** right now. Load, then cast the result
1162 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001163
John McCall7f416cc2015-09-08 08:05:57 +00001164 auto &byrefInfo = getBlockByrefInfo(variable);
1165 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001166
John McCall7f416cc2015-09-08 08:05:57 +00001167 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1168 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001169
John McCall7f416cc2015-09-08 08:05:57 +00001170 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1171 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001172 }
1173
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001174 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001175 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001176
John McCall351762c2011-02-07 10:33:21 +00001177 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001178}
1179
George Burgess IVe3763372016-12-22 02:50:20 +00001180void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1181 llvm::Constant *Addr) {
1182 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1183 (void)Ok;
1184 assert(Ok && "Trying to replace an already-existing global block!");
1185}
1186
Mike Stump2d5a2872009-02-14 22:16:35 +00001187llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001188CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1189 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001190 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1191 return Block;
1192
George Burgess IV70d15b32016-11-03 02:21:43 +00001193 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1194 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001195
John McCall351762c2011-02-07 10:33:21 +00001196 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001197 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001198
John McCall351762c2011-02-07 10:33:21 +00001199 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001200 {
John McCall7f416cc2015-09-08 08:05:57 +00001201 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001202 CodeGenFunction(*this).GenerateBlockFunction(
1203 GlobalDecl(), blockInfo, LocalDeclMap,
1204 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001205 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001206
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001207 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001208}
1209
John McCall351762c2011-02-07 10:33:21 +00001210static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1211 const CGBlockInfo &blockInfo,
1212 llvm::Constant *blockFn) {
1213 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001214 // Callers should detect this case on their own: calling this function
1215 // generally requires computing layout information, which is a waste of time
1216 // if we've already emitted this block.
1217 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1218 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001219
1220 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001221 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001222 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001223
Yaxun Liu10712d92017-10-04 20:32:17 +00001224 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1225 if (!IsOpenCL) {
1226 // isa
1227 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001228
Yaxun Liu10712d92017-10-04 20:32:17 +00001229 // __flags
1230 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1231 if (blockInfo.UsesStret)
1232 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001233
Yaxun Liu10712d92017-10-04 20:32:17 +00001234 fields.addInt(CGM.IntTy, flags.getBitMask());
1235
1236 // Reserved
1237 fields.addInt(CGM.IntTy, 0);
1238 } else {
1239 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1240 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1241 }
John McCall351762c2011-02-07 10:33:21 +00001242
1243 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001244 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001245
Yaxun Liu10712d92017-10-04 20:32:17 +00001246 if (!IsOpenCL) {
1247 // Descriptor
1248 fields.add(buildBlockDescriptor(CGM, blockInfo));
1249 } else if (auto *Helper =
1250 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1251 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1252 fields.add(I);
1253 }
1254 }
John McCall351762c2011-02-07 10:33:21 +00001255
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001256 unsigned AddrSpace = 0;
1257 if (CGM.getContext().getLangOpts().OpenCL)
1258 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1259
1260 llvm::Constant *literal = fields.finishAndCreateGlobal(
1261 "__block_literal_global", blockInfo.BlockAlign,
1262 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001263
1264 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001265 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001266 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001267 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001268 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001269 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1270 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001271}
1272
John McCall7f416cc2015-09-08 08:05:57 +00001273void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1274 unsigned argNum,
1275 llvm::Value *arg) {
1276 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1277
1278 llvm::Value *localAddr = nullptr;
1279 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1280 // Allocate a stack slot to let the debug info survive the RA.
1281 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1282 Builder.CreateStore(arg, alloc);
1283 localAddr = Builder.CreateLoad(alloc);
1284 }
1285
1286 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001287 if (CGM.getCodeGenOpts().getDebugInfo() >=
1288 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001289 DI->setLocation(D->getLocation());
1290 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1291 localAddr, Builder);
1292 }
1293 }
1294
1295 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1296 ApplyDebugLocation Scope(*this, StartLoc);
1297
1298 // Instead of messing around with LocalDeclMap, just set the value
1299 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001300 BlockPointer = Builder.CreatePointerCast(
1301 arg,
1302 BlockInfo->StructureType->getPointerTo(
1303 getContext().getLangOpts().OpenCL
1304 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1305 : 0),
1306 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001307}
1308
1309Address CodeGenFunction::LoadBlockStruct() {
1310 assert(BlockInfo && "not in a block invocation function!");
1311 assert(BlockPointer && "no block pointer set!");
1312 return Address(BlockPointer, BlockInfo->BlockAlign);
1313}
1314
Mike Stump4446dcf2009-03-05 08:32:30 +00001315llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001316CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1317 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001318 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001319 bool IsLambdaConversionToBlock,
1320 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001321 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001322
Fariborz Jahanian63628032012-06-26 16:06:38 +00001323 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001324
1325 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001326
John McCall351762c2011-02-07 10:33:21 +00001327 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001328
Mike Stump5469f292009-03-13 23:34:28 +00001329 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001330 // to be local to this function as well, in case they're directly
1331 // referenced in a block.
1332 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001333 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001334 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001335 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001336 }
1337
John McCall351762c2011-02-07 10:33:21 +00001338 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001339
John McCall351762c2011-02-07 10:33:21 +00001340 // Build the argument list.
1341 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001342
John McCall351762c2011-02-07 10:33:21 +00001343 // The first argument is the block pointer. Just take it as a void*
1344 // and cast it later.
1345 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001346
1347 // For OpenCL passed block pointer can be private AS local variable or
1348 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001349 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001350 // generic AS in one implementation.
1351 if (getLangOpts().OpenCL)
1352 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1353 getContext().VoidTy, LangAS::opencl_generic));
1354
Mike Stump7fe9cc12009-10-21 03:49:08 +00001355 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001356
Alexey Bataev56223232017-06-09 13:40:18 +00001357 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1358 SourceLocation(), II, selfTy,
1359 ImplicitParamDecl::ObjCSelf);
1360 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001361
John McCall351762c2011-02-07 10:33:21 +00001362 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001363 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001364
John McCall351762c2011-02-07 10:33:21 +00001365 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001366 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001367 const CGFunctionInfo &fnInfo =
1368 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001369 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001370 blockInfo.UsesStret = true;
1371
John McCalla729c622012-02-17 03:33:10 +00001372 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001373
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001374 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001375 llvm::Function *fn = llvm::Function::Create(
1376 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001377 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001378
Yaxun Liu10712d92017-10-04 20:32:17 +00001379 if (BuildGlobalBlock) {
1380 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1381 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1382 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001383 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001384 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1385 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001386
John McCall351762c2011-02-07 10:33:21 +00001387 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001388 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001389 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001390 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001391
John McCall147d0212011-02-22 22:38:33 +00001392 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001393
Adrian Prantl0f6df002013-03-29 19:20:35 +00001394 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1395 // won't delete the dbg.declare intrinsics for captured variables.
1396 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1397 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1398 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001399 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1400 getPointerAlign(),
1401 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001402 // Set the DebugLocation to empty, so the store is recognized as a
1403 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001404 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001405 Builder.CreateStore(BlockPointer, Alloca);
1406 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001407 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001408
John McCall87fe5d52010-05-20 01:18:31 +00001409 // If we have a C++ 'this' reference, go ahead and force it into
1410 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001411 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001412 Address addr =
1413 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1414 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001415 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001416 }
1417
John McCall351762c2011-02-07 10:33:21 +00001418 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001419 for (const auto &CI : blockDecl->captures()) {
1420 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001421 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1422 if (!capture.isConstant()) continue;
1423
John McCall7f416cc2015-09-08 08:05:57 +00001424 CharUnits align = getContext().getDeclAlign(variable);
1425 Address alloca =
1426 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001427
John McCall7f416cc2015-09-08 08:05:57 +00001428 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001429
John McCall7f416cc2015-09-08 08:05:57 +00001430 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001431 }
1432
John McCall113bee02012-03-10 09:33:50 +00001433 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001434 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1435 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1436 --entry_ptr;
1437
Eli Friedman2495ab02012-02-25 02:48:22 +00001438 if (IsLambdaConversionToBlock)
1439 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001440 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001441 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001442 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001443 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001444 }
Mike Stump017460a2009-10-01 22:29:41 +00001445
Mike Stump7d699112009-10-01 00:27:30 +00001446 // Remember where we were...
1447 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001448
Mike Stump7d699112009-10-01 00:27:30 +00001449 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001450 ++entry_ptr;
1451 Builder.SetInsertPoint(entry, entry_ptr);
1452
John McCall113bee02012-03-10 09:33:50 +00001453 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001454 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001455 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001456 for (const auto &CI : blockDecl->captures()) {
1457 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001458 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001459
Benjamin Kramer8c305922016-02-02 11:06:51 +00001460 if (CGM.getCodeGenOpts().getDebugInfo() >=
1461 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001462 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1463 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001464 auto addr = LocalDeclMap.find(variable)->second;
1465 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001466 Builder);
1467 continue;
1468 }
John McCall351762c2011-02-07 10:33:21 +00001469
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001470 DI->EmitDeclareOfBlockDeclRefVariable(
1471 variable, BlockPointerDbgLoc, Builder, blockInfo,
1472 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001473 }
Mike Stump2e722b92009-09-30 02:43:10 +00001474 }
Manman Renab08a9a2013-01-04 18:51:35 +00001475 // Recover location if it was changed in the above loop.
1476 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001477 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001478 }
John McCall351762c2011-02-07 10:33:21 +00001479
Mike Stump7d699112009-10-01 00:27:30 +00001480 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001481 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001482 Builder.ClearInsertionPoint();
1483 else
1484 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001485
John McCall351762c2011-02-07 10:33:21 +00001486 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001487
John McCall351762c2011-02-07 10:33:21 +00001488 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001489}
Mike Stump1db7d042009-02-28 09:07:16 +00001490
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001491namespace {
1492
1493/// Represents a type of copy/destroy operation that should be performed for an
1494/// entity that's captured by a block.
1495enum class BlockCaptureEntityKind {
1496 CXXRecord, // Copy or destroy
1497 ARCWeak,
1498 ARCStrong,
1499 BlockObject, // Assign or release
1500 None
1501};
1502
1503/// Represents a captured entity that requires extra operations in order for
1504/// this entity to be copied or destroyed correctly.
1505struct BlockCaptureManagedEntity {
1506 BlockCaptureEntityKind Kind;
1507 BlockFieldFlags Flags;
1508 const BlockDecl::Capture &CI;
1509 const CGBlockInfo::Capture &Capture;
1510
1511 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1512 const BlockDecl::Capture &CI,
1513 const CGBlockInfo::Capture &Capture)
1514 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1515};
1516
1517} // end anonymous namespace
1518
1519static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1520computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1521 const LangOptions &LangOpts) {
1522 if (CI.getCopyExpr()) {
1523 assert(!CI.isByRef());
1524 // don't bother computing flags
1525 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1526 }
1527 BlockFieldFlags Flags;
1528 if (CI.isByRef()) {
1529 Flags = BLOCK_FIELD_IS_BYREF;
1530 if (T.isObjCGCWeak())
1531 Flags |= BLOCK_FIELD_IS_WEAK;
1532 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1533 }
1534 if (!T->isObjCRetainableType())
1535 // For all other types, the memcpy is fine.
1536 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1537
1538 Flags = BLOCK_FIELD_IS_OBJECT;
1539 bool isBlockPointer = T->isBlockPointerType();
1540 if (isBlockPointer)
1541 Flags = BLOCK_FIELD_IS_BLOCK;
1542
1543 // Special rules for ARC captures:
1544 Qualifiers QS = T.getQualifiers();
1545
1546 // We need to register __weak direct captures with the runtime.
1547 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1548 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1549
1550 // We need to retain the copied value for __strong direct captures.
1551 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong) {
1552 // If it's a block pointer, we have to copy the block and
1553 // assign that to the destination pointer, so we might as
1554 // well use _Block_object_assign. Otherwise we can avoid that.
1555 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1556 : BlockCaptureEntityKind::BlockObject,
1557 Flags);
1558 }
1559
1560 // Non-ARC captures of retainable pointers are strong and
1561 // therefore require a call to _Block_object_assign.
1562 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1563 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1564
1565 // Otherwise the memcpy is fine.
1566 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1567}
1568
1569/// Find the set of block captures that need to be explicitly copied or destroy.
1570static void findBlockCapturedManagedEntities(
1571 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1572 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1573 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1574 const BlockDecl::Capture &, QualType, const LangOptions &)>
1575 Predicate) {
1576 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1577 const VarDecl *Variable = CI.getVariable();
1578 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1579 if (Capture.isConstant())
1580 continue;
1581
1582 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1583 if (Info.first != BlockCaptureEntityKind::None)
1584 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1585 }
1586}
1587
John McCallf593b102013-01-22 03:56:22 +00001588/// Generate the copy-helper function for a block closure object:
1589/// static void block_copy_helper(block_t *dst, block_t *src);
1590/// The runtime will have previously initialized 'dst' by doing a
1591/// bit-copy of 'src'.
1592///
1593/// Note that this copies an entire block closure object to the heap;
1594/// it should not be confused with a 'byref copy helper', which moves
1595/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001596llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001597CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001598 ASTContext &C = getContext();
1599
1600 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001601 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1602 ImplicitParamDecl::Other);
1603 args.push_back(&DstDecl);
1604 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1605 ImplicitParamDecl::Other);
1606 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001607
John McCallc56a8b32016-03-11 04:30:31 +00001608 const CGFunctionInfo &FI =
1609 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001610
John McCall351762c2011-02-07 10:33:21 +00001611 // FIXME: it would be nice if these were mergeable with things with
1612 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001613 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001614
1615 llvm::Function *Fn =
1616 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001617 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001618
1619 IdentifierInfo *II
1620 = &CGM.getContext().Idents.get("__copy_helper_block_");
1621
John McCall351762c2011-02-07 10:33:21 +00001622 FunctionDecl *FD = FunctionDecl::Create(C,
1623 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001624 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001625 SourceLocation(), II, C.VoidTy,
1626 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001627 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001628 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001629
1630 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1631
Adrian Prantl95b24e92015-02-03 20:00:54 +00001632 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001633 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001634 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001635 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001636 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001637
Alexey Bataev56223232017-06-09 13:40:18 +00001638 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001639 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001640 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001641
Alexey Bataev56223232017-06-09 13:40:18 +00001642 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001643 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001644 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001645
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001646 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1647 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1648 computeCopyInfoForBlockCapture);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001649
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001650 for (const auto &CopiedCapture : CopiedCaptures) {
1651 const BlockDecl::Capture &CI = CopiedCapture.CI;
1652 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
1653 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001654
1655 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001656 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1657 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001658
1659 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001660 if (CI.getCopyExpr()) {
1661 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1662 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1663 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001664 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001665 } else {
1666 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001667 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001668 // At -O0, store null into the destination field (so that the
1669 // storeStrong doesn't over-release) and then call storeStrong.
1670 // This is a workaround to not having an initStrong call.
1671 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001672 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001673 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1674 Builder.CreateStore(null, dstField);
1675 EmitARCStoreStrongCall(dstField, srcValue, true);
1676
1677 // With optimization enabled, take advantage of the fact that
1678 // the blocks runtime guarantees a memcpy of the block data, and
1679 // just emit a retain of the src field.
1680 } else {
1681 EmitARCRetainNonBlock(srcValue);
1682
1683 // We don't need this anymore, so kill it. It's not quite
1684 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001685 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001686 }
1687 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001688 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001689 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001690 llvm::Value *dstAddr =
1691 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001692 llvm::Value *args[] = {
1693 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1694 };
1695
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001696 const VarDecl *variable = CI.getVariable();
John McCall882987f2013-02-28 19:01:20 +00001697 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001698 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001699 const Expr *copyExpr =
1700 CGM.getContext().getBlockVarCopyInits(variable);
1701 if (copyExpr) {
1702 copyCanThrow = true; // FIXME: reuse the noexcept logic
1703 }
1704 }
1705
1706 if (copyCanThrow) {
1707 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1708 } else {
1709 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1710 }
John McCalle68b8f42012-10-17 02:28:37 +00001711 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001712 }
1713 }
1714
John McCallad7c5c12011-02-08 08:22:06 +00001715 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001716
John McCalle3dc1702011-02-15 09:22:45 +00001717 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001718}
1719
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001720static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1721computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1722 const LangOptions &LangOpts) {
1723 BlockFieldFlags Flags;
1724 if (CI.isByRef()) {
1725 Flags = BLOCK_FIELD_IS_BYREF;
1726 if (T.isObjCGCWeak())
1727 Flags |= BLOCK_FIELD_IS_WEAK;
1728 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1729 }
1730
1731 if (const CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1732 if (Record->hasTrivialDestructor())
1733 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1734 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1735 }
1736
1737 // Other types don't need to be destroy explicitly.
1738 if (!T->isObjCRetainableType())
1739 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1740
1741 Flags = BLOCK_FIELD_IS_OBJECT;
1742 if (T->isBlockPointerType())
1743 Flags = BLOCK_FIELD_IS_BLOCK;
1744
1745 // Special rules for ARC captures.
1746 Qualifiers QS = T.getQualifiers();
1747
1748 // Use objc_storeStrong for __strong direct captures; the
1749 // dynamic tools really like it when we do this.
1750 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong)
1751 return std::make_pair(BlockCaptureEntityKind::ARCStrong, Flags);
1752
1753 // Support __weak direct captures.
1754 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1755 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1756
1757 // Non-ARC captures are strong, and we need to use
1758 // _Block_object_dispose.
1759 if (!QS.hasObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1760 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1761
1762 // Otherwise, we have nothing to do.
1763 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1764}
1765
John McCallf593b102013-01-22 03:56:22 +00001766/// Generate the destroy-helper function for a block closure object:
1767/// static void block_destroy_helper(block_t *theBlock);
1768///
1769/// Note that this destroys a heap-allocated block closure object;
1770/// it should not be confused with a 'byref destroy helper', which
1771/// destroys the heap-allocated contents of an individual __block
1772/// variable.
John McCall351762c2011-02-07 10:33:21 +00001773llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001774CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001775 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001776
John McCall351762c2011-02-07 10:33:21 +00001777 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001778 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1779 ImplicitParamDecl::Other);
1780 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001781
John McCallc56a8b32016-03-11 04:30:31 +00001782 const CGFunctionInfo &FI =
1783 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001784
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001785 // FIXME: We'd like to put these into a mergable by content, with
1786 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001787 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001788
1789 llvm::Function *Fn =
1790 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001791 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001792
1793 IdentifierInfo *II
1794 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1795
John McCall351762c2011-02-07 10:33:21 +00001796 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001797 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001798 SourceLocation(), II, C.VoidTy,
1799 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001800 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001801
1802 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1803
Adrian Prantl49a78562013-07-24 20:34:39 +00001804 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001805 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001806 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001807 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001808
Chris Lattner2192fe52011-07-18 04:24:23 +00001809 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001810
Alexey Bataev56223232017-06-09 13:40:18 +00001811 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001812 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001813 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001814
John McCallad7c5c12011-02-08 08:22:06 +00001815 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001816
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001817 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1818 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1819 computeDestroyInfoForBlockCapture);
John McCall351762c2011-02-07 10:33:21 +00001820
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001821 for (const auto &DestroyedCapture : DestroyedCaptures) {
1822 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1823 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1824 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001825
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address srcField =
1827 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001828
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001829 // If the captured record has a destructor then call it.
1830 if (DestroyedCapture.Kind == BlockCaptureEntityKind::CXXRecord) {
1831 const auto *Dtor =
1832 CI.getVariable()->getType()->getAsCXXRecordDecl()->getDestructor();
1833 PushDestructorCleanup(Dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001834
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001835 // If this is a __weak capture, emit the release directly.
1836 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001837 EmitARCDestroyWeak(srcField);
1838
John McCalle68b8f42012-10-17 02:28:37 +00001839 // Destroy strong objects with a call if requested.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001840 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCallcdda29c2013-03-13 03:10:54 +00001841 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001842
John McCall351762c2011-02-07 10:33:21 +00001843 // Otherwise we call _Block_object_dispose. It wouldn't be too
1844 // hard to just emit this as a cleanup if we wanted to make sure
1845 // that things were done in reverse.
1846 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001847 assert(DestroyedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCall351762c2011-02-07 10:33:21 +00001848 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001849 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001850 BuildBlockRelease(value, flags);
1851 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001852 }
1853
John McCall351762c2011-02-07 10:33:21 +00001854 cleanups.ForceCleanup();
1855
John McCallad7c5c12011-02-08 08:22:06 +00001856 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001857
John McCalle3dc1702011-02-15 09:22:45 +00001858 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001859}
1860
John McCallf9b056b2011-03-31 08:03:29 +00001861namespace {
1862
1863/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001864class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001865 BlockFieldFlags Flags;
1866
1867public:
1868 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001869 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001870
John McCall7f416cc2015-09-08 08:05:57 +00001871 void emitCopy(CodeGenFunction &CGF, Address destField,
1872 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001873 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1874
1875 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1876 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1877
1878 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1879
1880 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1881 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001882
John McCall7f416cc2015-09-08 08:05:57 +00001883 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001884 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001885 }
1886
John McCall7f416cc2015-09-08 08:05:57 +00001887 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001888 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1889 llvm::Value *value = CGF.Builder.CreateLoad(field);
1890
1891 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1892 }
1893
Craig Topper4f12f102014-03-12 06:41:41 +00001894 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001895 id.AddInteger(Flags.getBitMask());
1896 }
1897};
1898
John McCall31168b02011-06-15 23:02:42 +00001899/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001900class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001901public:
John McCall7f416cc2015-09-08 08:05:57 +00001902 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001903
John McCall7f416cc2015-09-08 08:05:57 +00001904 void emitCopy(CodeGenFunction &CGF, Address destField,
1905 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001906 CGF.EmitARCMoveWeak(destField, srcField);
1907 }
1908
John McCall7f416cc2015-09-08 08:05:57 +00001909 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001910 CGF.EmitARCDestroyWeak(field);
1911 }
1912
Craig Topper4f12f102014-03-12 06:41:41 +00001913 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001914 // 0 is distinguishable from all pointers and byref flags
1915 id.AddInteger(0);
1916 }
1917};
1918
1919/// Emits the copy/dispose helpers for an ARC __block __strong variable
1920/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001921class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001922public:
John McCall7f416cc2015-09-08 08:05:57 +00001923 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001924
John McCall7f416cc2015-09-08 08:05:57 +00001925 void emitCopy(CodeGenFunction &CGF, Address destField,
1926 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001927 // Do a "move" by copying the value and then zeroing out the old
1928 // variable.
1929
John McCall7f416cc2015-09-08 08:05:57 +00001930 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001931
John McCall31168b02011-06-15 23:02:42 +00001932 llvm::Value *null =
1933 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001934
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001935 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001936 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001937 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1938 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1939 return;
1940 }
John McCall7f416cc2015-09-08 08:05:57 +00001941 CGF.Builder.CreateStore(value, destField);
1942 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001943 }
1944
John McCall7f416cc2015-09-08 08:05:57 +00001945 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001946 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001947 }
1948
Craig Topper4f12f102014-03-12 06:41:41 +00001949 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001950 // 1 is distinguishable from all pointers and byref flags
1951 id.AddInteger(1);
1952 }
1953};
1954
John McCall3a237aa2011-11-09 03:17:26 +00001955/// Emits the copy/dispose helpers for an ARC __block __strong
1956/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001957class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001958public:
John McCall7f416cc2015-09-08 08:05:57 +00001959 ARCStrongBlockByrefHelpers(CharUnits alignment)
1960 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001961
John McCall7f416cc2015-09-08 08:05:57 +00001962 void emitCopy(CodeGenFunction &CGF, Address destField,
1963 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001964 // Do the copy with objc_retainBlock; that's all that
1965 // _Block_object_assign would do anyway, and we'd have to pass the
1966 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001967 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001968 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001969 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001970 }
1971
John McCall7f416cc2015-09-08 08:05:57 +00001972 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001973 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001974 }
1975
Craig Topper4f12f102014-03-12 06:41:41 +00001976 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001977 // 2 is distinguishable from all pointers and byref flags
1978 id.AddInteger(2);
1979 }
1980};
1981
John McCallf9b056b2011-03-31 08:03:29 +00001982/// Emits the copy/dispose helpers for a __block variable with a
1983/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001984class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001985 QualType VarType;
1986 const Expr *CopyExpr;
1987
1988public:
1989 CXXByrefHelpers(CharUnits alignment, QualType type,
1990 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001991 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001992
Craig Topper8a13c412014-05-21 05:09:00 +00001993 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001994 void emitCopy(CodeGenFunction &CGF, Address destField,
1995 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001996 if (!CopyExpr) return;
1997 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1998 }
1999
John McCall7f416cc2015-09-08 08:05:57 +00002000 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002001 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2002 CGF.PushDestructorCleanup(VarType, field);
2003 CGF.PopCleanupBlocks(cleanupDepth);
2004 }
2005
Craig Topper4f12f102014-03-12 06:41:41 +00002006 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002007 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2008 }
2009};
2010} // end anonymous namespace
2011
2012static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002013generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2014 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002015 ASTContext &Context = CGF.getContext();
2016
2017 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002018
John McCalla738c252011-03-09 04:27:21 +00002019 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002020 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2021 ImplicitParamDecl::Other);
2022 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002023
Alexey Bataev56223232017-06-09 13:40:18 +00002024 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2025 ImplicitParamDecl::Other);
2026 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCallc56a8b32016-03-11 04:30:31 +00002028 const CGFunctionInfo &FI =
2029 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002030
John McCall7f416cc2015-09-08 08:05:57 +00002031 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002032
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002033 // FIXME: We'd like to put these into a mergable by content, with
2034 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002035 llvm::Function *Fn =
2036 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002037 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002038
2039 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002040 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002041
John McCallf9b056b2011-03-31 08:03:29 +00002042 FunctionDecl *FD = FunctionDecl::Create(Context,
2043 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002044 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002045 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002046 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002047 false, false);
John McCall31168b02011-06-15 23:02:42 +00002048
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002049 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2050
Adrian Prantl22e66b42014-04-11 01:13:04 +00002051 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002052
John McCall7f416cc2015-09-08 08:05:57 +00002053 if (generator.needsCopy()) {
2054 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002055
John McCallf9b056b2011-03-31 08:03:29 +00002056 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002057 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002058 destField = Address(CGF.Builder.CreateLoad(destField),
2059 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002060 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002061 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2062 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002063
John McCallf9b056b2011-03-31 08:03:29 +00002064 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002065 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002066 srcField = Address(CGF.Builder.CreateLoad(srcField),
2067 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002068 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002069 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2070 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002071
John McCall7f416cc2015-09-08 08:05:57 +00002072 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00002073 }
2074
2075 CGF.FinishFunction();
2076
2077 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002078}
2079
John McCallf9b056b2011-03-31 08:03:29 +00002080/// Build the copy helper for a __block variable.
2081static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002082 const BlockByrefInfo &byrefInfo,
2083 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002084 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002085 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002086}
2087
2088/// Generate code for a __block variable's dispose helper.
2089static llvm::Constant *
2090generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002091 const BlockByrefInfo &byrefInfo,
2092 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002093 ASTContext &Context = CGF.getContext();
2094 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002095
John McCalla738c252011-03-09 04:27:21 +00002096 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002097 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2098 ImplicitParamDecl::Other);
2099 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002100
John McCallc56a8b32016-03-11 04:30:31 +00002101 const CGFunctionInfo &FI =
2102 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002103
John McCall7f416cc2015-09-08 08:05:57 +00002104 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002105
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002106 // FIXME: We'd like to put these into a mergable by content, with
2107 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002108 llvm::Function *Fn =
2109 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002110 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002111 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002112
2113 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002114 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002115
John McCallf9b056b2011-03-31 08:03:29 +00002116 FunctionDecl *FD = FunctionDecl::Create(Context,
2117 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002118 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002119 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002120 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002121 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002122
2123 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2124
Adrian Prantl22e66b42014-04-11 01:13:04 +00002125 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002126
John McCall7f416cc2015-09-08 08:05:57 +00002127 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002128 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002129 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2130 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2131 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2132 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002133
John McCall7f416cc2015-09-08 08:05:57 +00002134 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002135 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002136
John McCallf9b056b2011-03-31 08:03:29 +00002137 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002138
John McCallf9b056b2011-03-31 08:03:29 +00002139 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002140}
2141
John McCallf9b056b2011-03-31 08:03:29 +00002142/// Build the dispose helper for a __block variable.
2143static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002144 const BlockByrefInfo &byrefInfo,
2145 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002146 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002147 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002148}
2149
John McCallf593b102013-01-22 03:56:22 +00002150/// Lazily build the copy and dispose helpers for a __block variable
2151/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002152template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002153static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2154 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002155 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002156 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002157
2158 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002159 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002160 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2161 if (node) return static_cast<T*>(node);
2162
John McCall7f416cc2015-09-08 08:05:57 +00002163 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2164 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002165
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002166 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002167 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2168 return copy;
2169}
2170
John McCallf593b102013-01-22 03:56:22 +00002171/// Build the copy and dispose helpers for the given __block variable
2172/// emission. Places the helpers in the global cache. Returns null
2173/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002174BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002175CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002176 const AutoVarEmission &emission) {
2177 const VarDecl &var = *emission.Variable;
2178 QualType type = var.getType();
2179
John McCall7f416cc2015-09-08 08:05:57 +00002180 auto &byrefInfo = getBlockByrefInfo(&var);
2181
2182 // The alignment we care about for the purposes of uniquing byref
2183 // helpers is the alignment of the actual byref value field.
2184 CharUnits valueAlignment =
2185 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002186
John McCallf9b056b2011-03-31 08:03:29 +00002187 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2188 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002189 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002190
David Blaikie92551612015-08-13 23:53:09 +00002191 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002192 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002193 }
2194
John McCall31168b02011-06-15 23:02:42 +00002195 // Otherwise, if we don't have a retainable type, there's nothing to do.
2196 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002197 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002198
2199 Qualifiers qs = type.getQualifiers();
2200
2201 // If we have lifetime, that dominates.
2202 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002203 switch (lifetime) {
2204 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2205
2206 // These are just bits as far as the runtime is concerned.
2207 case Qualifiers::OCL_ExplicitNone:
2208 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002209 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002210
2211 // Tell the runtime that this is ARC __weak, called by the
2212 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002213 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002214 return ::buildByrefHelpers(CGM, byrefInfo,
2215 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002216
2217 // ARC __strong __block variables need to be retained.
2218 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002219 // Block pointers need to be copied, and there's no direct
2220 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002221 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002222 return ::buildByrefHelpers(CGM, byrefInfo,
2223 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002224
2225 // Otherwise, we transfer ownership of the retain from the stack
2226 // to the heap.
2227 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002228 return ::buildByrefHelpers(CGM, byrefInfo,
2229 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002230 }
2231 }
2232 llvm_unreachable("fell out of lifetime switch!");
2233 }
2234
John McCallf9b056b2011-03-31 08:03:29 +00002235 BlockFieldFlags flags;
2236 if (type->isBlockPointerType()) {
2237 flags |= BLOCK_FIELD_IS_BLOCK;
2238 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2239 type->isObjCObjectPointerType()) {
2240 flags |= BLOCK_FIELD_IS_OBJECT;
2241 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002242 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002243 }
2244
2245 if (type.isObjCGCWeak())
2246 flags |= BLOCK_FIELD_IS_WEAK;
2247
John McCall7f416cc2015-09-08 08:05:57 +00002248 return ::buildByrefHelpers(CGM, byrefInfo,
2249 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002250}
2251
John McCall7f416cc2015-09-08 08:05:57 +00002252Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2253 const VarDecl *var,
2254 bool followForward) {
2255 auto &info = getBlockByrefInfo(var);
2256 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002257}
2258
John McCall7f416cc2015-09-08 08:05:57 +00002259Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2260 const BlockByrefInfo &info,
2261 bool followForward,
2262 const llvm::Twine &name) {
2263 // Chase the forwarding address if requested.
2264 if (followForward) {
2265 Address forwardingAddr =
2266 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2267 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2268 }
2269
2270 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2271 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002272}
2273
John McCall7f416cc2015-09-08 08:05:57 +00002274/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002275/// into:
2276///
2277/// struct {
2278/// void *__isa;
2279/// void *__forwarding;
2280/// int32_t __flags;
2281/// int32_t __size;
2282/// void *__copy_helper; // only if needed
2283/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002284/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002285/// char padding[X]; // only if needed
2286/// T x;
2287/// } x
2288///
John McCall7f416cc2015-09-08 08:05:57 +00002289const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2290 auto it = BlockByrefInfos.find(D);
2291 if (it != BlockByrefInfos.end())
2292 return it->second;
John McCall73064872011-03-31 01:59:53 +00002293
John McCall7f416cc2015-09-08 08:05:57 +00002294 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002295 llvm::StructType::create(getLLVMContext(),
2296 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002297
John McCall7f416cc2015-09-08 08:05:57 +00002298 QualType Ty = D->getType();
2299
2300 CharUnits size;
2301 SmallVector<llvm::Type *, 8> types;
2302
John McCall73064872011-03-31 01:59:53 +00002303 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002304 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002305 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002306
2307 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002308 types.push_back(llvm::PointerType::getUnqual(byrefType));
2309 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002310
2311 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002312 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002313 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002314
2315 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002316 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002317 size += CharUnits::fromQuantity(4);
2318
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002319 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002320 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2321 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002322 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002323 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002324 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002325
2326 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002327 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002328 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002329 }
John McCall7f416cc2015-09-08 08:05:57 +00002330
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002331 bool HasByrefExtendedLayout = false;
2332 Qualifiers::ObjCLifetime Lifetime;
2333 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002334 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002335 /// void *__byref_variable_layout;
2336 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002337 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002338 }
2339
2340 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002341 llvm::Type *varTy = ConvertTypeForMem(Ty);
2342
2343 bool packed = false;
2344 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002345 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002346
2347 // We may have to insert padding.
2348 if (varOffset != size) {
2349 llvm::Type *paddingTy =
2350 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2351
2352 types.push_back(paddingTy);
2353 size = varOffset;
2354
2355 // Conversely, we might have to prevent LLVM from inserting padding.
2356 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2357 > varAlign.getQuantity()) {
2358 packed = true;
2359 }
2360 types.push_back(varTy);
2361
2362 byrefType->setBody(types, packed);
2363
2364 BlockByrefInfo info;
2365 info.Type = byrefType;
2366 info.FieldIndex = types.size() - 1;
2367 info.FieldOffset = varOffset;
2368 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2369
2370 auto pair = BlockByrefInfos.insert({D, info});
2371 assert(pair.second && "info was inserted recursively?");
2372 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002373}
2374
2375/// Initialize the structural components of a __block variable, i.e.
2376/// everything but the actual object.
2377void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002378 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002379 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002380
John McCallf9b056b2011-03-31 08:03:29 +00002381 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002382 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002383 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2384
2385 unsigned nextHeaderIndex = 0;
2386 CharUnits nextHeaderOffset;
2387 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2388 const Twine &name) {
2389 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2390 nextHeaderOffset, name);
2391 Builder.CreateStore(value, fieldAddr);
2392
2393 nextHeaderIndex++;
2394 nextHeaderOffset += fieldSize;
2395 };
John McCallf9b056b2011-03-31 08:03:29 +00002396
2397 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002398 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002399
2400 const VarDecl &D = *emission.Variable;
2401 QualType type = D.getType();
2402
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002403 bool HasByrefExtendedLayout;
2404 Qualifiers::ObjCLifetime ByrefLifetime;
2405 bool ByRefHasLifetime =
2406 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002407
John McCallf9b056b2011-03-31 08:03:29 +00002408 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002409
2410 // Initialize the 'isa', which is just 0 or 1.
2411 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002412 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002413 isa = 1;
2414 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002415 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002416
2417 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002418 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002419
2420 // Blocks ABI:
2421 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002422 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002423 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002424 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2425 if (ByRefHasLifetime) {
2426 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2427 else switch (ByrefLifetime) {
2428 case Qualifiers::OCL_Strong:
2429 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2430 break;
2431 case Qualifiers::OCL_Weak:
2432 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2433 break;
2434 case Qualifiers::OCL_ExplicitNone:
2435 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2436 break;
2437 case Qualifiers::OCL_None:
2438 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2439 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2440 break;
2441 default:
2442 break;
2443 }
2444 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2445 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2446 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2447 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2448 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2449 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2450 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2451 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2452 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2453 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2454 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2455 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2456 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2457 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2458 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2459 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2460 }
2461 printf("\n");
2462 }
2463 }
John McCall7f416cc2015-09-08 08:05:57 +00002464 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2465 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002466
John McCallf9b056b2011-03-31 08:03:29 +00002467 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2468 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002469 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002470
John McCallf9b056b2011-03-31 08:03:29 +00002471 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002472 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2473 "byref.copyHelper");
2474 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2475 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002476 }
John McCall7f416cc2015-09-08 08:05:57 +00002477
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002478 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002479 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2480 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002481 }
John McCall73064872011-03-31 01:59:53 +00002482}
2483
John McCallad7c5c12011-02-08 08:22:06 +00002484void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002485 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002486 llvm::Value *args[] = {
2487 Builder.CreateBitCast(V, Int8PtrTy),
2488 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2489 };
2490 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002491}
John McCall73064872011-03-31 01:59:53 +00002492
2493namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002494 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002495 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002496 llvm::Value *Addr;
2497 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2498
Craig Topper4f12f102014-03-12 06:41:41 +00002499 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002500 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002501 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2502 }
2503 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002504} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002505
2506/// Enter a cleanup to destroy a __block variable. Note that this
2507/// cleanup should be a no-op if the variable hasn't left the stack
2508/// yet; if a cleanup is required for the variable itself, that needs
2509/// to be done externally.
2510void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2511 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002512 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002513 return;
2514
John McCall7f416cc2015-09-08 08:05:57 +00002515 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2516 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002517}
John McCall7959fee2011-09-09 20:41:01 +00002518
2519/// Adjust the declaration of something from the blocks API.
2520static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2521 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002522 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002523
2524 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2525 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2526 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2527 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2528
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002529 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2530 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2531 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002532
2533 const NamedDecl *ND = nullptr;
2534 for (const auto &Result : DC->lookup(&II))
2535 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2536 (ND = dyn_cast<VarDecl>(Result)))
2537 break;
2538
2539 // TODO: support static blocks runtime
2540 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2541 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2542 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2543 } else {
2544 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2545 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2546 }
2547 }
2548
2549 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2550 return;
2551
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002552 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002553 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2554}
2555
2556llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2557 if (BlockObjectDispose)
2558 return BlockObjectDispose;
2559
2560 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2561 llvm::FunctionType *fty
2562 = llvm::FunctionType::get(VoidTy, args, false);
2563 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2564 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2565 return BlockObjectDispose;
2566}
2567
2568llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2569 if (BlockObjectAssign)
2570 return BlockObjectAssign;
2571
2572 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2573 llvm::FunctionType *fty
2574 = llvm::FunctionType::get(VoidTy, args, false);
2575 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2576 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2577 return BlockObjectAssign;
2578}
2579
2580llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2581 if (NSConcreteGlobalBlock)
2582 return NSConcreteGlobalBlock;
2583
2584 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002585 Int8PtrTy->getPointerTo(),
2586 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002587 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2588 return NSConcreteGlobalBlock;
2589}
2590
2591llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2592 if (NSConcreteStackBlock)
2593 return NSConcreteStackBlock;
2594
2595 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002596 Int8PtrTy->getPointerTo(),
2597 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002598 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002599 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002600}