blob: 507ffec74cc9806580ebbe0cdaa7a5ce47b00bb8 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
17#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000018#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000022#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000023#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000024#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000025#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000026#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Module.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000029#include "llvm/Support/ScopedPrinter.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000030#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000031#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000032
Anders Carlsson2437cbf2009-02-12 00:39:25 +000033using namespace clang;
34using namespace CodeGen;
35
John McCall08ef4662011-11-10 08:15:53 +000036CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
37 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000038 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Akira Hatanaka9978da32018-08-10 15:09:24 +000039 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
40 StructureType(nullptr), Block(block), DominatingIP(nullptr) {
Craig Topper8a13c412014-05-21 05:09:00 +000041
John McCall08ef4662011-11-10 08:15:53 +000042 // Skip asm prefix, if any. 'name' is usually taken directly from
43 // the mangled name of the enclosing function.
44 if (!name.empty() && name[0] == '\01')
45 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000046}
47
John McCallf9b056b2011-03-31 08:03:29 +000048// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000049BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000050
John McCall351762c2011-02-07 10:33:21 +000051/// Build the given block as a global block.
52static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo,
54 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000055
John McCall351762c2011-02-07 10:33:21 +000056/// Build the helper function to copy a block.
57static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
60}
61
Alp Tokerf6a24ce2013-12-05 16:25:25 +000062/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000063static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
64 const CGBlockInfo &blockInfo) {
65 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
66}
67
Akira Hatanaka2ec36f02018-08-17 15:46:07 +000068namespace {
69
70/// Represents a type of copy/destroy operation that should be performed for an
71/// entity that's captured by a block.
72enum class BlockCaptureEntityKind {
73 CXXRecord, // Copy or destroy
74 ARCWeak,
75 ARCStrong,
76 NonTrivialCStruct,
77 BlockObject, // Assign or release
78 None
79};
80
81/// Represents a captured entity that requires extra operations in order for
82/// this entity to be copied or destroyed correctly.
83struct BlockCaptureManagedEntity {
84 BlockCaptureEntityKind CopyKind, DisposeKind;
85 BlockFieldFlags CopyFlags, DisposeFlags;
86 const BlockDecl::Capture *CI;
87 const CGBlockInfo::Capture *Capture;
88
89 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
90 BlockCaptureEntityKind DisposeType,
91 BlockFieldFlags CopyFlags,
92 BlockFieldFlags DisposeFlags,
93 const BlockDecl::Capture &CI,
94 const CGBlockInfo::Capture &Capture)
95 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
96 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
97
98 bool operator<(const BlockCaptureManagedEntity &Other) const {
99 return Capture->getOffset() < Other.Capture->getOffset();
100 }
101};
102
103enum class CaptureStrKind {
104 // String for the copy helper.
105 CopyHelper,
106 // String for the dispose helper.
107 DisposeHelper,
108 // Merge the strings for the copy helper and dispose helper.
109 Merged
110};
111
112} // end anonymous namespace
113
114static void findBlockCapturedManagedEntities(
115 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
116 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
117
118static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
119 CaptureStrKind StrKind,
120 CharUnits BlockAlignment,
121 CodeGenModule &CGM);
122
123static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
124 CodeGenModule &CGM) {
125 std::string Name = "__block_descriptor_";
126 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
127
128 if (BlockInfo.needsCopyDisposeHelpers()) {
129 if (CGM.getLangOpts().Exceptions)
130 Name += "e";
131 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
132 Name += "a";
133 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
134
135 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
136 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
137 ManagedCaptures);
138
139 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
140 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
141
142 if (E.CopyKind == E.DisposeKind) {
143 // If CopyKind and DisposeKind are the same, merge the capture
144 // information.
145 assert(E.CopyKind != BlockCaptureEntityKind::None &&
146 "shouldn't see BlockCaptureManagedEntity that is None");
147 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
148 BlockInfo.BlockAlign, CGM);
149 } else {
150 // If CopyKind and DisposeKind are not the same, which can happen when
151 // either Kind is None or the captured object is a __strong block,
152 // concatenate the copy and dispose strings.
153 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
154 BlockInfo.BlockAlign, CGM);
155 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
156 BlockInfo.BlockAlign, CGM);
157 }
158 }
159 Name += "_";
160 }
161
162 std::string TypeAtEncoding =
163 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
164 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
165 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
166 return Name;
167}
168
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000169/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
170/// buildBlockDescriptor is accessed from 5th field of the Block_literal
171/// meta-data and contains stationary information about the block literal.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000172/// Its definition will have 4 (or optionally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000173/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000174/// struct Block_descriptor {
175/// unsigned long reserved;
176/// unsigned long size; // size of Block_literal metadata in bytes.
177/// void *copy_func_helper_decl; // optional copy helper.
178/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000179/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000180/// void *block_layout_info; // encoding of captured block variables.
181/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000182/// \endcode
John McCall351762c2011-02-07 10:33:21 +0000183static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
184 const CGBlockInfo &blockInfo) {
185 ASTContext &C = CGM.getContext();
186
John McCall6c9f1fdb2016-11-19 08:17:24 +0000187 llvm::IntegerType *ulong =
188 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
189 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000190 if (CGM.getLangOpts().OpenCL)
Fangrui Song6907ce22018-07-30 19:24:48 +0000191 i8p =
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000192 llvm::Type::getInt8PtrTy(
193 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
194 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000195 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +0000196
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000197 std::string descName;
198
199 // If an equivalent block descriptor global variable exists, return it.
200 if (C.getLangOpts().ObjC1 &&
201 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
202 descName = getBlockDescriptorName(blockInfo, CGM);
203 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
204 return llvm::ConstantExpr::getBitCast(desc,
205 CGM.getBlockDescriptorType());
206 }
207
208 // If there isn't an equivalent block descriptor global variable, create a new
209 // one.
John McCall23c9dc62016-11-28 22:18:27 +0000210 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000211 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +0000212
213 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +0000214 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +0000215
216 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000217 // FIXME: What is the right way to say this doesn't fit? We should give
218 // a user diagnostic in that case. Better fix would be to change the
219 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000220 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000221
John McCall351762c2011-02-07 10:33:21 +0000222 // Optional copy/dispose helpers.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000223 bool hasInternalHelper = false;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000224 if (blockInfo.needsCopyDisposeHelpers()) {
Mike Stump85284ba2009-02-13 16:19:19 +0000225 // copy_func_helper_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000226 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
227 elements.add(copyHelper);
Mike Stump85284ba2009-02-13 16:19:19 +0000228
229 // destroy_func_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000230 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
231 elements.add(disposeHelper);
232
233 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
234 cast<llvm::Function>(disposeHelper->getOperand(0))
235 ->hasInternalLinkage())
236 hasInternalHelper = true;
Mike Stump85284ba2009-02-13 16:19:19 +0000237 }
238
John McCall351762c2011-02-07 10:33:21 +0000239 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
240 std::string typeAtEncoding =
241 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000242 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000243 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Fangrui Song6907ce22018-07-30 19:24:48 +0000244
John McCall351762c2011-02-07 10:33:21 +0000245 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000246 if (C.getLangOpts().ObjC1) {
247 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000248 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000249 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000250 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000251 }
John McCall351762c2011-02-07 10:33:21 +0000252 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000253 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000254
Joey Goulyddbda402016-08-10 15:57:02 +0000255 unsigned AddrSpace = 0;
256 if (C.getLangOpts().OpenCL)
257 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000258
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000259 llvm::GlobalValue::LinkageTypes linkage;
260 if (descName.empty()) {
261 linkage = llvm::GlobalValue::InternalLinkage;
262 descName = "__block_descriptor_tmp";
263 } else if (hasInternalHelper) {
264 // If either the copy helper or the dispose helper has internal linkage,
265 // the block descriptor must have internal linkage too.
266 linkage = llvm::GlobalValue::InternalLinkage;
267 } else {
268 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
269 }
270
John McCall351762c2011-02-07 10:33:21 +0000271 llvm::GlobalVariable *global =
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000272 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
273 /*constant*/ true, linkage, AddrSpace);
274
275 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
276 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
277 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
278 }
Mike Stump85284ba2009-02-13 16:19:19 +0000279
John McCall351762c2011-02-07 10:33:21 +0000280 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000281}
282
John McCall351762c2011-02-07 10:33:21 +0000283/*
284 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000285
John McCall351762c2011-02-07 10:33:21 +0000286 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
287 struct Block_literal {
288 /// Initialized to one of:
289 /// extern void *_NSConcreteStackBlock[];
290 /// extern void *_NSConcreteGlobalBlock[];
291 ///
292 /// In theory, we could start one off malloc'ed by setting
293 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
294 /// this isa:
295 /// extern void *_NSConcreteMallocBlock[];
296 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000297
John McCall351762c2011-02-07 10:33:21 +0000298 /// These are the flags (with corresponding bit number) that the
299 /// compiler is actually supposed to know about.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000300 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
John McCall351762c2011-02-07 10:33:21 +0000301 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
302 /// descriptor provides copy and dispose helper functions
303 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
304 /// object with a nontrivial destructor or copy constructor
305 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
306 /// as global memory
307 /// 29. BLOCK_USE_STRET - indicates that the block function
308 /// uses stret, which objc_msgSend needs to know about
309 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
310 /// @encoded signature string
311 /// And we're not supposed to manipulate these:
312 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
313 /// to malloc'ed memory
314 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
315 /// to GC-allocated memory
316 /// Additionally, the bottom 16 bits are a reference count which
317 /// should be zero on the stack.
318 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000319
John McCall351762c2011-02-07 10:33:21 +0000320 /// Reserved; should be zero-initialized.
321 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000322
John McCall351762c2011-02-07 10:33:21 +0000323 /// Function pointer generated from block literal.
324 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000325
John McCall351762c2011-02-07 10:33:21 +0000326 /// Block description metadata generated from block literal.
327 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000328
John McCall351762c2011-02-07 10:33:21 +0000329 /// Captured values follow.
330 _CapturesTypes captures...;
331 };
332 */
David Chisnall950a9512009-11-17 19:33:30 +0000333
John McCall351762c2011-02-07 10:33:21 +0000334namespace {
335 /// A chunk of data that we actually have to capture in the block.
336 struct BlockLayoutChunk {
337 CharUnits Alignment;
338 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000339 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000340 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000341 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000342 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000343
John McCall351762c2011-02-07 10:33:21 +0000344 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000345 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000346 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000347 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000348 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000349 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000350
John McCall351762c2011-02-07 10:33:21 +0000351 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000352 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
353 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000354 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000355 info.CXXThisOffset = offset;
356 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000357 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
358 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000359 }
John McCall87fe5d52010-05-20 01:18:31 +0000360 }
John McCall351762c2011-02-07 10:33:21 +0000361 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000362
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000363 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
364 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000365 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000366 if (left.Alignment != right.Alignment)
367 return left.Alignment > right.Alignment;
368
369 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000370 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000371 return 1;
372 if (chunk.Lifetime == Qualifiers::OCL_Strong)
373 return 0;
374 if (chunk.Lifetime == Qualifiers::OCL_Weak)
375 return 2;
376 return 3;
377 };
378
379 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000380 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000381} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000382
John McCallb0a3ecb2011-02-08 03:07:00 +0000383/// Determines if the given type is safe for constant capture in C++.
384static bool isSafeForCXXConstantCapture(QualType type) {
385 const RecordType *recordType =
386 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
387
388 // Only records can be unsafe.
389 if (!recordType) return true;
390
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000391 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000392
393 // Maintain semantics for classes with non-trivial dtors or copy ctors.
394 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000395 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000396
397 // Otherwise, we just have to make sure there aren't any mutable
398 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000399 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000400}
401
John McCall351762c2011-02-07 10:33:21 +0000402/// It is illegal to modify a const object after initialization.
403/// Therefore, if a const object has a constant initializer, we don't
404/// actually need to keep storage for it in the block; we'll just
405/// rematerialize it at the start of the block function. This is
406/// acceptable because we make no promises about address stability of
407/// captured variables.
408static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000409 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000410 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000411 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000412 // rematerialize default arguments of function parameters.
413 if (isa<ParmVarDecl>(var))
414 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000415
John McCall351762c2011-02-07 10:33:21 +0000416 QualType type = var->getType();
417
418 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000419 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000420
John McCallb0a3ecb2011-02-08 03:07:00 +0000421 // Furthermore, in C++ we have to worry about mutable fields:
422 // C++ [dcl.type.cv]p4:
423 // Except that any class member declared mutable can be
424 // modified, any attempt to modify a const object during its
425 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000426 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000427 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000428
429 // If the variable doesn't have any initializer (shouldn't this be
430 // invalid?), it's not clear what we should do. Maybe capture as
431 // zero?
432 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000433 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000434
John McCallde0fe072017-08-15 21:42:52 +0000435 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000436}
437
438/// Get the low bit of a nonzero character count. This is the
439/// alignment of the nth byte if the 0th byte is universally aligned.
440static CharUnits getLowBit(CharUnits v) {
441 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
442}
443
444static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000445 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000446
447 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000448 if (CGM.getLangOpts().OpenCL) {
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000449 // The header is basically 'struct { int; int;
Yaxun Liu10712d92017-10-04 20:32:17 +0000450 // custom_fields; }'. Assert that struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000451 elementTypes.push_back(CGM.IntTy); /* total size */
452 elementTypes.push_back(CGM.IntTy); /* align */
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000453 unsigned Offset = 2 * CGM.getIntSize().getQuantity();
454 unsigned BlockAlign = CGM.getIntAlign().getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000455 if (auto *Helper =
456 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
457 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
458 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
459 // If necessary, add padding fields to the custom fields.
460 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
461 if (BlockAlign < Align)
462 BlockAlign = Align;
463 assert(Offset % Align == 0);
464 Offset += CGM.getDataLayout().getTypeAllocSize(I);
465 elementTypes.push_back(I);
466 }
467 }
468 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
469 info.BlockSize = CharUnits::fromQuantity(Offset);
470 } else {
471 // The header is basically 'struct { void *; int; int; void *; void *; }'.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000472 // Assert that the struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000473 assert(CGM.getIntSize() <= CGM.getPointerSize());
474 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
475 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
476 info.BlockAlign = CGM.getPointerAlign();
477 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
478 elementTypes.push_back(CGM.VoidPtrTy);
479 elementTypes.push_back(CGM.IntTy);
480 elementTypes.push_back(CGM.IntTy);
481 elementTypes.push_back(CGM.VoidPtrTy);
482 elementTypes.push_back(CGM.getBlockDescriptorType());
483 }
John McCall351762c2011-02-07 10:33:21 +0000484}
485
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000486static QualType getCaptureFieldType(const CodeGenFunction &CGF,
487 const BlockDecl::Capture &CI) {
488 const VarDecl *VD = CI.getVariable();
489
490 // If the variable is captured by an enclosing block or lambda expression,
491 // use the type of the capture field.
492 if (CGF.BlockInfo && CI.isNested())
493 return CGF.BlockInfo->getCapture(VD).fieldType();
494 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
495 return FD->getType();
Akira Hatanaka2e00b982018-09-08 20:03:00 +0000496 // If the captured variable is a non-escaping __block variable, the field
497 // type is the reference type. If the variable is a __block variable that
498 // already has a reference type, the field type is the variable's type.
499 return VD->isNonEscapingByref() ?
500 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000501}
502
John McCall351762c2011-02-07 10:33:21 +0000503/// Compute the layout of the given block. Attempts to lay the block
504/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000505static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
506 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000507 ASTContext &C = CGM.getContext();
508 const BlockDecl *block = info.getBlockDecl();
509
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000511 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000512 bool hasNonConstantCustomFields = false;
513 if (auto *OpenCLHelper =
514 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
515 hasNonConstantCustomFields =
516 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
517 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000518 info.StructureType =
519 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
520 info.CanBeGlobal = true;
521 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000522 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000523 else if (C.getLangOpts().ObjC1 &&
524 CGM.getLangOpts().getGC() == LangOptions::NonGC)
525 info.HasCapturedVariableLayout = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000526
John McCall351762c2011-02-07 10:33:21 +0000527 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000529 layout.reserve(block->capturesCXXThis() +
530 (block->capture_end() - block->capture_begin()));
531
532 CharUnits maxFieldAlign;
533
534 // First, 'this'.
535 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000536 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
537 "Can't capture 'this' outside a method");
538 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000539
John McCall7f416cc2015-09-08 08:05:57 +0000540 // Theoretically, this could be in a different address space, so
541 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000542 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000543 std::pair<CharUnits,CharUnits> tinfo
544 = CGM.getContext().getTypeInfoInChars(thisType);
545 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
546
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000547 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
548 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000549 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000550 }
551
552 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000553 for (const auto &CI : block->captures()) {
554 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000555
Akira Hatanaka2e00b982018-09-08 20:03:00 +0000556 if (CI.isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +0000557 // We have to copy/dispose of the __block reference.
558 info.NeedsCopyDispose = true;
559
John McCall351762c2011-02-07 10:33:21 +0000560 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000561 CharUnits align = CGM.getPointerAlign();
562 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000563
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000564 // Since a __block variable cannot be captured by lambdas, its type and
565 // the capture field type should always match.
566 assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
567 "capture type differs from the variable type");
John McCall7f416cc2015-09-08 08:05:57 +0000568 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
569 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000570 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000571 continue;
572 }
573
574 // Otherwise, build a layout chunk with the size and alignment of
575 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000576 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000577 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
578 continue;
579 }
580
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000581 QualType VT = getCaptureFieldType(*CGF, CI);
582
John McCall31168b02011-06-15 23:02:42 +0000583 // If we have a lifetime qualifier, honor it for capture purposes.
584 // That includes *not* copying it if it's __unsafe_unretained.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000585 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000586 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000587 switch (lifetime) {
588 case Qualifiers::OCL_None: llvm_unreachable("impossible");
589 case Qualifiers::OCL_ExplicitNone:
590 case Qualifiers::OCL_Autoreleasing:
591 break;
John McCall351762c2011-02-07 10:33:21 +0000592
John McCall31168b02011-06-15 23:02:42 +0000593 case Qualifiers::OCL_Strong:
594 case Qualifiers::OCL_Weak:
595 info.NeedsCopyDispose = true;
596 }
597
598 // Block pointers require copy/dispose. So do Objective-C pointers.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000599 } else if (VT->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000600 // But honor the inert __unsafe_unretained qualifier, which doesn't
601 // actually make it into the type system.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000602 if (VT->isObjCInertUnsafeUnretainedType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000603 lifetime = Qualifiers::OCL_ExplicitNone;
604 } else {
605 info.NeedsCopyDispose = true;
606 // used for mrr below.
607 lifetime = Qualifiers::OCL_Strong;
608 }
John McCall351762c2011-02-07 10:33:21 +0000609
610 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000611 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000612 info.NeedsCopyDispose = true;
613 info.HasCXXObject = true;
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000614 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
Akira Hatanaka9978da32018-08-10 15:09:24 +0000615 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000616
Akira Hatanaka7275da02018-02-28 07:15:55 +0000617 // So do C structs that require non-trivial copy construction or
618 // destruction.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000619 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
620 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
Akira Hatanaka7275da02018-02-28 07:15:55 +0000621 info.NeedsCopyDispose = true;
622
John McCall351762c2011-02-07 10:33:21 +0000623 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000624 } else if (CGM.getLangOpts().CPlusPlus) {
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000625 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
John McCall351762c2011-02-07 10:33:21 +0000626 if (!record->hasTrivialDestructor()) {
627 info.HasCXXObject = true;
628 info.NeedsCopyDispose = true;
Akira Hatanaka9978da32018-08-10 15:09:24 +0000629 if (!record->isExternallyVisible())
630 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000631 }
632 }
633 }
634
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000635 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000636 CharUnits align = C.getDeclAlign(variable);
Fangrui Song6907ce22018-07-30 19:24:48 +0000637
John McCall351762c2011-02-07 10:33:21 +0000638 maxFieldAlign = std::max(maxFieldAlign, align);
639
Jay Foad7c57be32011-07-11 09:56:20 +0000640 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000641 CGM.getTypes().ConvertTypeForMem(VT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000642
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000643 layout.push_back(
644 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000645 }
646
647 // If that was everything, we're done here.
648 if (layout.empty()) {
649 info.StructureType =
650 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
651 info.CanBeGlobal = true;
652 return;
653 }
654
655 // Sort the layout by alignment. We have to use a stable sort here
656 // to get reproducible results. There should probably be an
657 // llvm::array_pod_stable_sort.
658 std::stable_sort(layout.begin(), layout.end());
Fangrui Song6907ce22018-07-30 19:24:48 +0000659
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000660 // Needed for blocks layout info.
661 info.BlockHeaderForcedGapOffset = info.BlockSize;
662 info.BlockHeaderForcedGapSize = CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +0000663
John McCall351762c2011-02-07 10:33:21 +0000664 CharUnits &blockSize = info.BlockSize;
665 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
666
667 // Assuming that the first byte in the header is maximally aligned,
668 // get the alignment of the first byte following the header.
669 CharUnits endAlign = getLowBit(blockSize);
670
671 // If the end of the header isn't satisfactorily aligned for the
672 // maximum thing, look for things that are okay with the header-end
673 // alignment, and keep appending them until we get something that's
674 // aligned right. This algorithm is only guaranteed optimal if
675 // that condition is satisfied at some point; otherwise we can get
676 // things like:
677 // header // next byte has alignment 4
678 // something_with_size_5; // next byte has alignment 1
679 // something_with_alignment_8;
680 // which has 7 bytes of padding, as opposed to the naive solution
681 // which might have less (?).
682 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000683 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000684 li = layout.begin() + 1, le = layout.end();
685
686 // Look for something that the header end is already
687 // satisfactorily aligned for.
688 for (; li != le && endAlign < li->Alignment; ++li)
689 ;
690
691 // If we found something that's naturally aligned for the end of
692 // the header, keep adding things...
693 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000694 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000695 for (; li != le; ++li) {
696 assert(endAlign >= li->Alignment);
697
John McCall7f416cc2015-09-08 08:05:57 +0000698 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000699 elementTypes.push_back(li->Type);
700 blockSize += li->Size;
701 endAlign = getLowBit(blockSize);
702
703 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000704 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000705 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000706 }
John McCall351762c2011-02-07 10:33:21 +0000707 }
John McCall351762c2011-02-07 10:33:21 +0000708 // Don't re-append everything we just appended.
709 layout.erase(first, li);
710 }
711 }
712
John McCallac0350a2012-04-26 21:14:42 +0000713 assert(endAlign == getLowBit(blockSize));
Fangrui Song6907ce22018-07-30 19:24:48 +0000714
John McCall351762c2011-02-07 10:33:21 +0000715 // At this point, we just have to add padding if the end align still
716 // isn't aligned right.
717 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000718 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000719 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000720
John McCall7f416cc2015-09-08 08:05:57 +0000721 // If we haven't yet added any fields, remember that there was an
722 // initial gap; this need to go into the block layout bit map.
723 if (blockSize == info.BlockHeaderForcedGapOffset) {
724 info.BlockHeaderForcedGapSize = padding;
725 }
726
John McCalle3dc1702011-02-15 09:22:45 +0000727 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
728 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000729 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000730 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000731 }
732
John McCall1db0a2f2012-05-01 20:28:00 +0000733 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000734 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000735 // Slam everything else on now. This works because they have
736 // strictly decreasing alignment and we expect that size is always a
737 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000738 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000739 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000740 if (endAlign < li->Alignment) {
741 // size may not be multiple of alignment. This can only happen with
742 // an over-aligned variable. We will be adding a padding field to
743 // make the size be multiple of alignment.
744 CharUnits padding = li->Alignment - endAlign;
745 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
746 padding.getQuantity()));
747 blockSize += padding;
748 endAlign = getLowBit(blockSize);
749 }
John McCall351762c2011-02-07 10:33:21 +0000750 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000751 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000752 elementTypes.push_back(li->Type);
753 blockSize += li->Size;
754 endAlign = getLowBit(blockSize);
755 }
756
757 info.StructureType =
758 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
759}
760
John McCall08ef4662011-11-10 08:15:53 +0000761/// Enter the scope of a block. This should be run at the entrance to
762/// a full-expression so that the block's cleanups are pushed at the
763/// right place in the stack.
764static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000765 assert(CGF.HaveInsertPoint());
766
John McCall08ef4662011-11-10 08:15:53 +0000767 // Allocate the block info and place it at the head of the list.
768 CGBlockInfo &blockInfo =
769 *new CGBlockInfo(block, CGF.CurFn->getName());
770 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
771 CGF.FirstBlockInfo = &blockInfo;
772
773 // Compute information about the layout, etc., of this block,
774 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000775 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000776
777 // Nothing else to do if it can be global.
778 if (blockInfo.CanBeGlobal) return;
779
780 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000781 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
782 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000783
784 // If there are cleanups to emit, enter them (but inactive).
785 if (!blockInfo.NeedsCopyDispose) return;
786
787 // Walk through the captures (in order) and find the ones not
788 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000789 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000790 // Ignore __block captures; there's nothing special in the
791 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000792 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000793
794 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000795 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000796 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
797 if (capture.isConstant()) continue;
798
799 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000800 QualType VT = getCaptureFieldType(CGF, CI);
801 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000802 if (dtorKind == QualType::DK_none) continue;
803
804 CodeGenFunction::Destroyer *destroyer;
805
806 // Block captures count as local values and have imprecise semantics.
807 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000808 //
809 // For const-qualified captures, emit clang.arc.use to ensure the captured
810 // object doesn't get released while we are still depending on its validity
811 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000812 if (VT.isConstQualified() &&
813 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
814 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
815 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
816 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000817 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000818 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000819 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000820 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000821 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000822 }
823
824 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000825 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
826 capture.getIndex(),
827 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000828
John McCallf4beacd2011-11-10 10:43:54 +0000829 // We can use that GEP as the dominating IP.
830 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000831 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000832
John McCall08ef4662011-11-10 08:15:53 +0000833 CleanupKind cleanupKind = InactiveNormalCleanup;
834 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
Fangrui Song6907ce22018-07-30 19:24:48 +0000835 if (useArrayEHCleanup)
John McCall08ef4662011-11-10 08:15:53 +0000836 cleanupKind = InactiveNormalAndEHCleanup;
837
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000838 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000839 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000840
841 // Remember where that cleanup was.
842 capture.setCleanup(CGF.EHStack.stable_begin());
843 }
844}
845
846/// Enter a full-expression with a non-trivial number of objects to
847/// clean up. This is in this file because, at the moment, the only
848/// kind of cleanup object is a BlockDecl*.
849void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
850 assert(E->getNumObjects() != 0);
George Burgess IV8b93a592018-03-02 20:10:38 +0000851 for (const ExprWithCleanups::CleanupObject &C : E->getObjects())
852 enterBlockScope(*this, C);
John McCall08ef4662011-11-10 08:15:53 +0000853}
854
855/// Find the layout for the given block in a linked list and remove it.
856static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
857 const BlockDecl *block) {
858 while (true) {
859 assert(head && *head);
860 CGBlockInfo *cur = *head;
861
862 // If this is the block we're looking for, splice it out of the list.
863 if (cur->getBlockDecl() == block) {
864 *head = cur->NextBlockInfo;
865 return cur;
866 }
867
868 head = &cur->NextBlockInfo;
869 }
870}
871
872/// Destroy a chain of block layouts.
873void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
874 assert(head && "destroying an empty chain");
875 do {
876 CGBlockInfo *cur = head;
877 head = cur->NextBlockInfo;
878 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000879 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000880}
881
John McCall351762c2011-02-07 10:33:21 +0000882/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000883llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000884 // If the block has no captures, we won't have a pre-computed
885 // layout for it.
886 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000887 // The block literal is emitted as a global variable, and the block invoke
888 // function has to be extracted from its initializer.
889 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
George Burgess IVe3763372016-12-22 02:50:20 +0000890 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000891 }
John McCall08ef4662011-11-10 08:15:53 +0000892 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000893 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000894 blockInfo.BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000895 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000896 }
John McCall351762c2011-02-07 10:33:21 +0000897
John McCall08ef4662011-11-10 08:15:53 +0000898 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000899 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000900 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
901 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000902
John McCall08ef4662011-11-10 08:15:53 +0000903 blockInfo->BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000904 return EmitBlockLiteral(*blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000905}
906
Yaxun Liufa13d012018-02-15 16:39:19 +0000907llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000908 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
John McCall08ef4662011-11-10 08:15:53 +0000909 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000910 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000911 CodeGenFunction BlockCGF{CGM, true};
912 BlockCGF.SanOpts = SanOpts;
913 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000914 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
John McCall351762c2011-02-07 10:33:21 +0000915
916 // If there is nothing to capture, we can emit this as a global block.
917 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000918 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000919
920 // Otherwise, we have to emit this as a local block.
921
John McCall7f416cc2015-09-08 08:05:57 +0000922 Address blockAddr = blockInfo.LocalAddress;
923 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000924
Yaxun Liu10712d92017-10-04 20:32:17 +0000925 llvm::Constant *isa;
926 llvm::Constant *descriptor;
927 BlockFlags flags;
928 if (!IsOpenCL) {
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000929 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
930 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
931 // block just returns the original block and releasing it is a no-op.
932 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
933 ? CGM.getNSConcreteGlobalBlock()
934 : CGM.getNSConcreteStackBlock();
935 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
Yaxun Liu10712d92017-10-04 20:32:17 +0000936
937 // Build the block descriptor.
938 descriptor = buildBlockDescriptor(CGM, blockInfo);
939
940 // Compute the initial on-stack block flags.
941 flags = BLOCK_HAS_SIGNATURE;
942 if (blockInfo.HasCapturedVariableLayout)
943 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000944 if (blockInfo.needsCopyDisposeHelpers())
Yaxun Liu10712d92017-10-04 20:32:17 +0000945 flags |= BLOCK_HAS_COPY_DISPOSE;
946 if (blockInfo.HasCXXObject)
947 flags |= BLOCK_HAS_CXX_OBJ;
948 if (blockInfo.UsesStret)
949 flags |= BLOCK_USE_STRET;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000950 if (blockInfo.getBlockDecl()->doesNotEscape())
951 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
Yaxun Liu10712d92017-10-04 20:32:17 +0000952 }
John McCall351762c2011-02-07 10:33:21 +0000953
John McCall7f416cc2015-09-08 08:05:57 +0000954 auto projectField =
955 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
956 return Builder.CreateStructGEP(blockAddr, index, offset, name);
957 };
958 auto storeField =
959 [&](llvm::Value *value, unsigned index, CharUnits offset,
960 const Twine &name) {
961 Builder.CreateStore(value, projectField(index, offset, name));
962 };
963
964 // Initialize the block header.
965 {
966 // We assume all the header fields are densely packed.
967 unsigned index = 0;
968 CharUnits offset;
969 auto addHeaderField =
970 [&](llvm::Value *value, CharUnits size, const Twine &name) {
971 storeField(value, index, offset, name);
972 offset += size;
973 index++;
974 };
975
Yaxun Liu10712d92017-10-04 20:32:17 +0000976 if (!IsOpenCL) {
977 addHeaderField(isa, getPointerSize(), "block.isa");
978 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
979 getIntSize(), "block.flags");
980 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
981 "block.reserved");
982 } else {
983 addHeaderField(
984 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
985 getIntSize(), "block.size");
986 addHeaderField(
987 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
988 getIntSize(), "block.align");
989 }
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000990 if (!IsOpenCL) {
991 addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
992 getPointerSize(), "block.invoke");
Yaxun Liu10712d92017-10-04 20:32:17 +0000993 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000994 } else if (auto *Helper =
995 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000996 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
997 addHeaderField(
998 I.first,
999 CharUnits::fromQuantity(
1000 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
1001 I.second);
1002 }
1003 }
John McCall7f416cc2015-09-08 08:05:57 +00001004 }
John McCall351762c2011-02-07 10:33:21 +00001005
1006 // Finally, capture all the values into the block.
1007 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1008
1009 // First, 'this'.
1010 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001011 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
1012 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +00001013 Builder.CreateStore(LoadCXXThis(), addr);
1014 }
1015
1016 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001017 for (const auto &CI : blockDecl->captures()) {
1018 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001019 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1020
1021 // Ignore constant captures.
1022 if (capture.isConstant()) continue;
1023
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001024 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +00001025
1026 // This will be a [[type]]*, except that a byref entry will just be
1027 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +00001028 Address blockField =
1029 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +00001030
1031 // Compute the address of the thing we're going to move into the
1032 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +00001033 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +00001034
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001035 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00001036 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +00001037 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001038 src = Address::invalid();
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001039 } else if (CI.isEscapingByref()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001040 if (BlockInfo && CI.isNested()) {
1041 // We need to use the capture from the enclosing block.
1042 const CGBlockInfo::Capture &enclosingCapture =
1043 BlockInfo->getCapture(variable);
1044
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001045 // This is a [[type]]*, except that a byref entry will just be an i8**.
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001046 src = Builder.CreateStructGEP(LoadBlockStruct(),
1047 enclosingCapture.getIndex(),
1048 enclosingCapture.getOffset(),
1049 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +00001050 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001051 auto I = LocalDeclMap.find(variable);
1052 assert(I != LocalDeclMap.end());
1053 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +00001054 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001055 } else {
1056 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
1057 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1058 type.getNonReferenceType(), VK_LValue,
1059 SourceLocation());
1060 src = EmitDeclRefLValue(&declRef).getAddress();
1061 };
John McCall351762c2011-02-07 10:33:21 +00001062
1063 // For byrefs, we just write the pointer to the byref struct into
1064 // the block field. There's no need to chase the forwarding
1065 // pointer at this point, since we're building something that will
1066 // live a shorter life than the stack byref anyway.
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001067 if (CI.isEscapingByref()) {
John McCalle3dc1702011-02-15 09:22:45 +00001068 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +00001069 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001070 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +00001071 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +00001072 else
John McCall7f416cc2015-09-08 08:05:57 +00001073 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001074
John McCalle3dc1702011-02-15 09:22:45 +00001075 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +00001076 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +00001077
1078 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001079 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00001080 if (blockDecl->isConversionFromLambda()) {
1081 // If we have a lambda conversion, emit the expression
1082 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +00001083 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +00001084 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +00001085 AggValueSlot::IsDestructed,
1086 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001087 AggValueSlot::IsNotAliased,
1088 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001089 EmitAggExpr(copyExpr, Slot);
1090 } else {
1091 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
1092 }
John McCall351762c2011-02-07 10:33:21 +00001093
1094 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001095 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001096 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +00001097
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00001098 // If type is const-qualified, copy the value into the block field.
1099 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +00001100 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1101 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00001102 llvm::Value *value = Builder.CreateLoad(src, "captured");
1103 Builder.CreateStore(value, blockField);
1104
John McCall4d14a902013-04-08 23:27:49 +00001105 // If this is an ARC __strong block-pointer variable, don't do a
1106 // block copy.
1107 //
1108 // TODO: this can be generalized into the normal initialization logic:
1109 // we should never need to do a block-copy when initializing a local
1110 // variable, because the local variable's lifetime should be strictly
1111 // contained within the stack block's.
1112 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1113 type->isBlockPointerType()) {
1114 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +00001115 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +00001116 value = EmitARCRetainNonBlock(value);
1117
1118 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +00001119 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +00001120
1121 // Otherwise, fake up a POD copy into the block field.
1122 } else {
John McCall31168b02011-06-15 23:02:42 +00001123 // Fake up a new variable so that EmitScalarInit doesn't think
1124 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +00001125 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1126 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +00001127
John McCall93be3f72011-02-07 18:37:40 +00001128 // We use one of these or the other depending on whether the
1129 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001130 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
1131 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1132 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +00001133
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001134 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +00001135 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +00001136 // FIXME: Pass a specific location for the expr init so that the store is
1137 // attributed to a reasonable location - otherwise it may be attributed to
1138 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +00001139 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001140 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +00001141 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +00001142 }
1143
John McCall08ef4662011-11-10 08:15:53 +00001144 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001145 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +00001146 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1147 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +00001148 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +00001149 }
John McCall351762c2011-02-07 10:33:21 +00001150 }
1151
1152 // Cast to the converted block-pointer type, which happens (somewhat
1153 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001154 llvm::Value *result = Builder.CreatePointerCast(
1155 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001156
Yaxun Liufa13d012018-02-15 16:39:19 +00001157 if (IsOpenCL) {
1158 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1159 result);
1160 }
1161
John McCall351762c2011-02-07 10:33:21 +00001162 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001163}
1164
1165
Chris Lattnera5f58b02011-07-09 17:41:47 +00001166llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001167 if (BlockDescriptorType)
1168 return BlockDescriptorType;
1169
Chris Lattnera5f58b02011-07-09 17:41:47 +00001170 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001171 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001172
Mike Stump650c9322009-02-13 15:16:56 +00001173 // struct __block_descriptor {
1174 // unsigned long reserved;
1175 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001176 //
1177 // // later, the following will be added
1178 //
1179 // struct {
1180 // void (*copyHelper)();
1181 // void (*copyHelper)();
1182 // } helpers; // !!! optional
1183 //
1184 // const char *signature; // the block signature
1185 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001186 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001187 BlockDescriptorType = llvm::StructType::create(
1188 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001189
John McCall351762c2011-02-07 10:33:21 +00001190 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001191 unsigned AddrSpace = 0;
1192 if (getLangOpts().OpenCL)
1193 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1194 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001195 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001196}
1197
Chris Lattnera5f58b02011-07-09 17:41:47 +00001198llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001199 assert(!getLangOpts().OpenCL && "OpenCL does not need this");
1200
Mike Stump005c9a62009-02-13 15:25:34 +00001201 if (GenericBlockLiteralType)
1202 return GenericBlockLiteralType;
1203
Chris Lattnera5f58b02011-07-09 17:41:47 +00001204 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001205
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001206 // struct __block_literal_generic {
1207 // void *__isa;
1208 // int __flags;
1209 // int __reserved;
1210 // void (*__invoke)(void *);
1211 // struct __block_descriptor *__descriptor;
1212 // };
1213 GenericBlockLiteralType =
1214 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1215 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001216
Mike Stump005c9a62009-02-13 15:25:34 +00001217 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001218}
1219
Yaxun Liu10712d92017-10-04 20:32:17 +00001220RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001221 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001222 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001223 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001224
John McCallb92ab1a2016-10-26 23:46:34 +00001225 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Erich Keaneed69e1b2018-08-03 18:08:36 +00001226 llvm::Value *FuncPtr = nullptr;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001227
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001228 if (!CGM.getLangOpts().OpenCL) {
1229 // Get a pointer to the generic block literal.
1230 llvm::Type *BlockLiteralTy =
1231 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), 0);
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001232
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001233 // Bitcast the callee to a block literal.
1234 BlockPtr =
1235 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001236
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001237 // Get the function pointer from the literal.
1238 FuncPtr =
1239 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
1240 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001241
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001242 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001243 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001244
1245 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1246 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1247 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001248 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001249 VoidPtrQualTy =
1250 getContext().getPointerType(getContext().getAddrSpaceQualType(
1251 getContext().VoidTy, LangAS::opencl_generic));
1252 }
1253
1254 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1255 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001256
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001257 QualType FnType = BPT->getPointeeType();
1258
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001259 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001260 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001261
Anders Carlsson5f50c652009-04-07 22:10:22 +00001262 // Load the function.
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001263 llvm::Value *Func;
1264 if (CGM.getLangOpts().OpenCL)
1265 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1266 else
1267 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001268
John McCall85915252011-03-09 08:39:33 +00001269 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001270 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001271 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Anders Carlsson5f50c652009-04-07 22:10:22 +00001273 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001274 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattner2192fe52011-07-18 04:24:23 +00001276 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001277 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001278
John McCallb92ab1a2016-10-26 23:46:34 +00001279 // Prepare the callee.
1280 CGCallee Callee(CGCalleeInfo(), Func);
1281
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001282 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001283 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001284}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001285
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001286Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
John McCall351762c2011-02-07 10:33:21 +00001287 assert(BlockInfo && "evaluating block ref without block information?");
1288 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001289
John McCall351762c2011-02-07 10:33:21 +00001290 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001291 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001292
John McCall7f416cc2015-09-08 08:05:57 +00001293 Address addr =
1294 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1295 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001296
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001297 if (variable->isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +00001298 // addr should be a void** right now. Load, then cast the result
1299 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001300
John McCall7f416cc2015-09-08 08:05:57 +00001301 auto &byrefInfo = getBlockByrefInfo(variable);
1302 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001303
John McCall7f416cc2015-09-08 08:05:57 +00001304 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1305 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001306
John McCall7f416cc2015-09-08 08:05:57 +00001307 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1308 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001309 }
1310
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001311 assert((!variable->isNonEscapingByref() ||
1312 capture.fieldType()->isReferenceType()) &&
1313 "the capture field of a non-escaping variable should have a "
1314 "reference type");
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001315 if (capture.fieldType()->isReferenceType())
1316 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001317
John McCall351762c2011-02-07 10:33:21 +00001318 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001319}
1320
George Burgess IVe3763372016-12-22 02:50:20 +00001321void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1322 llvm::Constant *Addr) {
1323 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1324 (void)Ok;
1325 assert(Ok && "Trying to replace an already-existing global block!");
1326}
1327
Mike Stump2d5a2872009-02-14 22:16:35 +00001328llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001329CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1330 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001331 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1332 return Block;
1333
George Burgess IV70d15b32016-11-03 02:21:43 +00001334 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1335 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001336
John McCall351762c2011-02-07 10:33:21 +00001337 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001338 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001339
John McCall351762c2011-02-07 10:33:21 +00001340 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001341 {
John McCall7f416cc2015-09-08 08:05:57 +00001342 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001343 CodeGenFunction(*this).GenerateBlockFunction(
1344 GlobalDecl(), blockInfo, LocalDeclMap,
1345 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001346 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001347
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001348 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001349}
1350
John McCall351762c2011-02-07 10:33:21 +00001351static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1352 const CGBlockInfo &blockInfo,
1353 llvm::Constant *blockFn) {
1354 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001355 // Callers should detect this case on their own: calling this function
1356 // generally requires computing layout information, which is a waste of time
1357 // if we've already emitted this block.
1358 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1359 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001360
1361 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001362 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001363 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001364
Yaxun Liu10712d92017-10-04 20:32:17 +00001365 bool IsOpenCL = CGM.getLangOpts().OpenCL;
David Chisnallc5a458c2018-08-09 08:02:42 +00001366 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
Yaxun Liu10712d92017-10-04 20:32:17 +00001367 if (!IsOpenCL) {
1368 // isa
David Chisnallc5a458c2018-08-09 08:02:42 +00001369 if (IsWindows)
1370 fields.addNullPointer(CGM.Int8PtrPtrTy);
1371 else
1372 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001373
Yaxun Liu10712d92017-10-04 20:32:17 +00001374 // __flags
1375 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1376 if (blockInfo.UsesStret)
1377 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001378
Yaxun Liu10712d92017-10-04 20:32:17 +00001379 fields.addInt(CGM.IntTy, flags.getBitMask());
1380
1381 // Reserved
1382 fields.addInt(CGM.IntTy, 0);
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001383
1384 // Function
1385 fields.add(blockFn);
Yaxun Liu10712d92017-10-04 20:32:17 +00001386 } else {
1387 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1388 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1389 }
John McCall351762c2011-02-07 10:33:21 +00001390
Yaxun Liu10712d92017-10-04 20:32:17 +00001391 if (!IsOpenCL) {
1392 // Descriptor
1393 fields.add(buildBlockDescriptor(CGM, blockInfo));
1394 } else if (auto *Helper =
1395 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1396 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1397 fields.add(I);
1398 }
1399 }
John McCall351762c2011-02-07 10:33:21 +00001400
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001401 unsigned AddrSpace = 0;
1402 if (CGM.getContext().getLangOpts().OpenCL)
1403 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1404
1405 llvm::Constant *literal = fields.finishAndCreateGlobal(
1406 "__block_literal_global", blockInfo.BlockAlign,
David Chisnallc5a458c2018-08-09 08:02:42 +00001407 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1408
1409 // Windows does not allow globals to be initialised to point to globals in
1410 // different DLLs. Any such variables must run code to initialise them.
1411 if (IsWindows) {
1412 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1413 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1414 &CGM.getModule());
1415 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1416 Init));
1417 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1418 b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1419 b.CreateRetVoid();
1420 // We can't use the normal LLVM global initialisation array, because we
1421 // need to specify that this runs early in library initialisation.
1422 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1423 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1424 Init, ".block_isa_init_ptr");
1425 InitVar->setSection(".CRT$XCLa");
1426 CGM.addUsedGlobal(InitVar);
1427 }
John McCall351762c2011-02-07 10:33:21 +00001428
1429 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001430 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001431 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001432 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001433 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001434 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001435 if (CGM.getContext().getLangOpts().OpenCL)
1436 CGM.getOpenCLRuntime().recordBlockInfo(
1437 blockInfo.BlockExpression,
1438 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001439 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001440}
1441
John McCall7f416cc2015-09-08 08:05:57 +00001442void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1443 unsigned argNum,
1444 llvm::Value *arg) {
1445 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1446
Adrian Prantl356347b2017-10-26 20:08:52 +00001447 // Allocate a stack slot like for any local variable to guarantee optimal
1448 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1449 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1450 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001451 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001452 if (CGM.getCodeGenOpts().getDebugInfo() >=
1453 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001454 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001455 DI->EmitDeclareOfBlockLiteralArgVariable(
1456 *BlockInfo, D->getName(), argNum,
1457 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001458 }
1459 }
1460
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001461 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
John McCall7f416cc2015-09-08 08:05:57 +00001462 ApplyDebugLocation Scope(*this, StartLoc);
1463
1464 // Instead of messing around with LocalDeclMap, just set the value
1465 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001466 BlockPointer = Builder.CreatePointerCast(
1467 arg,
1468 BlockInfo->StructureType->getPointerTo(
1469 getContext().getLangOpts().OpenCL
1470 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1471 : 0),
1472 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001473}
1474
1475Address CodeGenFunction::LoadBlockStruct() {
1476 assert(BlockInfo && "not in a block invocation function!");
1477 assert(BlockPointer && "no block pointer set!");
1478 return Address(BlockPointer, BlockInfo->BlockAlign);
1479}
1480
Mike Stump4446dcf2009-03-05 08:32:30 +00001481llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001482CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1483 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001484 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001485 bool IsLambdaConversionToBlock,
1486 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001487 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001488
Fariborz Jahanian63628032012-06-26 16:06:38 +00001489 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001490
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001491 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001492
John McCall351762c2011-02-07 10:33:21 +00001493 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001494
Mike Stump5469f292009-03-13 23:34:28 +00001495 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001496 // to be local to this function as well, in case they're directly
1497 // referenced in a block.
1498 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001499 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001500 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001501 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001502 }
1503
John McCall351762c2011-02-07 10:33:21 +00001504 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001505
John McCall351762c2011-02-07 10:33:21 +00001506 // Build the argument list.
1507 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001508
John McCall351762c2011-02-07 10:33:21 +00001509 // The first argument is the block pointer. Just take it as a void*
1510 // and cast it later.
1511 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001512
1513 // For OpenCL passed block pointer can be private AS local variable or
1514 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001515 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001516 // generic AS in one implementation.
1517 if (getLangOpts().OpenCL)
1518 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1519 getContext().VoidTy, LangAS::opencl_generic));
1520
Mike Stump7fe9cc12009-10-21 03:49:08 +00001521 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001522
Alexey Bataev56223232017-06-09 13:40:18 +00001523 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1524 SourceLocation(), II, selfTy,
1525 ImplicitParamDecl::ObjCSelf);
1526 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001527
John McCall351762c2011-02-07 10:33:21 +00001528 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001529 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001530
John McCall351762c2011-02-07 10:33:21 +00001531 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001532 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001533 const CGFunctionInfo &fnInfo =
1534 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001535 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001536 blockInfo.UsesStret = true;
1537
John McCalla729c622012-02-17 03:33:10 +00001538 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001539
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001540 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001541 llvm::Function *fn = llvm::Function::Create(
1542 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001543 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001544
Yaxun Liu10712d92017-10-04 20:32:17 +00001545 if (BuildGlobalBlock) {
1546 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1547 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1548 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001549 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001550 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1551 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001552
John McCall351762c2011-02-07 10:33:21 +00001553 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001554 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001555 blockDecl->getLocation(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001556 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
Mike Stumpb7074c02009-02-13 15:32:32 +00001557
John McCall147d0212011-02-22 22:38:33 +00001558 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001559
Adrian Prantl0f6df002013-03-29 19:20:35 +00001560 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1561 // won't delete the dbg.declare intrinsics for captured variables.
1562 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1563 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1564 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001565 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1566 getPointerAlign(),
1567 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001568 // Set the DebugLocation to empty, so the store is recognized as a
1569 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001570 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001571 Builder.CreateStore(BlockPointer, Alloca);
1572 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001573 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001574
John McCall87fe5d52010-05-20 01:18:31 +00001575 // If we have a C++ 'this' reference, go ahead and force it into
1576 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001577 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001578 Address addr =
1579 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1580 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001581 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001582 }
1583
John McCall351762c2011-02-07 10:33:21 +00001584 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001585 for (const auto &CI : blockDecl->captures()) {
1586 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001587 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1588 if (!capture.isConstant()) continue;
1589
John McCall7f416cc2015-09-08 08:05:57 +00001590 CharUnits align = getContext().getDeclAlign(variable);
1591 Address alloca =
1592 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001593
John McCall7f416cc2015-09-08 08:05:57 +00001594 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001595
John McCall7f416cc2015-09-08 08:05:57 +00001596 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001597 }
1598
John McCall113bee02012-03-10 09:33:50 +00001599 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001600 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1601 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1602 --entry_ptr;
1603
Eli Friedman2495ab02012-02-25 02:48:22 +00001604 if (IsLambdaConversionToBlock)
1605 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001606 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001607 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001608 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001609 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001610 }
Mike Stump017460a2009-10-01 22:29:41 +00001611
Mike Stump7d699112009-10-01 00:27:30 +00001612 // Remember where we were...
1613 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001614
Mike Stump7d699112009-10-01 00:27:30 +00001615 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001616 ++entry_ptr;
1617 Builder.SetInsertPoint(entry, entry_ptr);
1618
John McCall113bee02012-03-10 09:33:50 +00001619 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001620 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001621 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001622 for (const auto &CI : blockDecl->captures()) {
1623 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001624 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001625
Benjamin Kramer8c305922016-02-02 11:06:51 +00001626 if (CGM.getCodeGenOpts().getDebugInfo() >=
1627 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001628 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1629 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001630 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001631 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1632 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001633 continue;
1634 }
John McCall351762c2011-02-07 10:33:21 +00001635
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001636 DI->EmitDeclareOfBlockDeclRefVariable(
1637 variable, BlockPointerDbgLoc, Builder, blockInfo,
1638 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001639 }
Mike Stump2e722b92009-09-30 02:43:10 +00001640 }
Manman Renab08a9a2013-01-04 18:51:35 +00001641 // Recover location if it was changed in the above loop.
1642 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001643 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001644 }
John McCall351762c2011-02-07 10:33:21 +00001645
Mike Stump7d699112009-10-01 00:27:30 +00001646 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001647 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001648 Builder.ClearInsertionPoint();
1649 else
1650 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001651
John McCall351762c2011-02-07 10:33:21 +00001652 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001653
John McCall351762c2011-02-07 10:33:21 +00001654 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001655}
Mike Stump1db7d042009-02-28 09:07:16 +00001656
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001657static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1658computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1659 const LangOptions &LangOpts) {
1660 if (CI.getCopyExpr()) {
1661 assert(!CI.isByRef());
1662 // don't bother computing flags
1663 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1664 }
1665 BlockFieldFlags Flags;
Akira Hatanaka2e00b982018-09-08 20:03:00 +00001666 if (CI.isEscapingByref()) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001667 Flags = BLOCK_FIELD_IS_BYREF;
1668 if (T.isObjCGCWeak())
1669 Flags |= BLOCK_FIELD_IS_WEAK;
1670 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1671 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001672
1673 Flags = BLOCK_FIELD_IS_OBJECT;
1674 bool isBlockPointer = T->isBlockPointerType();
1675 if (isBlockPointer)
1676 Flags = BLOCK_FIELD_IS_BLOCK;
1677
Akira Hatanaka7275da02018-02-28 07:15:55 +00001678 switch (T.isNonTrivialToPrimitiveCopy()) {
1679 case QualType::PCK_Struct:
1680 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1681 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001682 case QualType::PCK_ARCWeak:
1683 // We need to register __weak direct captures with the runtime.
1684 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001685 case QualType::PCK_ARCStrong:
1686 // We need to retain the copied value for __strong direct captures.
1687 // If it's a block pointer, we have to copy the block and assign that to
1688 // the destination pointer, so we might as well use _Block_object_assign.
1689 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001690 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1691 : BlockCaptureEntityKind::BlockObject,
1692 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001693 case QualType::PCK_Trivial:
1694 case QualType::PCK_VolatileTrivial: {
1695 if (!T->isObjCRetainableType())
1696 // For all other types, the memcpy is fine.
1697 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1698
1699 // Special rules for ARC captures:
1700 Qualifiers QS = T.getQualifiers();
1701
Akira Hatanaka7275da02018-02-28 07:15:55 +00001702 // Non-ARC captures of retainable pointers are strong and
1703 // therefore require a call to _Block_object_assign.
1704 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1705 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1706
1707 // Otherwise the memcpy is fine.
1708 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001709 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001710 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001711 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001712}
1713
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001714static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1715computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1716 const LangOptions &LangOpts);
1717
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001718/// Find the set of block captures that need to be explicitly copied or destroy.
1719static void findBlockCapturedManagedEntities(
1720 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001721 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001722 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1723 const VarDecl *Variable = CI.getVariable();
1724 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1725 if (Capture.isConstant())
1726 continue;
1727
Akira Hatanaka2a5e4632018-08-22 13:41:19 +00001728 QualType VT = Capture.fieldType();
1729 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1730 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001731 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1732 DisposeInfo.first != BlockCaptureEntityKind::None)
1733 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1734 CopyInfo.second, DisposeInfo.second, CI,
1735 Capture);
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001736 }
Akira Hatanaka9978da32018-08-10 15:09:24 +00001737
1738 // Sort the captures by offset.
1739 llvm::sort(ManagedCaptures.begin(), ManagedCaptures.end());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001740}
1741
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001742namespace {
1743/// Release a __block variable.
1744struct CallBlockRelease final : EHScopeStack::Cleanup {
1745 Address Addr;
1746 BlockFieldFlags FieldFlags;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001747 bool LoadBlockVarAddr, CanThrow;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001748
Akira Hatanaka9978da32018-08-10 15:09:24 +00001749 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1750 bool CT)
1751 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1752 CanThrow(CT) {}
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001753
1754 void Emit(CodeGenFunction &CGF, Flags flags) override {
1755 llvm::Value *BlockVarAddr;
1756 if (LoadBlockVarAddr) {
1757 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1758 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1759 } else {
1760 BlockVarAddr = Addr.getPointer();
1761 }
1762
Akira Hatanaka9978da32018-08-10 15:09:24 +00001763 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001764 }
1765};
1766} // end anonymous namespace
1767
Akira Hatanaka9978da32018-08-10 15:09:24 +00001768/// Check if \p T is a C++ class that has a destructor that can throw.
1769bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1770 if (const auto *RD = T->getAsCXXRecordDecl())
1771 if (const CXXDestructorDecl *DD = RD->getDestructor())
1772 return DD->getType()->getAs<FunctionProtoType>()->canThrow();
1773 return false;
1774}
1775
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001776// Return a string that has the information about a capture.
1777static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1778 CaptureStrKind StrKind,
1779 CharUnits BlockAlignment,
1780 CodeGenModule &CGM) {
1781 std::string Str;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001782 ASTContext &Ctx = CGM.getContext();
1783 std::unique_ptr<ItaniumMangleContext> MC(
1784 ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics()));
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001785 const BlockDecl::Capture &CI = *E.CI;
1786 QualType CaptureTy = CI.getVariable()->getType();
Akira Hatanaka9978da32018-08-10 15:09:24 +00001787
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001788 BlockCaptureEntityKind Kind;
1789 BlockFieldFlags Flags;
1790
1791 // CaptureStrKind::Merged should be passed only when the operations and the
1792 // flags are the same for copy and dispose.
1793 assert((StrKind != CaptureStrKind::Merged ||
1794 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1795 "different operations and flags");
1796
1797 if (StrKind == CaptureStrKind::DisposeHelper) {
1798 Kind = E.DisposeKind;
1799 Flags = E.DisposeFlags;
1800 } else {
1801 Kind = E.CopyKind;
1802 Flags = E.CopyFlags;
1803 }
1804
1805 switch (Kind) {
1806 case BlockCaptureEntityKind::CXXRecord: {
1807 Str += "c";
1808 SmallString<256> TyStr;
1809 llvm::raw_svector_ostream Out(TyStr);
1810 MC->mangleTypeName(CaptureTy, Out);
1811 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1812 break;
1813 }
1814 case BlockCaptureEntityKind::ARCWeak:
1815 Str += "w";
1816 break;
1817 case BlockCaptureEntityKind::ARCStrong:
1818 Str += "s";
1819 break;
1820 case BlockCaptureEntityKind::BlockObject: {
1821 const VarDecl *Var = CI.getVariable();
1822 unsigned F = Flags.getBitMask();
1823 if (F & BLOCK_FIELD_IS_BYREF) {
1824 Str += "r";
1825 if (F & BLOCK_FIELD_IS_WEAK)
1826 Str += "w";
1827 else {
1828 // If CaptureStrKind::Merged is passed, check both the copy expression
1829 // and the destructor.
1830 if (StrKind != CaptureStrKind::DisposeHelper) {
1831 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1832 Str += "c";
1833 }
1834 if (StrKind != CaptureStrKind::CopyHelper) {
1835 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1836 Str += "d";
1837 }
1838 }
1839 } else {
1840 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1841 if (F == BLOCK_FIELD_IS_BLOCK)
1842 Str += "b";
1843 else
1844 Str += "o";
1845 }
1846 break;
1847 }
1848 case BlockCaptureEntityKind::NonTrivialCStruct: {
1849 bool IsVolatile = CaptureTy.isVolatileQualified();
1850 CharUnits Alignment =
1851 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1852
1853 Str += "n";
1854 std::string FuncStr;
1855 if (StrKind == CaptureStrKind::DisposeHelper)
1856 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1857 CaptureTy, Alignment, IsVolatile, Ctx);
1858 else
1859 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1860 // It has all the information that the destructor string has.
1861 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1862 CaptureTy, Alignment, IsVolatile, Ctx);
1863 // The underscore is necessary here because non-trivial copy constructor
1864 // and destructor strings can start with a number.
1865 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1866 break;
1867 }
1868 case BlockCaptureEntityKind::None:
1869 break;
1870 }
1871
1872 return Str;
1873}
1874
1875static std::string getCopyDestroyHelperFuncName(
1876 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1877 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1878 assert((StrKind == CaptureStrKind::CopyHelper ||
1879 StrKind == CaptureStrKind::DisposeHelper) &&
1880 "unexpected CaptureStrKind");
1881 std::string Name = StrKind == CaptureStrKind::CopyHelper
1882 ? "__copy_helper_block_"
1883 : "__destroy_helper_block_";
Akira Hatanaka9978da32018-08-10 15:09:24 +00001884 if (CGM.getLangOpts().Exceptions)
1885 Name += "e";
1886 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1887 Name += "a";
1888 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1889
1890 for (const BlockCaptureManagedEntity &E : Captures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001891 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001892 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001893 }
1894
1895 return Name;
1896}
1897
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001898static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1899 Address Field, QualType CaptureType,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001900 BlockFieldFlags Flags, bool ForCopyHelper,
1901 VarDecl *Var, CodeGenFunction &CGF) {
1902 bool EHOnly = ForCopyHelper;
1903
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001904 switch (CaptureKind) {
1905 case BlockCaptureEntityKind::CXXRecord:
1906 case BlockCaptureEntityKind::ARCWeak:
1907 case BlockCaptureEntityKind::NonTrivialCStruct:
1908 case BlockCaptureEntityKind::ARCStrong: {
1909 if (CaptureType.isDestructedType() &&
1910 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1911 CodeGenFunction::Destroyer *Destroyer =
1912 CaptureKind == BlockCaptureEntityKind::ARCStrong
1913 ? CodeGenFunction::destroyARCStrongImprecise
1914 : CGF.getDestroyer(CaptureType.isDestructedType());
1915 CleanupKind Kind =
1916 EHOnly ? EHCleanup
1917 : CGF.getCleanupKind(CaptureType.isDestructedType());
1918 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1919 }
1920 break;
1921 }
1922 case BlockCaptureEntityKind::BlockObject: {
1923 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1924 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001925 // Calls to _Block_object_dispose along the EH path in the copy helper
1926 // function don't throw as newly-copied __block variables always have a
1927 // reference count of 2.
1928 bool CanThrow =
1929 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1930 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1931 CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001932 }
1933 break;
1934 }
1935 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001936 break;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001937 }
1938}
1939
Akira Hatanaka9978da32018-08-10 15:09:24 +00001940static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1941 llvm::Function *Fn,
1942 const CGFunctionInfo &FI,
1943 CodeGenModule &CGM) {
1944 if (CapturesNonExternalType) {
1945 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1946 } else {
1947 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1948 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1949 CGM.SetLLVMFunctionAttributes(nullptr, FI, Fn);
1950 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1951 }
1952}
John McCallf593b102013-01-22 03:56:22 +00001953/// Generate the copy-helper function for a block closure object:
1954/// static void block_copy_helper(block_t *dst, block_t *src);
1955/// The runtime will have previously initialized 'dst' by doing a
1956/// bit-copy of 'src'.
1957///
1958/// Note that this copies an entire block closure object to the heap;
1959/// it should not be confused with a 'byref copy helper', which moves
1960/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001961llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001962CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001963 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001964 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001965 std::string FuncName =
1966 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001967 CaptureStrKind::CopyHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001968
1969 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00001970 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001971
John McCall351762c2011-02-07 10:33:21 +00001972 ASTContext &C = getContext();
1973
1974 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001975 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1976 ImplicitParamDecl::Other);
1977 args.push_back(&DstDecl);
1978 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1979 ImplicitParamDecl::Other);
1980 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001981
John McCallc56a8b32016-03-11 04:30:31 +00001982 const CGFunctionInfo &FI =
1983 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001984
John McCall351762c2011-02-07 10:33:21 +00001985 // FIXME: it would be nice if these were mergeable with things with
1986 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001987 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001988
1989 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00001990 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1991 FuncName, &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001992
1993 IdentifierInfo *II
Akira Hatanaka9978da32018-08-10 15:09:24 +00001994 = &CGM.getContext().Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00001995
John McCall351762c2011-02-07 10:33:21 +00001996 FunctionDecl *FD = FunctionDecl::Create(C,
1997 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001998 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001999 SourceLocation(), II, C.VoidTy,
2000 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002001 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00002002 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002003
Akira Hatanaka9978da32018-08-10 15:09:24 +00002004 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2005 CGM);
Adrian Prantl22e66b42014-04-11 01:13:04 +00002006 StartFunction(FD, C.VoidTy, Fn, FI, args);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002007 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Chris Lattner2192fe52011-07-18 04:24:23 +00002008 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002009
Alexey Bataev56223232017-06-09 13:40:18 +00002010 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002011 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002012 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002013
Alexey Bataev56223232017-06-09 13:40:18 +00002014 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002015 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002016 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002017
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002018 for (const auto &CopiedCapture : CopiedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002019 const BlockDecl::Capture &CI = *CopiedCapture.CI;
2020 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002021 QualType captureType = CI.getVariable()->getType();
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002022 BlockFieldFlags flags = CopiedCapture.CopyFlags;
John McCall351762c2011-02-07 10:33:21 +00002023
2024 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00002025 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
2026 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00002027
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002028 switch (CopiedCapture.CopyKind) {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002029 case BlockCaptureEntityKind::CXXRecord:
2030 // If there's an explicit copy expression, we do that.
2031 assert(CI.getCopyExpr() && "copy expression for variable is missing");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002032 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002033 break;
2034 case BlockCaptureEntityKind::ARCWeak:
John McCall31168b02011-06-15 23:02:42 +00002035 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002036 break;
2037 case BlockCaptureEntityKind::NonTrivialCStruct: {
2038 // If this is a C struct that requires non-trivial copy construction,
2039 // emit a call to its copy constructor.
Akira Hatanaka7275da02018-02-28 07:15:55 +00002040 QualType varType = CI.getVariable()->getType();
2041 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2042 MakeAddrLValue(srcField, varType));
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002043 break;
2044 }
2045 case BlockCaptureEntityKind::ARCStrong: {
John McCall351762c2011-02-07 10:33:21 +00002046 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002047 // At -O0, store null into the destination field (so that the
2048 // storeStrong doesn't over-release) and then call storeStrong.
2049 // This is a workaround to not having an initStrong call.
2050 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2051 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2052 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2053 Builder.CreateStore(null, dstField);
2054 EmitARCStoreStrongCall(dstField, srcValue, true);
John McCalle68b8f42012-10-17 02:28:37 +00002055
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002056 // With optimization enabled, take advantage of the fact that
2057 // the blocks runtime guarantees a memcpy of the block data, and
2058 // just emit a retain of the src field.
John McCalle68b8f42012-10-17 02:28:37 +00002059 } else {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002060 EmitARCRetainNonBlock(srcValue);
John McCall882987f2013-02-28 19:01:20 +00002061
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002062 // Unless EH cleanup is required, we don't need this anymore, so kill
2063 // it. It's not quite worth the annoyance to avoid creating it in the
2064 // first place.
2065 if (!needsEHCleanup(captureType.isDestructedType()))
2066 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00002067 }
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002068 break;
2069 }
2070 case BlockCaptureEntityKind::BlockObject: {
2071 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2072 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2073 llvm::Value *dstAddr =
2074 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2075 llvm::Value *args[] = {
2076 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2077 };
2078
2079 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2080 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2081 else
2082 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2083 break;
2084 }
2085 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002086 continue;
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002087 }
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002088
2089 // Ensure that we destroy the copied object if an exception is thrown later
2090 // in the helper function.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002091 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002092 /*ForCopyHelper*/ true, CI.getVariable(), *this);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002093 }
2094
John McCallad7c5c12011-02-08 08:22:06 +00002095 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002096
John McCalle3dc1702011-02-15 09:22:45 +00002097 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00002098}
2099
Akira Hatanaka7275da02018-02-28 07:15:55 +00002100static BlockFieldFlags
2101getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2102 QualType T) {
2103 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2104 if (T->isBlockPointerType())
2105 Flags = BLOCK_FIELD_IS_BLOCK;
2106 return Flags;
2107}
2108
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002109static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2110computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2111 const LangOptions &LangOpts) {
Akira Hatanaka2e00b982018-09-08 20:03:00 +00002112 if (CI.isEscapingByref()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002113 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002114 if (T.isObjCGCWeak())
2115 Flags |= BLOCK_FIELD_IS_WEAK;
2116 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2117 }
2118
Akira Hatanaka7275da02018-02-28 07:15:55 +00002119 switch (T.isDestructedType()) {
2120 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002121 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00002122 case QualType::DK_objc_strong_lifetime:
2123 // Use objc_storeStrong for __strong direct captures; the
2124 // dynamic tools really like it when we do this.
2125 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2126 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2127 case QualType::DK_objc_weak_lifetime:
2128 // Support __weak direct captures.
2129 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2130 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2131 case QualType::DK_nontrivial_c_struct:
2132 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2133 BlockFieldFlags());
2134 case QualType::DK_none: {
2135 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2136 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2137 !LangOpts.ObjCAutoRefCount)
2138 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2139 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2140 // Otherwise, we have nothing to do.
2141 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002142 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00002143 }
Nico Weberb3897eb2018-02-28 19:28:47 +00002144 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002145}
2146
John McCallf593b102013-01-22 03:56:22 +00002147/// Generate the destroy-helper function for a block closure object:
2148/// static void block_destroy_helper(block_t *theBlock);
2149///
2150/// Note that this destroys a heap-allocated block closure object;
2151/// it should not be confused with a 'byref destroy helper', which
2152/// destroys the heap-allocated contents of an individual __block
2153/// variable.
John McCall351762c2011-02-07 10:33:21 +00002154llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00002155CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002156 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002157 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002158 std::string FuncName =
2159 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002160 CaptureStrKind::DisposeHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002161
2162 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00002163 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002164
John McCall351762c2011-02-07 10:33:21 +00002165 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00002166
John McCall351762c2011-02-07 10:33:21 +00002167 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002168 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
2169 ImplicitParamDecl::Other);
2170 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002171
John McCallc56a8b32016-03-11 04:30:31 +00002172 const CGFunctionInfo &FI =
2173 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00002174
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002175 // FIXME: We'd like to put these into a mergable by content, with
2176 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00002177 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00002178
2179 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00002180 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2181 FuncName, &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00002182
2183 IdentifierInfo *II
Akira Hatanaka9978da32018-08-10 15:09:24 +00002184 = &CGM.getContext().Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00002185
John McCall351762c2011-02-07 10:33:21 +00002186 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002187 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002188 SourceLocation(), II, C.VoidTy,
2189 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00002190 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002191
Akira Hatanaka9978da32018-08-10 15:09:24 +00002192 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2193 CGM);
Adrian Prantl22e66b42014-04-11 01:13:04 +00002194 StartFunction(FD, C.VoidTy, Fn, FI, args);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002195 markAsIgnoreThreadCheckingAtRuntime(Fn);
2196
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002197 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Mike Stump6f7d9f82009-03-07 02:53:18 +00002198
Chris Lattner2192fe52011-07-18 04:24:23 +00002199 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00002200
Alexey Bataev56223232017-06-09 13:40:18 +00002201 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002202 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002203 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00002204
John McCallad7c5c12011-02-08 08:22:06 +00002205 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00002206
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002207 for (const auto &DestroyedCapture : DestroyedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002208 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2209 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002210 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
John McCall351762c2011-02-07 10:33:21 +00002211
John McCall7f416cc2015-09-08 08:05:57 +00002212 Address srcField =
2213 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00002214
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002215 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002216 CI.getVariable()->getType(), flags,
2217 /*ForCopyHelper*/ false, CI.getVariable(), *this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00002218 }
2219
John McCall351762c2011-02-07 10:33:21 +00002220 cleanups.ForceCleanup();
2221
John McCallad7c5c12011-02-08 08:22:06 +00002222 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002223
John McCalle3dc1702011-02-15 09:22:45 +00002224 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00002225}
2226
John McCallf9b056b2011-03-31 08:03:29 +00002227namespace {
2228
2229/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00002230class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002231 BlockFieldFlags Flags;
2232
2233public:
2234 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00002235 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00002236
John McCall7f416cc2015-09-08 08:05:57 +00002237 void emitCopy(CodeGenFunction &CGF, Address destField,
2238 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002239 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2240
2241 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2242 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2243
2244 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2245
2246 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2247 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00002248
John McCall7f416cc2015-09-08 08:05:57 +00002249 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00002250 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00002251 }
2252
John McCall7f416cc2015-09-08 08:05:57 +00002253 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002254 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2255 llvm::Value *value = CGF.Builder.CreateLoad(field);
2256
Akira Hatanaka9978da32018-08-10 15:09:24 +00002257 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
John McCallf9b056b2011-03-31 08:03:29 +00002258 }
2259
Craig Topper4f12f102014-03-12 06:41:41 +00002260 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002261 id.AddInteger(Flags.getBitMask());
2262 }
2263};
2264
John McCall31168b02011-06-15 23:02:42 +00002265/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00002266class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002267public:
John McCall7f416cc2015-09-08 08:05:57 +00002268 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002269
John McCall7f416cc2015-09-08 08:05:57 +00002270 void emitCopy(CodeGenFunction &CGF, Address destField,
2271 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002272 CGF.EmitARCMoveWeak(destField, srcField);
2273 }
2274
John McCall7f416cc2015-09-08 08:05:57 +00002275 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00002276 CGF.EmitARCDestroyWeak(field);
2277 }
2278
Craig Topper4f12f102014-03-12 06:41:41 +00002279 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002280 // 0 is distinguishable from all pointers and byref flags
2281 id.AddInteger(0);
2282 }
2283};
2284
2285/// Emits the copy/dispose helpers for an ARC __block __strong variable
2286/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002287class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002288public:
John McCall7f416cc2015-09-08 08:05:57 +00002289 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002290
John McCall7f416cc2015-09-08 08:05:57 +00002291 void emitCopy(CodeGenFunction &CGF, Address destField,
2292 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002293 // Do a "move" by copying the value and then zeroing out the old
2294 // variable.
2295
John McCall7f416cc2015-09-08 08:05:57 +00002296 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002297
John McCall31168b02011-06-15 23:02:42 +00002298 llvm::Value *null =
2299 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00002300
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002301 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002302 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002303 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2304 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2305 return;
2306 }
John McCall7f416cc2015-09-08 08:05:57 +00002307 CGF.Builder.CreateStore(value, destField);
2308 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00002309 }
2310
John McCall7f416cc2015-09-08 08:05:57 +00002311 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002312 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00002313 }
2314
Craig Topper4f12f102014-03-12 06:41:41 +00002315 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002316 // 1 is distinguishable from all pointers and byref flags
2317 id.AddInteger(1);
2318 }
2319};
2320
John McCall3a237aa2011-11-09 03:17:26 +00002321/// Emits the copy/dispose helpers for an ARC __block __strong
2322/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002323class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00002324public:
John McCall7f416cc2015-09-08 08:05:57 +00002325 ARCStrongBlockByrefHelpers(CharUnits alignment)
2326 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00002327
John McCall7f416cc2015-09-08 08:05:57 +00002328 void emitCopy(CodeGenFunction &CGF, Address destField,
2329 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00002330 // Do the copy with objc_retainBlock; that's all that
2331 // _Block_object_assign would do anyway, and we'd have to pass the
2332 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00002333 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00002334 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00002335 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00002336 }
2337
John McCall7f416cc2015-09-08 08:05:57 +00002338 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002339 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00002340 }
2341
Craig Topper4f12f102014-03-12 06:41:41 +00002342 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00002343 // 2 is distinguishable from all pointers and byref flags
2344 id.AddInteger(2);
2345 }
2346};
2347
John McCallf9b056b2011-03-31 08:03:29 +00002348/// Emits the copy/dispose helpers for a __block variable with a
2349/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002350class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002351 QualType VarType;
2352 const Expr *CopyExpr;
2353
2354public:
2355 CXXByrefHelpers(CharUnits alignment, QualType type,
2356 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002357 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002358
Craig Topper8a13c412014-05-21 05:09:00 +00002359 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002360 void emitCopy(CodeGenFunction &CGF, Address destField,
2361 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002362 if (!CopyExpr) return;
2363 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2364 }
2365
John McCall7f416cc2015-09-08 08:05:57 +00002366 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002367 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2368 CGF.PushDestructorCleanup(VarType, field);
2369 CGF.PopCleanupBlocks(cleanupDepth);
2370 }
2371
Craig Topper4f12f102014-03-12 06:41:41 +00002372 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002373 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2374 }
2375};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002376
2377/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2378/// C struct.
2379class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2380 QualType VarType;
2381
2382public:
2383 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2384 : BlockByrefHelpers(alignment), VarType(type) {}
2385
2386 void emitCopy(CodeGenFunction &CGF, Address destField,
2387 Address srcField) override {
2388 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2389 CGF.MakeAddrLValue(srcField, VarType));
2390 }
2391
2392 bool needsDispose() const override {
2393 return VarType.isDestructedType();
2394 }
2395
2396 void emitDispose(CodeGenFunction &CGF, Address field) override {
2397 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2398 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2399 CGF.PopCleanupBlocks(cleanupDepth);
2400 }
2401
2402 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2403 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2404 }
2405};
John McCallf9b056b2011-03-31 08:03:29 +00002406} // end anonymous namespace
2407
2408static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002409generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2410 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002411 ASTContext &Context = CGF.getContext();
2412
2413 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002414
John McCalla738c252011-03-09 04:27:21 +00002415 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002416 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2417 ImplicitParamDecl::Other);
2418 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002419
Alexey Bataev56223232017-06-09 13:40:18 +00002420 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2421 ImplicitParamDecl::Other);
2422 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002423
John McCallc56a8b32016-03-11 04:30:31 +00002424 const CGFunctionInfo &FI =
2425 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002426
John McCall7f416cc2015-09-08 08:05:57 +00002427 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002428
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002429 // FIXME: We'd like to put these into a mergable by content, with
2430 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002431 llvm::Function *Fn =
2432 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002433 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002434
2435 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002436 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002437
John McCallf9b056b2011-03-31 08:03:29 +00002438 FunctionDecl *FD = FunctionDecl::Create(Context,
2439 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002440 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002441 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002442 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002443 false, false);
John McCall31168b02011-06-15 23:02:42 +00002444
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002445 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002446
Adrian Prantl22e66b42014-04-11 01:13:04 +00002447 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002448
John McCall7f416cc2015-09-08 08:05:57 +00002449 if (generator.needsCopy()) {
2450 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002451
John McCallf9b056b2011-03-31 08:03:29 +00002452 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002453 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002454 destField = Address(CGF.Builder.CreateLoad(destField),
2455 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002456 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002457 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2458 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002459
John McCallf9b056b2011-03-31 08:03:29 +00002460 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002461 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002462 srcField = Address(CGF.Builder.CreateLoad(srcField),
2463 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002464 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002465 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2466 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002467
John McCall7f416cc2015-09-08 08:05:57 +00002468 generator.emitCopy(CGF, destField, srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002469 }
John McCallf9b056b2011-03-31 08:03:29 +00002470
2471 CGF.FinishFunction();
2472
2473 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002474}
2475
John McCallf9b056b2011-03-31 08:03:29 +00002476/// Build the copy helper for a __block variable.
2477static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002478 const BlockByrefInfo &byrefInfo,
2479 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002480 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002481 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002482}
2483
2484/// Generate code for a __block variable's dispose helper.
2485static llvm::Constant *
2486generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002487 const BlockByrefInfo &byrefInfo,
2488 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002489 ASTContext &Context = CGF.getContext();
2490 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002491
John McCalla738c252011-03-09 04:27:21 +00002492 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002493 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2494 ImplicitParamDecl::Other);
2495 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002496
John McCallc56a8b32016-03-11 04:30:31 +00002497 const CGFunctionInfo &FI =
2498 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002499
John McCall7f416cc2015-09-08 08:05:57 +00002500 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002501
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002502 // FIXME: We'd like to put these into a mergable by content, with
2503 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002504 llvm::Function *Fn =
2505 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002506 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002507 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002508
2509 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002510 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002511
John McCallf9b056b2011-03-31 08:03:29 +00002512 FunctionDecl *FD = FunctionDecl::Create(Context,
2513 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002514 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002515 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002516 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002517 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002518
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002519 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002520
Adrian Prantl22e66b42014-04-11 01:13:04 +00002521 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002522
John McCall7f416cc2015-09-08 08:05:57 +00002523 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002524 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002525 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2526 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2527 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2528 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002529
John McCall7f416cc2015-09-08 08:05:57 +00002530 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002531 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002532
John McCallf9b056b2011-03-31 08:03:29 +00002533 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002534
John McCallf9b056b2011-03-31 08:03:29 +00002535 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002536}
2537
John McCallf9b056b2011-03-31 08:03:29 +00002538/// Build the dispose helper for a __block variable.
2539static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002540 const BlockByrefInfo &byrefInfo,
2541 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002542 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002543 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002544}
2545
John McCallf593b102013-01-22 03:56:22 +00002546/// Lazily build the copy and dispose helpers for a __block variable
2547/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002548template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002549static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2550 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002551 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002552 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002553
2554 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002555 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002556 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2557 if (node) return static_cast<T*>(node);
2558
John McCall7f416cc2015-09-08 08:05:57 +00002559 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2560 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002561
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002562 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002563 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2564 return copy;
2565}
2566
John McCallf593b102013-01-22 03:56:22 +00002567/// Build the copy and dispose helpers for the given __block variable
2568/// emission. Places the helpers in the global cache. Returns null
2569/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002570BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002571CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002572 const AutoVarEmission &emission) {
2573 const VarDecl &var = *emission.Variable;
Akira Hatanaka2e00b982018-09-08 20:03:00 +00002574 assert(var.isEscapingByref() &&
2575 "only escaping __block variables need byref helpers");
2576
John McCallf9b056b2011-03-31 08:03:29 +00002577 QualType type = var.getType();
2578
John McCall7f416cc2015-09-08 08:05:57 +00002579 auto &byrefInfo = getBlockByrefInfo(&var);
2580
2581 // The alignment we care about for the purposes of uniquing byref
2582 // helpers is the alignment of the actual byref value field.
2583 CharUnits valueAlignment =
2584 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002585
John McCallf9b056b2011-03-31 08:03:29 +00002586 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002587 const Expr *copyExpr =
2588 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002589 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002590
David Blaikie92551612015-08-13 23:53:09 +00002591 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002592 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002593 }
2594
Akira Hatanaka7275da02018-02-28 07:15:55 +00002595 // If type is a non-trivial C struct type that is non-trivial to
2596 // destructly move or destroy, build the copy and dispose helpers.
2597 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2598 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2599 return ::buildByrefHelpers(
2600 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2601
John McCall31168b02011-06-15 23:02:42 +00002602 // Otherwise, if we don't have a retainable type, there's nothing to do.
2603 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002604 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002605
2606 Qualifiers qs = type.getQualifiers();
2607
2608 // If we have lifetime, that dominates.
2609 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002610 switch (lifetime) {
2611 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2612
2613 // These are just bits as far as the runtime is concerned.
2614 case Qualifiers::OCL_ExplicitNone:
2615 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002616 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002617
2618 // Tell the runtime that this is ARC __weak, called by the
2619 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002620 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002621 return ::buildByrefHelpers(CGM, byrefInfo,
2622 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002623
2624 // ARC __strong __block variables need to be retained.
2625 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002626 // Block pointers need to be copied, and there's no direct
2627 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002628 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002629 return ::buildByrefHelpers(CGM, byrefInfo,
2630 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002631
2632 // Otherwise, we transfer ownership of the retain from the stack
2633 // to the heap.
2634 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002635 return ::buildByrefHelpers(CGM, byrefInfo,
2636 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002637 }
2638 }
2639 llvm_unreachable("fell out of lifetime switch!");
2640 }
2641
John McCallf9b056b2011-03-31 08:03:29 +00002642 BlockFieldFlags flags;
2643 if (type->isBlockPointerType()) {
2644 flags |= BLOCK_FIELD_IS_BLOCK;
Fangrui Song6907ce22018-07-30 19:24:48 +00002645 } else if (CGM.getContext().isObjCNSObjectType(type) ||
John McCallf9b056b2011-03-31 08:03:29 +00002646 type->isObjCObjectPointerType()) {
2647 flags |= BLOCK_FIELD_IS_OBJECT;
2648 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002649 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002650 }
2651
2652 if (type.isObjCGCWeak())
2653 flags |= BLOCK_FIELD_IS_WEAK;
2654
John McCall7f416cc2015-09-08 08:05:57 +00002655 return ::buildByrefHelpers(CGM, byrefInfo,
2656 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002657}
2658
John McCall7f416cc2015-09-08 08:05:57 +00002659Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2660 const VarDecl *var,
2661 bool followForward) {
2662 auto &info = getBlockByrefInfo(var);
2663 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002664}
2665
John McCall7f416cc2015-09-08 08:05:57 +00002666Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2667 const BlockByrefInfo &info,
2668 bool followForward,
2669 const llvm::Twine &name) {
2670 // Chase the forwarding address if requested.
2671 if (followForward) {
2672 Address forwardingAddr =
2673 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2674 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2675 }
2676
2677 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2678 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002679}
2680
John McCall7f416cc2015-09-08 08:05:57 +00002681/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002682/// into:
2683///
2684/// struct {
2685/// void *__isa;
2686/// void *__forwarding;
2687/// int32_t __flags;
2688/// int32_t __size;
2689/// void *__copy_helper; // only if needed
2690/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002691/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002692/// char padding[X]; // only if needed
2693/// T x;
2694/// } x
2695///
John McCall7f416cc2015-09-08 08:05:57 +00002696const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2697 auto it = BlockByrefInfos.find(D);
2698 if (it != BlockByrefInfos.end())
2699 return it->second;
John McCall73064872011-03-31 01:59:53 +00002700
John McCall7f416cc2015-09-08 08:05:57 +00002701 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002702 llvm::StructType::create(getLLVMContext(),
2703 "struct.__block_byref_" + D->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00002704
John McCall7f416cc2015-09-08 08:05:57 +00002705 QualType Ty = D->getType();
2706
2707 CharUnits size;
2708 SmallVector<llvm::Type *, 8> types;
Fangrui Song6907ce22018-07-30 19:24:48 +00002709
John McCall73064872011-03-31 01:59:53 +00002710 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002711 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002712 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002713
John McCall73064872011-03-31 01:59:53 +00002714 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002715 types.push_back(llvm::PointerType::getUnqual(byrefType));
2716 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002717
John McCall73064872011-03-31 01:59:53 +00002718 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002719 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002720 size += CharUnits::fromQuantity(4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002721
John McCall73064872011-03-31 01:59:53 +00002722 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002723 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002724 size += CharUnits::fromQuantity(4);
2725
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002726 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002727 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2728 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002729 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002730 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002731 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002732
John McCall73064872011-03-31 01:59:53 +00002733 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002734 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002735 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002736 }
John McCall7f416cc2015-09-08 08:05:57 +00002737
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002738 bool HasByrefExtendedLayout = false;
2739 Qualifiers::ObjCLifetime Lifetime;
2740 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002741 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002742 /// void *__byref_variable_layout;
2743 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002744 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002745 }
2746
2747 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002748 llvm::Type *varTy = ConvertTypeForMem(Ty);
2749
2750 bool packed = false;
2751 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002752 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002753
2754 // We may have to insert padding.
2755 if (varOffset != size) {
2756 llvm::Type *paddingTy =
2757 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2758
2759 types.push_back(paddingTy);
2760 size = varOffset;
2761
2762 // Conversely, we might have to prevent LLVM from inserting padding.
2763 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2764 > varAlign.getQuantity()) {
2765 packed = true;
2766 }
2767 types.push_back(varTy);
2768
2769 byrefType->setBody(types, packed);
2770
2771 BlockByrefInfo info;
2772 info.Type = byrefType;
2773 info.FieldIndex = types.size() - 1;
2774 info.FieldOffset = varOffset;
2775 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2776
2777 auto pair = BlockByrefInfos.insert({D, info});
2778 assert(pair.second && "info was inserted recursively?");
2779 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002780}
2781
2782/// Initialize the structural components of a __block variable, i.e.
2783/// everything but the actual object.
2784void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002785 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002786 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002787
John McCallf9b056b2011-03-31 08:03:29 +00002788 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002789 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002790 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2791
2792 unsigned nextHeaderIndex = 0;
2793 CharUnits nextHeaderOffset;
2794 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2795 const Twine &name) {
2796 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2797 nextHeaderOffset, name);
2798 Builder.CreateStore(value, fieldAddr);
2799
2800 nextHeaderIndex++;
2801 nextHeaderOffset += fieldSize;
2802 };
John McCallf9b056b2011-03-31 08:03:29 +00002803
2804 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002805 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002806
2807 const VarDecl &D = *emission.Variable;
2808 QualType type = D.getType();
2809
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002810 bool HasByrefExtendedLayout;
2811 Qualifiers::ObjCLifetime ByrefLifetime;
2812 bool ByRefHasLifetime =
2813 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002814
John McCallf9b056b2011-03-31 08:03:29 +00002815 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002816
2817 // Initialize the 'isa', which is just 0 or 1.
2818 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002819 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002820 isa = 1;
2821 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002822 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002823
2824 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002825 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002826
2827 // Blocks ABI:
2828 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002829 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002830 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002831 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2832 if (ByRefHasLifetime) {
2833 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2834 else switch (ByrefLifetime) {
2835 case Qualifiers::OCL_Strong:
2836 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2837 break;
2838 case Qualifiers::OCL_Weak:
2839 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2840 break;
2841 case Qualifiers::OCL_ExplicitNone:
2842 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2843 break;
2844 case Qualifiers::OCL_None:
2845 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2846 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2847 break;
2848 default:
2849 break;
2850 }
2851 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2852 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2853 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2854 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2855 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2856 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2857 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2858 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2859 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2860 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2861 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2862 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2863 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2864 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2865 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2866 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2867 }
2868 printf("\n");
2869 }
2870 }
John McCall7f416cc2015-09-08 08:05:57 +00002871 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2872 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002873
John McCallf9b056b2011-03-31 08:03:29 +00002874 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2875 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002876 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002877
John McCallf9b056b2011-03-31 08:03:29 +00002878 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002879 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2880 "byref.copyHelper");
2881 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2882 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002883 }
John McCall7f416cc2015-09-08 08:05:57 +00002884
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002885 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002886 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2887 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002888 }
John McCall73064872011-03-31 01:59:53 +00002889}
2890
Akira Hatanaka9978da32018-08-10 15:09:24 +00002891void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2892 bool CanThrow) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002893 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002894 llvm::Value *args[] = {
2895 Builder.CreateBitCast(V, Int8PtrTy),
2896 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2897 };
Akira Hatanaka9978da32018-08-10 15:09:24 +00002898
2899 if (CanThrow)
2900 EmitRuntimeCallOrInvoke(F, args);
2901 else
2902 EmitNounwindRuntimeCall(F, args);
Mike Stump626aecc2009-03-05 01:23:13 +00002903}
John McCall73064872011-03-31 01:59:53 +00002904
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002905void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2906 BlockFieldFlags Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002907 bool LoadBlockVarAddr, bool CanThrow) {
2908 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2909 CanThrow);
John McCall73064872011-03-31 01:59:53 +00002910}
John McCall7959fee2011-09-09 20:41:01 +00002911
2912/// Adjust the declaration of something from the blocks API.
2913static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2914 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002915 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002916
2917 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2918 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2919 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2920 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2921
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002922 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2923 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2924 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002925
2926 const NamedDecl *ND = nullptr;
2927 for (const auto &Result : DC->lookup(&II))
2928 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2929 (ND = dyn_cast<VarDecl>(Result)))
2930 break;
2931
2932 // TODO: support static blocks runtime
2933 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2934 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2935 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2936 } else {
2937 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2938 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2939 }
2940 }
2941
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002942 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2943 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002944 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002945
2946 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002947}
2948
2949llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2950 if (BlockObjectDispose)
2951 return BlockObjectDispose;
2952
2953 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2954 llvm::FunctionType *fty
2955 = llvm::FunctionType::get(VoidTy, args, false);
2956 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2957 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2958 return BlockObjectDispose;
2959}
2960
2961llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2962 if (BlockObjectAssign)
2963 return BlockObjectAssign;
2964
2965 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2966 llvm::FunctionType *fty
2967 = llvm::FunctionType::get(VoidTy, args, false);
2968 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2969 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2970 return BlockObjectAssign;
2971}
2972
2973llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2974 if (NSConcreteGlobalBlock)
2975 return NSConcreteGlobalBlock;
2976
2977 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002978 Int8PtrTy->getPointerTo(),
2979 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002980 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2981 return NSConcreteGlobalBlock;
2982}
2983
2984llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2985 if (NSConcreteStackBlock)
2986 return NSConcreteStackBlock;
2987
2988 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002989 Int8PtrTy->getPointerTo(),
2990 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002991 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002992 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002993}