blob: 6a1a73955319c665fdbb5877491090669f8c67d6 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson2437cbf2009-02-12 00:39:25 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit blocks.
10//
11//===----------------------------------------------------------------------===//
12
John McCallad7c5c12011-02-08 08:22:06 +000013#include "CGBlocks.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000021#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000022#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000023#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000024#include "llvm/ADT/SmallSet.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Module.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000027#include "llvm/Support/ScopedPrinter.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000029#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000030
Anders Carlsson2437cbf2009-02-12 00:39:25 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall08ef4662011-11-10 08:15:53 +000034CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
35 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000036 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Akira Hatanaka9978da32018-08-10 15:09:24 +000037 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
38 StructureType(nullptr), Block(block), DominatingIP(nullptr) {
Craig Topper8a13c412014-05-21 05:09:00 +000039
John McCall08ef4662011-11-10 08:15:53 +000040 // Skip asm prefix, if any. 'name' is usually taken directly from
41 // the mangled name of the enclosing function.
42 if (!name.empty() && name[0] == '\01')
43 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000044}
45
John McCallf9b056b2011-03-31 08:03:29 +000046// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000047BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000048
John McCall351762c2011-02-07 10:33:21 +000049/// Build the given block as a global block.
50static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo,
52 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000053
John McCall351762c2011-02-07 10:33:21 +000054/// Build the helper function to copy a block.
55static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
58}
59
Alp Tokerf6a24ce2013-12-05 16:25:25 +000060/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000061static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
62 const CGBlockInfo &blockInfo) {
63 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
64}
65
Akira Hatanaka2ec36f02018-08-17 15:46:07 +000066namespace {
67
68/// Represents a type of copy/destroy operation that should be performed for an
69/// entity that's captured by a block.
70enum class BlockCaptureEntityKind {
71 CXXRecord, // Copy or destroy
72 ARCWeak,
73 ARCStrong,
74 NonTrivialCStruct,
75 BlockObject, // Assign or release
76 None
77};
78
79/// Represents a captured entity that requires extra operations in order for
80/// this entity to be copied or destroyed correctly.
81struct BlockCaptureManagedEntity {
82 BlockCaptureEntityKind CopyKind, DisposeKind;
83 BlockFieldFlags CopyFlags, DisposeFlags;
84 const BlockDecl::Capture *CI;
85 const CGBlockInfo::Capture *Capture;
86
87 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
88 BlockCaptureEntityKind DisposeType,
89 BlockFieldFlags CopyFlags,
90 BlockFieldFlags DisposeFlags,
91 const BlockDecl::Capture &CI,
92 const CGBlockInfo::Capture &Capture)
93 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
94 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
95
96 bool operator<(const BlockCaptureManagedEntity &Other) const {
97 return Capture->getOffset() < Other.Capture->getOffset();
98 }
99};
100
101enum class CaptureStrKind {
102 // String for the copy helper.
103 CopyHelper,
104 // String for the dispose helper.
105 DisposeHelper,
106 // Merge the strings for the copy helper and dispose helper.
107 Merged
108};
109
110} // end anonymous namespace
111
112static void findBlockCapturedManagedEntities(
113 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
114 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
115
116static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
117 CaptureStrKind StrKind,
118 CharUnits BlockAlignment,
119 CodeGenModule &CGM);
120
121static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
122 CodeGenModule &CGM) {
123 std::string Name = "__block_descriptor_";
124 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
125
126 if (BlockInfo.needsCopyDisposeHelpers()) {
127 if (CGM.getLangOpts().Exceptions)
128 Name += "e";
129 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
130 Name += "a";
131 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
132
133 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
134 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
135 ManagedCaptures);
136
137 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
138 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
139
140 if (E.CopyKind == E.DisposeKind) {
141 // If CopyKind and DisposeKind are the same, merge the capture
142 // information.
143 assert(E.CopyKind != BlockCaptureEntityKind::None &&
144 "shouldn't see BlockCaptureManagedEntity that is None");
145 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
146 BlockInfo.BlockAlign, CGM);
147 } else {
148 // If CopyKind and DisposeKind are not the same, which can happen when
149 // either Kind is None or the captured object is a __strong block,
150 // concatenate the copy and dispose strings.
151 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
152 BlockInfo.BlockAlign, CGM);
153 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
154 BlockInfo.BlockAlign, CGM);
155 }
156 }
157 Name += "_";
158 }
159
160 std::string TypeAtEncoding =
161 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
Akira Hatanakac7c75742018-12-29 17:28:30 +0000162 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
163 /// a separator between symbol name and symbol version.
164 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000165 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
166 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
167 return Name;
168}
169
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000170/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
171/// buildBlockDescriptor is accessed from 5th field of the Block_literal
172/// meta-data and contains stationary information about the block literal.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000173/// Its definition will have 4 (or optionally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000174/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000175/// struct Block_descriptor {
176/// unsigned long reserved;
177/// unsigned long size; // size of Block_literal metadata in bytes.
178/// void *copy_func_helper_decl; // optional copy helper.
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000179/// void *destroy_func_decl; // optional destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000180/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000181/// void *block_layout_info; // encoding of captured block variables.
182/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000183/// \endcode
John McCall351762c2011-02-07 10:33:21 +0000184static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
185 const CGBlockInfo &blockInfo) {
186 ASTContext &C = CGM.getContext();
187
John McCall6c9f1fdb2016-11-19 08:17:24 +0000188 llvm::IntegerType *ulong =
189 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
190 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000191 if (CGM.getLangOpts().OpenCL)
Fangrui Song6907ce22018-07-30 19:24:48 +0000192 i8p =
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000193 llvm::Type::getInt8PtrTy(
194 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
195 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000196 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +0000197
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000198 std::string descName;
199
200 // If an equivalent block descriptor global variable exists, return it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000201 if (C.getLangOpts().ObjC &&
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000202 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
203 descName = getBlockDescriptorName(blockInfo, CGM);
204 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
205 return llvm::ConstantExpr::getBitCast(desc,
206 CGM.getBlockDescriptorType());
207 }
208
209 // If there isn't an equivalent block descriptor global variable, create a new
210 // one.
John McCall23c9dc62016-11-28 22:18:27 +0000211 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000212 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +0000213
214 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +0000215 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +0000216
217 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000218 // FIXME: What is the right way to say this doesn't fit? We should give
219 // a user diagnostic in that case. Better fix would be to change the
220 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000221 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000222
John McCall351762c2011-02-07 10:33:21 +0000223 // Optional copy/dispose helpers.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000224 bool hasInternalHelper = false;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000225 if (blockInfo.needsCopyDisposeHelpers()) {
Mike Stump85284ba2009-02-13 16:19:19 +0000226 // copy_func_helper_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000227 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
228 elements.add(copyHelper);
Mike Stump85284ba2009-02-13 16:19:19 +0000229
230 // destroy_func_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000231 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
232 elements.add(disposeHelper);
233
234 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
235 cast<llvm::Function>(disposeHelper->getOperand(0))
236 ->hasInternalLinkage())
237 hasInternalHelper = true;
Mike Stump85284ba2009-02-13 16:19:19 +0000238 }
239
John McCall351762c2011-02-07 10:33:21 +0000240 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
241 std::string typeAtEncoding =
242 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000243 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000244 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Fangrui Song6907ce22018-07-30 19:24:48 +0000245
John McCall351762c2011-02-07 10:33:21 +0000246 // GC layout.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000247 if (C.getLangOpts().ObjC) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000248 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000249 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000250 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000251 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000252 }
John McCall351762c2011-02-07 10:33:21 +0000253 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000254 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000255
Joey Goulyddbda402016-08-10 15:57:02 +0000256 unsigned AddrSpace = 0;
257 if (C.getLangOpts().OpenCL)
258 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000259
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000260 llvm::GlobalValue::LinkageTypes linkage;
261 if (descName.empty()) {
262 linkage = llvm::GlobalValue::InternalLinkage;
263 descName = "__block_descriptor_tmp";
264 } else if (hasInternalHelper) {
265 // If either the copy helper or the dispose helper has internal linkage,
266 // the block descriptor must have internal linkage too.
267 linkage = llvm::GlobalValue::InternalLinkage;
268 } else {
269 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
270 }
271
John McCall351762c2011-02-07 10:33:21 +0000272 llvm::GlobalVariable *global =
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000273 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
274 /*constant*/ true, linkage, AddrSpace);
275
276 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
David Chisnall17d42952019-03-31 11:22:26 +0000277 if (CGM.supportsCOMDAT())
278 global->setComdat(CGM.getModule().getOrInsertComdat(descName));
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000279 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
280 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
281 }
Mike Stump85284ba2009-02-13 16:19:19 +0000282
John McCall351762c2011-02-07 10:33:21 +0000283 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000284}
285
John McCall351762c2011-02-07 10:33:21 +0000286/*
287 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000288
John McCall351762c2011-02-07 10:33:21 +0000289 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
290 struct Block_literal {
291 /// Initialized to one of:
292 /// extern void *_NSConcreteStackBlock[];
293 /// extern void *_NSConcreteGlobalBlock[];
294 ///
295 /// In theory, we could start one off malloc'ed by setting
296 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
297 /// this isa:
298 /// extern void *_NSConcreteMallocBlock[];
299 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000300
John McCall351762c2011-02-07 10:33:21 +0000301 /// These are the flags (with corresponding bit number) that the
302 /// compiler is actually supposed to know about.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000303 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
John McCall351762c2011-02-07 10:33:21 +0000304 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
305 /// descriptor provides copy and dispose helper functions
306 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
307 /// object with a nontrivial destructor or copy constructor
308 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
309 /// as global memory
310 /// 29. BLOCK_USE_STRET - indicates that the block function
311 /// uses stret, which objc_msgSend needs to know about
312 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
313 /// @encoded signature string
314 /// And we're not supposed to manipulate these:
315 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
316 /// to malloc'ed memory
317 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
318 /// to GC-allocated memory
319 /// Additionally, the bottom 16 bits are a reference count which
320 /// should be zero on the stack.
321 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000322
John McCall351762c2011-02-07 10:33:21 +0000323 /// Reserved; should be zero-initialized.
324 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000325
John McCall351762c2011-02-07 10:33:21 +0000326 /// Function pointer generated from block literal.
327 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000328
John McCall351762c2011-02-07 10:33:21 +0000329 /// Block description metadata generated from block literal.
330 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000331
John McCall351762c2011-02-07 10:33:21 +0000332 /// Captured values follow.
333 _CapturesTypes captures...;
334 };
335 */
David Chisnall950a9512009-11-17 19:33:30 +0000336
John McCall351762c2011-02-07 10:33:21 +0000337namespace {
338 /// A chunk of data that we actually have to capture in the block.
339 struct BlockLayoutChunk {
340 CharUnits Alignment;
341 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000342 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000343 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000344 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000345 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000346
John McCall351762c2011-02-07 10:33:21 +0000347 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000348 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000349 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000350 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000351 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000352 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000353
John McCall351762c2011-02-07 10:33:21 +0000354 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000355 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
356 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000357 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000358 info.CXXThisOffset = offset;
359 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000360 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
361 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000362 }
John McCall87fe5d52010-05-20 01:18:31 +0000363 }
John McCall351762c2011-02-07 10:33:21 +0000364 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000365
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000366 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
367 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000368 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000369 if (left.Alignment != right.Alignment)
370 return left.Alignment > right.Alignment;
371
372 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000373 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000374 return 1;
375 if (chunk.Lifetime == Qualifiers::OCL_Strong)
376 return 0;
377 if (chunk.Lifetime == Qualifiers::OCL_Weak)
378 return 2;
379 return 3;
380 };
381
382 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000383 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000384} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000385
John McCallb0a3ecb2011-02-08 03:07:00 +0000386/// Determines if the given type is safe for constant capture in C++.
387static bool isSafeForCXXConstantCapture(QualType type) {
388 const RecordType *recordType =
389 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
390
391 // Only records can be unsafe.
392 if (!recordType) return true;
393
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000394 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000395
396 // Maintain semantics for classes with non-trivial dtors or copy ctors.
397 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000398 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000399
400 // Otherwise, we just have to make sure there aren't any mutable
401 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000402 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000403}
404
John McCall351762c2011-02-07 10:33:21 +0000405/// It is illegal to modify a const object after initialization.
406/// Therefore, if a const object has a constant initializer, we don't
407/// actually need to keep storage for it in the block; we'll just
408/// rematerialize it at the start of the block function. This is
409/// acceptable because we make no promises about address stability of
410/// captured variables.
411static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000412 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000413 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000414 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000415 // rematerialize default arguments of function parameters.
416 if (isa<ParmVarDecl>(var))
417 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000418
John McCall351762c2011-02-07 10:33:21 +0000419 QualType type = var->getType();
420
421 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000422 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000423
John McCallb0a3ecb2011-02-08 03:07:00 +0000424 // Furthermore, in C++ we have to worry about mutable fields:
425 // C++ [dcl.type.cv]p4:
426 // Except that any class member declared mutable can be
427 // modified, any attempt to modify a const object during its
428 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000429 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000430 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000431
432 // If the variable doesn't have any initializer (shouldn't this be
433 // invalid?), it's not clear what we should do. Maybe capture as
434 // zero?
435 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000436 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000437
John McCallde0fe072017-08-15 21:42:52 +0000438 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000439}
440
441/// Get the low bit of a nonzero character count. This is the
442/// alignment of the nth byte if the 0th byte is universally aligned.
443static CharUnits getLowBit(CharUnits v) {
444 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
445}
446
447static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000449
450 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000451 if (CGM.getLangOpts().OpenCL) {
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000452 // The header is basically 'struct { int; int; generic void *;
Yaxun Liu10712d92017-10-04 20:32:17 +0000453 // custom_fields; }'. Assert that struct is packed.
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000454 auto GenericAS =
455 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
456 auto GenPtrAlign =
457 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
458 auto GenPtrSize =
459 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
460 assert(CGM.getIntSize() <= GenPtrSize);
461 assert(CGM.getIntAlign() <= GenPtrAlign);
462 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
Yaxun Liu10712d92017-10-04 20:32:17 +0000463 elementTypes.push_back(CGM.IntTy); /* total size */
464 elementTypes.push_back(CGM.IntTy); /* align */
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000465 elementTypes.push_back(
466 CGM.getOpenCLRuntime()
467 .getGenericVoidPointerType()); /* invoke function */
468 unsigned Offset =
469 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
470 unsigned BlockAlign = GenPtrAlign.getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000471 if (auto *Helper =
472 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
473 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
474 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
475 // If necessary, add padding fields to the custom fields.
476 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
477 if (BlockAlign < Align)
478 BlockAlign = Align;
479 assert(Offset % Align == 0);
480 Offset += CGM.getDataLayout().getTypeAllocSize(I);
481 elementTypes.push_back(I);
482 }
483 }
484 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
485 info.BlockSize = CharUnits::fromQuantity(Offset);
486 } else {
487 // The header is basically 'struct { void *; int; int; void *; void *; }'.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000488 // Assert that the struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000489 assert(CGM.getIntSize() <= CGM.getPointerSize());
490 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
491 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
492 info.BlockAlign = CGM.getPointerAlign();
493 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
494 elementTypes.push_back(CGM.VoidPtrTy);
495 elementTypes.push_back(CGM.IntTy);
496 elementTypes.push_back(CGM.IntTy);
497 elementTypes.push_back(CGM.VoidPtrTy);
498 elementTypes.push_back(CGM.getBlockDescriptorType());
499 }
John McCall351762c2011-02-07 10:33:21 +0000500}
501
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000502static QualType getCaptureFieldType(const CodeGenFunction &CGF,
503 const BlockDecl::Capture &CI) {
504 const VarDecl *VD = CI.getVariable();
505
506 // If the variable is captured by an enclosing block or lambda expression,
507 // use the type of the capture field.
508 if (CGF.BlockInfo && CI.isNested())
509 return CGF.BlockInfo->getCapture(VD).fieldType();
510 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
511 return FD->getType();
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000512 // If the captured variable is a non-escaping __block variable, the field
513 // type is the reference type. If the variable is a __block variable that
514 // already has a reference type, the field type is the variable's type.
515 return VD->isNonEscapingByref() ?
516 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000517}
518
John McCall351762c2011-02-07 10:33:21 +0000519/// Compute the layout of the given block. Attempts to lay the block
520/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000521static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
522 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000523 ASTContext &C = CGM.getContext();
524 const BlockDecl *block = info.getBlockDecl();
525
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000526 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000527 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000528 bool hasNonConstantCustomFields = false;
529 if (auto *OpenCLHelper =
530 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
531 hasNonConstantCustomFields =
532 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
533 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000534 info.StructureType =
535 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
536 info.CanBeGlobal = true;
537 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000538 }
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000539 else if (C.getLangOpts().ObjC &&
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000540 CGM.getLangOpts().getGC() == LangOptions::NonGC)
541 info.HasCapturedVariableLayout = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000542
John McCall351762c2011-02-07 10:33:21 +0000543 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000544 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000545 layout.reserve(block->capturesCXXThis() +
546 (block->capture_end() - block->capture_begin()));
547
548 CharUnits maxFieldAlign;
549
550 // First, 'this'.
551 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000552 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
553 "Can't capture 'this' outside a method");
Brian Gesiak5488ab42019-01-11 01:54:53 +0000554 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
John McCall351762c2011-02-07 10:33:21 +0000555
John McCall7f416cc2015-09-08 08:05:57 +0000556 // Theoretically, this could be in a different address space, so
557 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000558 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000559 std::pair<CharUnits,CharUnits> tinfo
560 = CGM.getContext().getTypeInfoInChars(thisType);
561 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
562
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000563 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
564 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000565 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000566 }
567
568 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000569 for (const auto &CI : block->captures()) {
570 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000571
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000572 if (CI.isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +0000573 // We have to copy/dispose of the __block reference.
574 info.NeedsCopyDispose = true;
575
John McCall351762c2011-02-07 10:33:21 +0000576 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000577 CharUnits align = CGM.getPointerAlign();
578 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000579
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000580 // Since a __block variable cannot be captured by lambdas, its type and
581 // the capture field type should always match.
582 assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
583 "capture type differs from the variable type");
John McCall7f416cc2015-09-08 08:05:57 +0000584 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
585 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000586 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000587 continue;
588 }
589
590 // Otherwise, build a layout chunk with the size and alignment of
591 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000592 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000593 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
594 continue;
595 }
596
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000597 QualType VT = getCaptureFieldType(*CGF, CI);
598
John McCall31168b02011-06-15 23:02:42 +0000599 // If we have a lifetime qualifier, honor it for capture purposes.
600 // That includes *not* copying it if it's __unsafe_unretained.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000601 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000602 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000603 switch (lifetime) {
604 case Qualifiers::OCL_None: llvm_unreachable("impossible");
605 case Qualifiers::OCL_ExplicitNone:
606 case Qualifiers::OCL_Autoreleasing:
607 break;
John McCall351762c2011-02-07 10:33:21 +0000608
John McCall31168b02011-06-15 23:02:42 +0000609 case Qualifiers::OCL_Strong:
610 case Qualifiers::OCL_Weak:
611 info.NeedsCopyDispose = true;
612 }
613
614 // Block pointers require copy/dispose. So do Objective-C pointers.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000615 } else if (VT->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000616 // But honor the inert __unsafe_unretained qualifier, which doesn't
617 // actually make it into the type system.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000618 if (VT->isObjCInertUnsafeUnretainedType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000619 lifetime = Qualifiers::OCL_ExplicitNone;
620 } else {
621 info.NeedsCopyDispose = true;
622 // used for mrr below.
623 lifetime = Qualifiers::OCL_Strong;
624 }
John McCall351762c2011-02-07 10:33:21 +0000625
626 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000627 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000628 info.NeedsCopyDispose = true;
629 info.HasCXXObject = true;
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000630 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
Akira Hatanaka9978da32018-08-10 15:09:24 +0000631 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000632
Akira Hatanaka7275da02018-02-28 07:15:55 +0000633 // So do C structs that require non-trivial copy construction or
634 // destruction.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000635 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
636 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
Akira Hatanaka7275da02018-02-28 07:15:55 +0000637 info.NeedsCopyDispose = true;
638
John McCall351762c2011-02-07 10:33:21 +0000639 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000640 } else if (CGM.getLangOpts().CPlusPlus) {
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000641 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
John McCall351762c2011-02-07 10:33:21 +0000642 if (!record->hasTrivialDestructor()) {
643 info.HasCXXObject = true;
644 info.NeedsCopyDispose = true;
Akira Hatanaka9978da32018-08-10 15:09:24 +0000645 if (!record->isExternallyVisible())
646 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000647 }
648 }
649 }
650
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000651 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000652 CharUnits align = C.getDeclAlign(variable);
Fangrui Song6907ce22018-07-30 19:24:48 +0000653
John McCall351762c2011-02-07 10:33:21 +0000654 maxFieldAlign = std::max(maxFieldAlign, align);
655
Jay Foad7c57be32011-07-11 09:56:20 +0000656 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000657 CGM.getTypes().ConvertTypeForMem(VT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000658
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000659 layout.push_back(
660 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000661 }
662
663 // If that was everything, we're done here.
664 if (layout.empty()) {
665 info.StructureType =
666 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
667 info.CanBeGlobal = true;
668 return;
669 }
670
671 // Sort the layout by alignment. We have to use a stable sort here
672 // to get reproducible results. There should probably be an
673 // llvm::array_pod_stable_sort.
Fangrui Song899d1392019-04-24 14:43:05 +0000674 llvm::stable_sort(layout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000675
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000676 // Needed for blocks layout info.
677 info.BlockHeaderForcedGapOffset = info.BlockSize;
678 info.BlockHeaderForcedGapSize = CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +0000679
John McCall351762c2011-02-07 10:33:21 +0000680 CharUnits &blockSize = info.BlockSize;
681 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
682
683 // Assuming that the first byte in the header is maximally aligned,
684 // get the alignment of the first byte following the header.
685 CharUnits endAlign = getLowBit(blockSize);
686
687 // If the end of the header isn't satisfactorily aligned for the
688 // maximum thing, look for things that are okay with the header-end
689 // alignment, and keep appending them until we get something that's
690 // aligned right. This algorithm is only guaranteed optimal if
691 // that condition is satisfied at some point; otherwise we can get
692 // things like:
693 // header // next byte has alignment 4
694 // something_with_size_5; // next byte has alignment 1
695 // something_with_alignment_8;
696 // which has 7 bytes of padding, as opposed to the naive solution
697 // which might have less (?).
698 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000699 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000700 li = layout.begin() + 1, le = layout.end();
701
702 // Look for something that the header end is already
703 // satisfactorily aligned for.
704 for (; li != le && endAlign < li->Alignment; ++li)
705 ;
706
707 // If we found something that's naturally aligned for the end of
708 // the header, keep adding things...
709 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000710 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000711 for (; li != le; ++li) {
712 assert(endAlign >= li->Alignment);
713
John McCall7f416cc2015-09-08 08:05:57 +0000714 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000715 elementTypes.push_back(li->Type);
716 blockSize += li->Size;
717 endAlign = getLowBit(blockSize);
718
719 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000720 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000721 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000722 }
John McCall351762c2011-02-07 10:33:21 +0000723 }
John McCall351762c2011-02-07 10:33:21 +0000724 // Don't re-append everything we just appended.
725 layout.erase(first, li);
726 }
727 }
728
John McCallac0350a2012-04-26 21:14:42 +0000729 assert(endAlign == getLowBit(blockSize));
Fangrui Song6907ce22018-07-30 19:24:48 +0000730
John McCall351762c2011-02-07 10:33:21 +0000731 // At this point, we just have to add padding if the end align still
732 // isn't aligned right.
733 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000734 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000735 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000736
John McCall7f416cc2015-09-08 08:05:57 +0000737 // If we haven't yet added any fields, remember that there was an
738 // initial gap; this need to go into the block layout bit map.
739 if (blockSize == info.BlockHeaderForcedGapOffset) {
740 info.BlockHeaderForcedGapSize = padding;
741 }
742
John McCalle3dc1702011-02-15 09:22:45 +0000743 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
744 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000745 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000746 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000747 }
748
John McCall1db0a2f2012-05-01 20:28:00 +0000749 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000750 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000751 // Slam everything else on now. This works because they have
752 // strictly decreasing alignment and we expect that size is always a
753 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000754 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000755 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000756 if (endAlign < li->Alignment) {
757 // size may not be multiple of alignment. This can only happen with
758 // an over-aligned variable. We will be adding a padding field to
759 // make the size be multiple of alignment.
760 CharUnits padding = li->Alignment - endAlign;
761 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
762 padding.getQuantity()));
763 blockSize += padding;
764 endAlign = getLowBit(blockSize);
765 }
John McCall351762c2011-02-07 10:33:21 +0000766 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000767 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000768 elementTypes.push_back(li->Type);
769 blockSize += li->Size;
770 endAlign = getLowBit(blockSize);
771 }
772
773 info.StructureType =
774 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
775}
776
John McCall08ef4662011-11-10 08:15:53 +0000777/// Enter the scope of a block. This should be run at the entrance to
778/// a full-expression so that the block's cleanups are pushed at the
779/// right place in the stack.
780static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000781 assert(CGF.HaveInsertPoint());
782
John McCall08ef4662011-11-10 08:15:53 +0000783 // Allocate the block info and place it at the head of the list.
784 CGBlockInfo &blockInfo =
785 *new CGBlockInfo(block, CGF.CurFn->getName());
786 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
787 CGF.FirstBlockInfo = &blockInfo;
788
789 // Compute information about the layout, etc., of this block,
790 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000791 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000792
793 // Nothing else to do if it can be global.
794 if (blockInfo.CanBeGlobal) return;
795
796 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000797 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
798 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000799
800 // If there are cleanups to emit, enter them (but inactive).
801 if (!blockInfo.NeedsCopyDispose) return;
802
803 // Walk through the captures (in order) and find the ones not
804 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000805 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000806 // Ignore __block captures; there's nothing special in the
807 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000808 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000809
810 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000811 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000812 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
813 if (capture.isConstant()) continue;
814
815 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000816 QualType VT = getCaptureFieldType(CGF, CI);
817 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000818 if (dtorKind == QualType::DK_none) continue;
819
820 CodeGenFunction::Destroyer *destroyer;
821
822 // Block captures count as local values and have imprecise semantics.
823 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000824 //
825 // For const-qualified captures, emit clang.arc.use to ensure the captured
826 // object doesn't get released while we are still depending on its validity
827 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000828 if (VT.isConstQualified() &&
829 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
830 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
831 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
832 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000833 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000834 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000835 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000836 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000837 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000838 }
839
840 // GEP down to the address.
James Y Knight751fe282019-02-09 22:22:28 +0000841 Address addr =
842 CGF.Builder.CreateStructGEP(blockInfo.LocalAddress, capture.getIndex());
John McCall08ef4662011-11-10 08:15:53 +0000843
John McCallf4beacd2011-11-10 10:43:54 +0000844 // We can use that GEP as the dominating IP.
845 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000846 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000847
John McCall08ef4662011-11-10 08:15:53 +0000848 CleanupKind cleanupKind = InactiveNormalCleanup;
849 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
Fangrui Song6907ce22018-07-30 19:24:48 +0000850 if (useArrayEHCleanup)
John McCall08ef4662011-11-10 08:15:53 +0000851 cleanupKind = InactiveNormalAndEHCleanup;
852
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000853 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000854 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000855
856 // Remember where that cleanup was.
857 capture.setCleanup(CGF.EHStack.stable_begin());
858 }
859}
860
861/// Enter a full-expression with a non-trivial number of objects to
862/// clean up. This is in this file because, at the moment, the only
863/// kind of cleanup object is a BlockDecl*.
Bill Wendling7c44da22018-10-31 03:48:47 +0000864void CodeGenFunction::enterNonTrivialFullExpression(const FullExpr *E) {
865 if (const auto EWC = dyn_cast<ExprWithCleanups>(E)) {
866 assert(EWC->getNumObjects() != 0);
867 for (const ExprWithCleanups::CleanupObject &C : EWC->getObjects())
868 enterBlockScope(*this, C);
869 }
John McCall08ef4662011-11-10 08:15:53 +0000870}
871
872/// Find the layout for the given block in a linked list and remove it.
873static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
874 const BlockDecl *block) {
875 while (true) {
876 assert(head && *head);
877 CGBlockInfo *cur = *head;
878
879 // If this is the block we're looking for, splice it out of the list.
880 if (cur->getBlockDecl() == block) {
881 *head = cur->NextBlockInfo;
882 return cur;
883 }
884
885 head = &cur->NextBlockInfo;
886 }
887}
888
889/// Destroy a chain of block layouts.
890void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
891 assert(head && "destroying an empty chain");
892 do {
893 CGBlockInfo *cur = head;
894 head = cur->NextBlockInfo;
895 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000896 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000897}
898
John McCall351762c2011-02-07 10:33:21 +0000899/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000900llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000901 // If the block has no captures, we won't have a pre-computed
902 // layout for it.
903 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000904 // The block literal is emitted as a global variable, and the block invoke
905 // function has to be extracted from its initializer.
906 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
George Burgess IVe3763372016-12-22 02:50:20 +0000907 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000908 }
John McCall08ef4662011-11-10 08:15:53 +0000909 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000910 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000911 blockInfo.BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000912 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000913 }
John McCall351762c2011-02-07 10:33:21 +0000914
John McCall08ef4662011-11-10 08:15:53 +0000915 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000916 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000917 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
918 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000919
John McCall08ef4662011-11-10 08:15:53 +0000920 blockInfo->BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000921 return EmitBlockLiteral(*blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000922}
923
Yaxun Liufa13d012018-02-15 16:39:19 +0000924llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000925 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000926 auto GenVoidPtrTy =
927 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
928 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
929 auto GenVoidPtrSize = CharUnits::fromQuantity(
930 CGM.getTarget().getPointerWidth(
931 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
932 8);
John McCall08ef4662011-11-10 08:15:53 +0000933 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000934 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000935 CodeGenFunction BlockCGF{CGM, true};
936 BlockCGF.SanOpts = SanOpts;
937 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000938 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000939 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000940
941 // If there is nothing to capture, we can emit this as a global block.
942 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000943 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000944
945 // Otherwise, we have to emit this as a local block.
946
John McCall7f416cc2015-09-08 08:05:57 +0000947 Address blockAddr = blockInfo.LocalAddress;
948 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000949
Yaxun Liu10712d92017-10-04 20:32:17 +0000950 llvm::Constant *isa;
951 llvm::Constant *descriptor;
952 BlockFlags flags;
953 if (!IsOpenCL) {
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000954 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
955 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
956 // block just returns the original block and releasing it is a no-op.
957 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
958 ? CGM.getNSConcreteGlobalBlock()
959 : CGM.getNSConcreteStackBlock();
960 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
Yaxun Liu10712d92017-10-04 20:32:17 +0000961
962 // Build the block descriptor.
963 descriptor = buildBlockDescriptor(CGM, blockInfo);
964
965 // Compute the initial on-stack block flags.
966 flags = BLOCK_HAS_SIGNATURE;
967 if (blockInfo.HasCapturedVariableLayout)
968 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000969 if (blockInfo.needsCopyDisposeHelpers())
Yaxun Liu10712d92017-10-04 20:32:17 +0000970 flags |= BLOCK_HAS_COPY_DISPOSE;
971 if (blockInfo.HasCXXObject)
972 flags |= BLOCK_HAS_CXX_OBJ;
973 if (blockInfo.UsesStret)
974 flags |= BLOCK_USE_STRET;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000975 if (blockInfo.getBlockDecl()->doesNotEscape())
976 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
Yaxun Liu10712d92017-10-04 20:32:17 +0000977 }
John McCall351762c2011-02-07 10:33:21 +0000978
James Y Knight751fe282019-02-09 22:22:28 +0000979 auto projectField = [&](unsigned index, const Twine &name) -> Address {
980 return Builder.CreateStructGEP(blockAddr, index, name);
981 };
982 auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
983 Builder.CreateStore(value, projectField(index, name));
984 };
John McCall7f416cc2015-09-08 08:05:57 +0000985
986 // Initialize the block header.
987 {
988 // We assume all the header fields are densely packed.
989 unsigned index = 0;
990 CharUnits offset;
James Y Knight751fe282019-02-09 22:22:28 +0000991 auto addHeaderField = [&](llvm::Value *value, CharUnits size,
992 const Twine &name) {
993 storeField(value, index, name);
994 offset += size;
995 index++;
996 };
John McCall7f416cc2015-09-08 08:05:57 +0000997
Yaxun Liu10712d92017-10-04 20:32:17 +0000998 if (!IsOpenCL) {
999 addHeaderField(isa, getPointerSize(), "block.isa");
1000 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1001 getIntSize(), "block.flags");
1002 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
1003 "block.reserved");
1004 } else {
1005 addHeaderField(
1006 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
1007 getIntSize(), "block.size");
1008 addHeaderField(
1009 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
1010 getIntSize(), "block.align");
1011 }
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001012 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
1013 if (!IsOpenCL)
Yaxun Liu10712d92017-10-04 20:32:17 +00001014 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001015 else if (auto *Helper =
1016 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001017 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
1018 addHeaderField(
1019 I.first,
1020 CharUnits::fromQuantity(
1021 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
1022 I.second);
1023 }
1024 }
John McCall7f416cc2015-09-08 08:05:57 +00001025 }
John McCall351762c2011-02-07 10:33:21 +00001026
1027 // Finally, capture all the values into the block.
1028 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1029
1030 // First, 'this'.
1031 if (blockDecl->capturesCXXThis()) {
James Y Knight751fe282019-02-09 22:22:28 +00001032 Address addr =
1033 projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +00001034 Builder.CreateStore(LoadCXXThis(), addr);
1035 }
1036
1037 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001038 for (const auto &CI : blockDecl->captures()) {
1039 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001040 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1041
1042 // Ignore constant captures.
1043 if (capture.isConstant()) continue;
1044
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001045 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +00001046
1047 // This will be a [[type]]*, except that a byref entry will just be
1048 // an i8**.
James Y Knight751fe282019-02-09 22:22:28 +00001049 Address blockField = projectField(capture.getIndex(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +00001050
1051 // Compute the address of the thing we're going to move into the
1052 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +00001053 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +00001054
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001055 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00001056 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +00001057 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001058 src = Address::invalid();
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001059 } else if (CI.isEscapingByref()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001060 if (BlockInfo && CI.isNested()) {
1061 // We need to use the capture from the enclosing block.
1062 const CGBlockInfo::Capture &enclosingCapture =
1063 BlockInfo->getCapture(variable);
1064
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001065 // This is a [[type]]*, except that a byref entry will just be an i8**.
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001066 src = Builder.CreateStructGEP(LoadBlockStruct(),
1067 enclosingCapture.getIndex(),
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001068 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +00001069 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001070 auto I = LocalDeclMap.find(variable);
1071 assert(I != LocalDeclMap.end());
1072 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +00001073 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001074 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001075 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001076 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1077 type.getNonReferenceType(), VK_LValue,
1078 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001079 src = EmitDeclRefLValue(&declRef).getAddress(*this);
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001080 };
John McCall351762c2011-02-07 10:33:21 +00001081
1082 // For byrefs, we just write the pointer to the byref struct into
1083 // the block field. There's no need to chase the forwarding
1084 // pointer at this point, since we're building something that will
1085 // live a shorter life than the stack byref anyway.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001086 if (CI.isEscapingByref()) {
John McCalle3dc1702011-02-15 09:22:45 +00001087 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +00001088 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001089 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +00001090 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +00001091 else
John McCall7f416cc2015-09-08 08:05:57 +00001092 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001093
John McCalle3dc1702011-02-15 09:22:45 +00001094 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +00001095 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +00001096
1097 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001098 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00001099 if (blockDecl->isConversionFromLambda()) {
1100 // If we have a lambda conversion, emit the expression
1101 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +00001102 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +00001103 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +00001104 AggValueSlot::IsDestructed,
1105 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001106 AggValueSlot::IsNotAliased,
1107 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001108 EmitAggExpr(copyExpr, Slot);
1109 } else {
1110 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
1111 }
John McCall351762c2011-02-07 10:33:21 +00001112
1113 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001114 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +00001115 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +00001116
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00001117 // If type is const-qualified, copy the value into the block field.
1118 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +00001119 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1120 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00001121 llvm::Value *value = Builder.CreateLoad(src, "captured");
1122 Builder.CreateStore(value, blockField);
1123
John McCall4d14a902013-04-08 23:27:49 +00001124 // If this is an ARC __strong block-pointer variable, don't do a
1125 // block copy.
1126 //
1127 // TODO: this can be generalized into the normal initialization logic:
1128 // we should never need to do a block-copy when initializing a local
1129 // variable, because the local variable's lifetime should be strictly
1130 // contained within the stack block's.
1131 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1132 type->isBlockPointerType()) {
1133 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +00001134 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +00001135 value = EmitARCRetainNonBlock(value);
1136
1137 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +00001138 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +00001139
1140 // Otherwise, fake up a POD copy into the block field.
1141 } else {
John McCall31168b02011-06-15 23:02:42 +00001142 // Fake up a new variable so that EmitScalarInit doesn't think
1143 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +00001144 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1145 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +00001146
John McCall93be3f72011-02-07 18:37:40 +00001147 // We use one of these or the other depending on whether the
1148 // reference is nested.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001149 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001150 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1151 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +00001152
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001153 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +00001154 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +00001155 // FIXME: Pass a specific location for the expr init so that the store is
1156 // attributed to a reasonable location - otherwise it may be attributed to
1157 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +00001158 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001159 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +00001160 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +00001161 }
1162
John McCall08ef4662011-11-10 08:15:53 +00001163 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001164 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +00001165 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1166 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +00001167 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +00001168 }
John McCall351762c2011-02-07 10:33:21 +00001169 }
1170
1171 // Cast to the converted block-pointer type, which happens (somewhat
1172 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001173 llvm::Value *result = Builder.CreatePointerCast(
1174 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001175
Yaxun Liufa13d012018-02-15 16:39:19 +00001176 if (IsOpenCL) {
1177 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1178 result);
1179 }
1180
John McCall351762c2011-02-07 10:33:21 +00001181 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001182}
1183
1184
Chris Lattnera5f58b02011-07-09 17:41:47 +00001185llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001186 if (BlockDescriptorType)
1187 return BlockDescriptorType;
1188
Chris Lattnera5f58b02011-07-09 17:41:47 +00001189 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001190 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001191
Mike Stump650c9322009-02-13 15:16:56 +00001192 // struct __block_descriptor {
1193 // unsigned long reserved;
1194 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001195 //
1196 // // later, the following will be added
1197 //
1198 // struct {
1199 // void (*copyHelper)();
1200 // void (*copyHelper)();
1201 // } helpers; // !!! optional
1202 //
1203 // const char *signature; // the block signature
1204 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001205 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001206 BlockDescriptorType = llvm::StructType::create(
1207 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001208
John McCall351762c2011-02-07 10:33:21 +00001209 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001210 unsigned AddrSpace = 0;
1211 if (getLangOpts().OpenCL)
1212 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1213 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001214 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001215}
1216
Chris Lattnera5f58b02011-07-09 17:41:47 +00001217llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +00001218 if (GenericBlockLiteralType)
1219 return GenericBlockLiteralType;
1220
Chris Lattnera5f58b02011-07-09 17:41:47 +00001221 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001222
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001223 if (getLangOpts().OpenCL) {
1224 // struct __opencl_block_literal_generic {
1225 // int __size;
1226 // int __align;
1227 // __generic void *__invoke;
1228 // /* custom fields */
1229 // };
1230 SmallVector<llvm::Type *, 8> StructFields(
1231 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1232 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1233 for (auto I : Helper->getCustomFieldTypes())
1234 StructFields.push_back(I);
1235 }
1236 GenericBlockLiteralType = llvm::StructType::create(
1237 StructFields, "struct.__opencl_block_literal_generic");
1238 } else {
1239 // struct __block_literal_generic {
1240 // void *__isa;
1241 // int __flags;
1242 // int __reserved;
1243 // void (*__invoke)(void *);
1244 // struct __block_descriptor *__descriptor;
1245 // };
1246 GenericBlockLiteralType =
1247 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1248 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1249 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001250
Mike Stump005c9a62009-02-13 15:25:34 +00001251 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001252}
1253
Yaxun Liu10712d92017-10-04 20:32:17 +00001254RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001255 ReturnValueSlot ReturnValue) {
Simon Pilgrim0abbb152019-10-04 15:01:54 +00001256 const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
John McCallb92ab1a2016-10-26 23:46:34 +00001257 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Andrew Savonichev43fceb22019-02-21 11:02:10 +00001258 llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1259 llvm::Value *Func = nullptr;
1260 QualType FnType = BPT->getPointeeType();
1261 ASTContext &Ctx = getContext();
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001262 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001263
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001264 if (getLangOpts().OpenCL) {
Andrew Savonichev43fceb22019-02-21 11:02:10 +00001265 // For OpenCL, BlockPtr is already casted to generic block literal.
1266
1267 // First argument of a block call is a generic block literal casted to
1268 // generic void pointer, i.e. i8 addrspace(4)*
1269 llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1270 BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
1271 QualType VoidPtrQualTy = Ctx.getPointerType(
1272 Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1273 Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1274 // And the rest of the arguments.
1275 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1276
1277 // We *can* call the block directly unless it is a function argument.
1278 if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1279 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1280 else {
1281 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1282 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1283 }
1284 } else {
1285 // Bitcast the block literal to a generic block literal.
1286 BlockPtr = Builder.CreatePointerCast(
1287 BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1288 // Get pointer to the block invoke function
1289 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1290
1291 // First argument is a block literal casted to a void pointer
1292 BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1293 Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1294 // And the rest of the arguments.
1295 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1296
1297 // Load the function.
1298 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001299 }
1300
John McCall85915252011-03-09 08:39:33 +00001301 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001302 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001303 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001304
Anders Carlsson5f50c652009-04-07 22:10:22 +00001305 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001306 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Chris Lattner2192fe52011-07-18 04:24:23 +00001308 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001309 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001310
John McCallb92ab1a2016-10-26 23:46:34 +00001311 // Prepare the callee.
1312 CGCallee Callee(CGCalleeInfo(), Func);
1313
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001314 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001315 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001316}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001317
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001318Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
John McCall351762c2011-02-07 10:33:21 +00001319 assert(BlockInfo && "evaluating block ref without block information?");
1320 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001321
John McCall351762c2011-02-07 10:33:21 +00001322 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001323 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001324
James Y Knight751fe282019-02-09 22:22:28 +00001325 Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1326 "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001327
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001328 if (variable->isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +00001329 // addr should be a void** right now. Load, then cast the result
1330 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001331
John McCall7f416cc2015-09-08 08:05:57 +00001332 auto &byrefInfo = getBlockByrefInfo(variable);
1333 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001334
John McCall7f416cc2015-09-08 08:05:57 +00001335 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1336 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001337
John McCall7f416cc2015-09-08 08:05:57 +00001338 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1339 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001340 }
1341
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001342 assert((!variable->isNonEscapingByref() ||
1343 capture.fieldType()->isReferenceType()) &&
1344 "the capture field of a non-escaping variable should have a "
1345 "reference type");
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001346 if (capture.fieldType()->isReferenceType())
1347 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001348
John McCall351762c2011-02-07 10:33:21 +00001349 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001350}
1351
George Burgess IVe3763372016-12-22 02:50:20 +00001352void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1353 llvm::Constant *Addr) {
1354 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1355 (void)Ok;
1356 assert(Ok && "Trying to replace an already-existing global block!");
1357}
1358
Mike Stump2d5a2872009-02-14 22:16:35 +00001359llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001360CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1361 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001362 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1363 return Block;
1364
George Burgess IV70d15b32016-11-03 02:21:43 +00001365 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1366 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001367
John McCall351762c2011-02-07 10:33:21 +00001368 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001369 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001370
John McCall351762c2011-02-07 10:33:21 +00001371 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001372 {
John McCall7f416cc2015-09-08 08:05:57 +00001373 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001374 CodeGenFunction(*this).GenerateBlockFunction(
1375 GlobalDecl(), blockInfo, LocalDeclMap,
1376 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001377 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001378
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001379 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001380}
1381
John McCall351762c2011-02-07 10:33:21 +00001382static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1383 const CGBlockInfo &blockInfo,
1384 llvm::Constant *blockFn) {
1385 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001386 // Callers should detect this case on their own: calling this function
1387 // generally requires computing layout information, which is a waste of time
1388 // if we've already emitted this block.
1389 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1390 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001391
1392 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001393 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001394 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001395
Yaxun Liu10712d92017-10-04 20:32:17 +00001396 bool IsOpenCL = CGM.getLangOpts().OpenCL;
David Chisnallc5a458c2018-08-09 08:02:42 +00001397 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
Yaxun Liu10712d92017-10-04 20:32:17 +00001398 if (!IsOpenCL) {
1399 // isa
David Chisnallc5a458c2018-08-09 08:02:42 +00001400 if (IsWindows)
1401 fields.addNullPointer(CGM.Int8PtrPtrTy);
1402 else
1403 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001404
Yaxun Liu10712d92017-10-04 20:32:17 +00001405 // __flags
1406 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1407 if (blockInfo.UsesStret)
1408 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001409
Yaxun Liu10712d92017-10-04 20:32:17 +00001410 fields.addInt(CGM.IntTy, flags.getBitMask());
1411
1412 // Reserved
1413 fields.addInt(CGM.IntTy, 0);
1414 } else {
1415 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1416 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1417 }
John McCall351762c2011-02-07 10:33:21 +00001418
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001419 // Function
1420 fields.add(blockFn);
1421
Yaxun Liu10712d92017-10-04 20:32:17 +00001422 if (!IsOpenCL) {
1423 // Descriptor
1424 fields.add(buildBlockDescriptor(CGM, blockInfo));
1425 } else if (auto *Helper =
1426 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1427 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1428 fields.add(I);
1429 }
1430 }
John McCall351762c2011-02-07 10:33:21 +00001431
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001432 unsigned AddrSpace = 0;
1433 if (CGM.getContext().getLangOpts().OpenCL)
1434 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1435
Akira Hatanaka6cb2d9d2019-06-14 22:06:28 +00001436 llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001437 "__block_literal_global", blockInfo.BlockAlign,
David Chisnallc5a458c2018-08-09 08:02:42 +00001438 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1439
Akira Hatanaka6cb2d9d2019-06-14 22:06:28 +00001440 literal->addAttribute("objc_arc_inert");
1441
David Chisnallc5a458c2018-08-09 08:02:42 +00001442 // Windows does not allow globals to be initialised to point to globals in
1443 // different DLLs. Any such variables must run code to initialise them.
1444 if (IsWindows) {
1445 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1446 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1447 &CGM.getModule());
1448 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1449 Init));
1450 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1451 b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1452 b.CreateRetVoid();
1453 // We can't use the normal LLVM global initialisation array, because we
1454 // need to specify that this runs early in library initialisation.
1455 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1456 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1457 Init, ".block_isa_init_ptr");
1458 InitVar->setSection(".CRT$XCLa");
1459 CGM.addUsedGlobal(InitVar);
1460 }
John McCall351762c2011-02-07 10:33:21 +00001461
1462 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001463 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001464 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001465 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001466 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001467 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001468 if (CGM.getContext().getLangOpts().OpenCL)
1469 CGM.getOpenCLRuntime().recordBlockInfo(
1470 blockInfo.BlockExpression,
1471 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001472 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001473}
1474
John McCall7f416cc2015-09-08 08:05:57 +00001475void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1476 unsigned argNum,
1477 llvm::Value *arg) {
1478 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1479
Adrian Prantl356347b2017-10-26 20:08:52 +00001480 // Allocate a stack slot like for any local variable to guarantee optimal
1481 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1482 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1483 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001484 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001485 if (CGM.getCodeGenOpts().getDebugInfo() >=
1486 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001487 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001488 DI->EmitDeclareOfBlockLiteralArgVariable(
1489 *BlockInfo, D->getName(), argNum,
1490 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001491 }
1492 }
1493
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001494 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
John McCall7f416cc2015-09-08 08:05:57 +00001495 ApplyDebugLocation Scope(*this, StartLoc);
1496
1497 // Instead of messing around with LocalDeclMap, just set the value
1498 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001499 BlockPointer = Builder.CreatePointerCast(
1500 arg,
1501 BlockInfo->StructureType->getPointerTo(
1502 getContext().getLangOpts().OpenCL
1503 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1504 : 0),
1505 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001506}
1507
1508Address CodeGenFunction::LoadBlockStruct() {
1509 assert(BlockInfo && "not in a block invocation function!");
1510 assert(BlockPointer && "no block pointer set!");
1511 return Address(BlockPointer, BlockInfo->BlockAlign);
1512}
1513
Mike Stump4446dcf2009-03-05 08:32:30 +00001514llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001515CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1516 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001517 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001518 bool IsLambdaConversionToBlock,
1519 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001520 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001521
Fariborz Jahanian63628032012-06-26 16:06:38 +00001522 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001523
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001524 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001525
John McCall351762c2011-02-07 10:33:21 +00001526 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001527
Mike Stump5469f292009-03-13 23:34:28 +00001528 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001529 // to be local to this function as well, in case they're directly
1530 // referenced in a block.
1531 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001532 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001533 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001534 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001535 }
1536
John McCall351762c2011-02-07 10:33:21 +00001537 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001538
John McCall351762c2011-02-07 10:33:21 +00001539 // Build the argument list.
1540 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001541
John McCall351762c2011-02-07 10:33:21 +00001542 // The first argument is the block pointer. Just take it as a void*
1543 // and cast it later.
1544 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001545
1546 // For OpenCL passed block pointer can be private AS local variable or
1547 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001548 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001549 // generic AS in one implementation.
1550 if (getLangOpts().OpenCL)
1551 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1552 getContext().VoidTy, LangAS::opencl_generic));
1553
Mike Stump7fe9cc12009-10-21 03:49:08 +00001554 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001555
Alexey Bataev56223232017-06-09 13:40:18 +00001556 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1557 SourceLocation(), II, selfTy,
1558 ImplicitParamDecl::ObjCSelf);
1559 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001560
John McCall351762c2011-02-07 10:33:21 +00001561 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001562 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001563
John McCall351762c2011-02-07 10:33:21 +00001564 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001565 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001566 const CGFunctionInfo &fnInfo =
1567 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001568 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001569 blockInfo.UsesStret = true;
1570
John McCalla729c622012-02-17 03:33:10 +00001571 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001572
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001573 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001574 llvm::Function *fn = llvm::Function::Create(
1575 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001576 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001577
Yaxun Liu10712d92017-10-04 20:32:17 +00001578 if (BuildGlobalBlock) {
1579 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1580 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1581 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001582 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001583 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1584 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001585
John McCall351762c2011-02-07 10:33:21 +00001586 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001587 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001588 blockDecl->getLocation(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001589 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
Mike Stumpb7074c02009-02-13 15:32:32 +00001590
John McCall147d0212011-02-22 22:38:33 +00001591 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001592
Adrian Prantl0f6df002013-03-29 19:20:35 +00001593 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1594 // won't delete the dbg.declare intrinsics for captured variables.
1595 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1596 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1597 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001598 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1599 getPointerAlign(),
1600 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001601 // Set the DebugLocation to empty, so the store is recognized as a
1602 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001603 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001604 Builder.CreateStore(BlockPointer, Alloca);
1605 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001606 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001607
John McCall87fe5d52010-05-20 01:18:31 +00001608 // If we have a C++ 'this' reference, go ahead and force it into
1609 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001610 if (blockDecl->capturesCXXThis()) {
James Y Knight751fe282019-02-09 22:22:28 +00001611 Address addr = Builder.CreateStructGEP(
1612 LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001613 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001614 }
1615
John McCall351762c2011-02-07 10:33:21 +00001616 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001617 for (const auto &CI : blockDecl->captures()) {
1618 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001619 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1620 if (!capture.isConstant()) continue;
1621
John McCall7f416cc2015-09-08 08:05:57 +00001622 CharUnits align = getContext().getDeclAlign(variable);
1623 Address alloca =
1624 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001625
John McCall7f416cc2015-09-08 08:05:57 +00001626 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001627
John McCall7f416cc2015-09-08 08:05:57 +00001628 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001629 }
1630
John McCall113bee02012-03-10 09:33:50 +00001631 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001632 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1633 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1634 --entry_ptr;
1635
Eli Friedman2495ab02012-02-25 02:48:22 +00001636 if (IsLambdaConversionToBlock)
1637 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001638 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001639 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001640 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001641 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001642 }
Mike Stump017460a2009-10-01 22:29:41 +00001643
Mike Stump7d699112009-10-01 00:27:30 +00001644 // Remember where we were...
1645 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001646
Mike Stump7d699112009-10-01 00:27:30 +00001647 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001648 ++entry_ptr;
1649 Builder.SetInsertPoint(entry, entry_ptr);
1650
John McCall113bee02012-03-10 09:33:50 +00001651 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001652 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001653 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001654 for (const auto &CI : blockDecl->captures()) {
1655 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001656 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001657
Benjamin Kramer8c305922016-02-02 11:06:51 +00001658 if (CGM.getCodeGenOpts().getDebugInfo() >=
1659 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001660 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1661 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001662 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001663 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1664 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001665 continue;
1666 }
John McCall351762c2011-02-07 10:33:21 +00001667
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001668 DI->EmitDeclareOfBlockDeclRefVariable(
1669 variable, BlockPointerDbgLoc, Builder, blockInfo,
1670 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001671 }
Mike Stump2e722b92009-09-30 02:43:10 +00001672 }
Manman Renab08a9a2013-01-04 18:51:35 +00001673 // Recover location if it was changed in the above loop.
1674 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001675 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001676 }
John McCall351762c2011-02-07 10:33:21 +00001677
Mike Stump7d699112009-10-01 00:27:30 +00001678 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001679 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001680 Builder.ClearInsertionPoint();
1681 else
1682 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001683
John McCall351762c2011-02-07 10:33:21 +00001684 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001685
John McCall351762c2011-02-07 10:33:21 +00001686 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001687}
Mike Stump1db7d042009-02-28 09:07:16 +00001688
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001689static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1690computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1691 const LangOptions &LangOpts) {
1692 if (CI.getCopyExpr()) {
1693 assert(!CI.isByRef());
1694 // don't bother computing flags
1695 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1696 }
1697 BlockFieldFlags Flags;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001698 if (CI.isEscapingByref()) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001699 Flags = BLOCK_FIELD_IS_BYREF;
1700 if (T.isObjCGCWeak())
1701 Flags |= BLOCK_FIELD_IS_WEAK;
1702 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1703 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001704
1705 Flags = BLOCK_FIELD_IS_OBJECT;
1706 bool isBlockPointer = T->isBlockPointerType();
1707 if (isBlockPointer)
1708 Flags = BLOCK_FIELD_IS_BLOCK;
1709
Akira Hatanaka7275da02018-02-28 07:15:55 +00001710 switch (T.isNonTrivialToPrimitiveCopy()) {
1711 case QualType::PCK_Struct:
1712 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1713 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001714 case QualType::PCK_ARCWeak:
1715 // We need to register __weak direct captures with the runtime.
1716 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001717 case QualType::PCK_ARCStrong:
1718 // We need to retain the copied value for __strong direct captures.
1719 // If it's a block pointer, we have to copy the block and assign that to
1720 // the destination pointer, so we might as well use _Block_object_assign.
1721 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001722 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1723 : BlockCaptureEntityKind::BlockObject,
1724 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001725 case QualType::PCK_Trivial:
1726 case QualType::PCK_VolatileTrivial: {
1727 if (!T->isObjCRetainableType())
1728 // For all other types, the memcpy is fine.
1729 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1730
1731 // Special rules for ARC captures:
1732 Qualifiers QS = T.getQualifiers();
1733
Akira Hatanaka7275da02018-02-28 07:15:55 +00001734 // Non-ARC captures of retainable pointers are strong and
1735 // therefore require a call to _Block_object_assign.
1736 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1737 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1738
1739 // Otherwise the memcpy is fine.
1740 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001741 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001742 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001743 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001744}
1745
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001746static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1747computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1748 const LangOptions &LangOpts);
1749
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001750/// Find the set of block captures that need to be explicitly copied or destroy.
1751static void findBlockCapturedManagedEntities(
1752 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001753 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001754 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1755 const VarDecl *Variable = CI.getVariable();
1756 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1757 if (Capture.isConstant())
1758 continue;
1759
Akira Hatanaka2a5e4632018-08-22 13:41:19 +00001760 QualType VT = Capture.fieldType();
1761 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1762 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001763 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1764 DisposeInfo.first != BlockCaptureEntityKind::None)
1765 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1766 CopyInfo.second, DisposeInfo.second, CI,
1767 Capture);
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001768 }
Akira Hatanaka9978da32018-08-10 15:09:24 +00001769
1770 // Sort the captures by offset.
Fangrui Song55fab262018-09-26 22:16:28 +00001771 llvm::sort(ManagedCaptures);
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001772}
1773
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001774namespace {
1775/// Release a __block variable.
1776struct CallBlockRelease final : EHScopeStack::Cleanup {
1777 Address Addr;
1778 BlockFieldFlags FieldFlags;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001779 bool LoadBlockVarAddr, CanThrow;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001780
Akira Hatanaka9978da32018-08-10 15:09:24 +00001781 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1782 bool CT)
1783 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1784 CanThrow(CT) {}
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001785
1786 void Emit(CodeGenFunction &CGF, Flags flags) override {
1787 llvm::Value *BlockVarAddr;
1788 if (LoadBlockVarAddr) {
1789 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1790 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1791 } else {
1792 BlockVarAddr = Addr.getPointer();
1793 }
1794
Akira Hatanaka9978da32018-08-10 15:09:24 +00001795 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001796 }
1797};
1798} // end anonymous namespace
1799
Akira Hatanaka9978da32018-08-10 15:09:24 +00001800/// Check if \p T is a C++ class that has a destructor that can throw.
1801bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1802 if (const auto *RD = T->getAsCXXRecordDecl())
1803 if (const CXXDestructorDecl *DD = RD->getDestructor())
Simon Pilgrim0abbb152019-10-04 15:01:54 +00001804 return DD->getType()->castAs<FunctionProtoType>()->canThrow();
Akira Hatanaka9978da32018-08-10 15:09:24 +00001805 return false;
1806}
1807
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001808// Return a string that has the information about a capture.
1809static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1810 CaptureStrKind StrKind,
1811 CharUnits BlockAlignment,
1812 CodeGenModule &CGM) {
1813 std::string Str;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001814 ASTContext &Ctx = CGM.getContext();
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001815 const BlockDecl::Capture &CI = *E.CI;
1816 QualType CaptureTy = CI.getVariable()->getType();
Akira Hatanaka9978da32018-08-10 15:09:24 +00001817
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001818 BlockCaptureEntityKind Kind;
1819 BlockFieldFlags Flags;
1820
1821 // CaptureStrKind::Merged should be passed only when the operations and the
1822 // flags are the same for copy and dispose.
1823 assert((StrKind != CaptureStrKind::Merged ||
1824 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1825 "different operations and flags");
1826
1827 if (StrKind == CaptureStrKind::DisposeHelper) {
1828 Kind = E.DisposeKind;
1829 Flags = E.DisposeFlags;
1830 } else {
1831 Kind = E.CopyKind;
1832 Flags = E.CopyFlags;
1833 }
1834
1835 switch (Kind) {
1836 case BlockCaptureEntityKind::CXXRecord: {
1837 Str += "c";
1838 SmallString<256> TyStr;
1839 llvm::raw_svector_ostream Out(TyStr);
Akira Hatanaka32e0a582018-10-20 05:45:01 +00001840 CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001841 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1842 break;
1843 }
1844 case BlockCaptureEntityKind::ARCWeak:
1845 Str += "w";
1846 break;
1847 case BlockCaptureEntityKind::ARCStrong:
1848 Str += "s";
1849 break;
1850 case BlockCaptureEntityKind::BlockObject: {
1851 const VarDecl *Var = CI.getVariable();
1852 unsigned F = Flags.getBitMask();
1853 if (F & BLOCK_FIELD_IS_BYREF) {
1854 Str += "r";
1855 if (F & BLOCK_FIELD_IS_WEAK)
1856 Str += "w";
1857 else {
1858 // If CaptureStrKind::Merged is passed, check both the copy expression
1859 // and the destructor.
1860 if (StrKind != CaptureStrKind::DisposeHelper) {
1861 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1862 Str += "c";
1863 }
1864 if (StrKind != CaptureStrKind::CopyHelper) {
1865 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1866 Str += "d";
1867 }
1868 }
1869 } else {
1870 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1871 if (F == BLOCK_FIELD_IS_BLOCK)
1872 Str += "b";
1873 else
1874 Str += "o";
1875 }
1876 break;
1877 }
1878 case BlockCaptureEntityKind::NonTrivialCStruct: {
1879 bool IsVolatile = CaptureTy.isVolatileQualified();
1880 CharUnits Alignment =
1881 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1882
1883 Str += "n";
1884 std::string FuncStr;
1885 if (StrKind == CaptureStrKind::DisposeHelper)
1886 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1887 CaptureTy, Alignment, IsVolatile, Ctx);
1888 else
1889 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1890 // It has all the information that the destructor string has.
1891 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1892 CaptureTy, Alignment, IsVolatile, Ctx);
1893 // The underscore is necessary here because non-trivial copy constructor
1894 // and destructor strings can start with a number.
1895 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1896 break;
1897 }
1898 case BlockCaptureEntityKind::None:
1899 break;
1900 }
1901
1902 return Str;
1903}
1904
1905static std::string getCopyDestroyHelperFuncName(
1906 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1907 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1908 assert((StrKind == CaptureStrKind::CopyHelper ||
1909 StrKind == CaptureStrKind::DisposeHelper) &&
1910 "unexpected CaptureStrKind");
1911 std::string Name = StrKind == CaptureStrKind::CopyHelper
1912 ? "__copy_helper_block_"
1913 : "__destroy_helper_block_";
Akira Hatanaka9978da32018-08-10 15:09:24 +00001914 if (CGM.getLangOpts().Exceptions)
1915 Name += "e";
1916 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1917 Name += "a";
1918 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1919
1920 for (const BlockCaptureManagedEntity &E : Captures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001921 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001922 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001923 }
1924
1925 return Name;
1926}
1927
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001928static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1929 Address Field, QualType CaptureType,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001930 BlockFieldFlags Flags, bool ForCopyHelper,
1931 VarDecl *Var, CodeGenFunction &CGF) {
1932 bool EHOnly = ForCopyHelper;
1933
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001934 switch (CaptureKind) {
1935 case BlockCaptureEntityKind::CXXRecord:
1936 case BlockCaptureEntityKind::ARCWeak:
1937 case BlockCaptureEntityKind::NonTrivialCStruct:
1938 case BlockCaptureEntityKind::ARCStrong: {
1939 if (CaptureType.isDestructedType() &&
1940 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1941 CodeGenFunction::Destroyer *Destroyer =
1942 CaptureKind == BlockCaptureEntityKind::ARCStrong
1943 ? CodeGenFunction::destroyARCStrongImprecise
1944 : CGF.getDestroyer(CaptureType.isDestructedType());
1945 CleanupKind Kind =
1946 EHOnly ? EHCleanup
1947 : CGF.getCleanupKind(CaptureType.isDestructedType());
1948 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1949 }
1950 break;
1951 }
1952 case BlockCaptureEntityKind::BlockObject: {
1953 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1954 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001955 // Calls to _Block_object_dispose along the EH path in the copy helper
1956 // function don't throw as newly-copied __block variables always have a
1957 // reference count of 2.
1958 bool CanThrow =
1959 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1960 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1961 CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001962 }
1963 break;
1964 }
1965 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001966 break;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001967 }
1968}
1969
Akira Hatanaka9978da32018-08-10 15:09:24 +00001970static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1971 llvm::Function *Fn,
1972 const CGFunctionInfo &FI,
1973 CodeGenModule &CGM) {
1974 if (CapturesNonExternalType) {
1975 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1976 } else {
1977 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1978 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Erich Keanede6480a32018-11-13 15:48:08 +00001979 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001980 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1981 }
1982}
John McCallf593b102013-01-22 03:56:22 +00001983/// Generate the copy-helper function for a block closure object:
1984/// static void block_copy_helper(block_t *dst, block_t *src);
1985/// The runtime will have previously initialized 'dst' by doing a
1986/// bit-copy of 'src'.
1987///
1988/// Note that this copies an entire block closure object to the heap;
1989/// it should not be confused with a 'byref copy helper', which moves
1990/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001991llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001992CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001993 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001994 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001995 std::string FuncName =
1996 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001997 CaptureStrKind::CopyHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001998
1999 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00002000 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002001
John McCall351762c2011-02-07 10:33:21 +00002002 ASTContext &C = getContext();
2003
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002004 QualType ReturnTy = C.VoidTy;
2005
John McCall351762c2011-02-07 10:33:21 +00002006 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002007 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002008 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002009 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002010 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002011
John McCallc56a8b32016-03-11 04:30:31 +00002012 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002013 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00002014
John McCall351762c2011-02-07 10:33:21 +00002015 // FIXME: it would be nice if these were mergeable with things with
2016 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00002017 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00002018
2019 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00002020 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2021 FuncName, &CGM.getModule());
Saleem Abdulrasool89628922019-02-22 16:29:50 +00002022 if (CGM.supportsCOMDAT())
2023 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
Mike Stump0c743272009-03-06 01:33:24 +00002024
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002025 IdentifierInfo *II = &C.Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00002026
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002027 SmallVector<QualType, 2> ArgTys;
2028 ArgTys.push_back(C.VoidPtrTy);
2029 ArgTys.push_back(C.VoidPtrTy);
2030 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2031
2032 FunctionDecl *FD = FunctionDecl::Create(
2033 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2034 FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002035
Akira Hatanaka9978da32018-08-10 15:09:24 +00002036 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2037 CGM);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002038 StartFunction(FD, ReturnTy, Fn, FI, args);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002039 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Chris Lattner2192fe52011-07-18 04:24:23 +00002040 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002041
Alexey Bataev56223232017-06-09 13:40:18 +00002042 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002043 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002044 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002045
Alexey Bataev56223232017-06-09 13:40:18 +00002046 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002047 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002048 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002049
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002050 for (const auto &CopiedCapture : CopiedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002051 const BlockDecl::Capture &CI = *CopiedCapture.CI;
2052 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002053 QualType captureType = CI.getVariable()->getType();
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002054 BlockFieldFlags flags = CopiedCapture.CopyFlags;
John McCall351762c2011-02-07 10:33:21 +00002055
2056 unsigned index = capture.getIndex();
James Y Knight751fe282019-02-09 22:22:28 +00002057 Address srcField = Builder.CreateStructGEP(src, index);
2058 Address dstField = Builder.CreateStructGEP(dst, index);
John McCall351762c2011-02-07 10:33:21 +00002059
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002060 switch (CopiedCapture.CopyKind) {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002061 case BlockCaptureEntityKind::CXXRecord:
2062 // If there's an explicit copy expression, we do that.
2063 assert(CI.getCopyExpr() && "copy expression for variable is missing");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002064 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002065 break;
2066 case BlockCaptureEntityKind::ARCWeak:
John McCall31168b02011-06-15 23:02:42 +00002067 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002068 break;
2069 case BlockCaptureEntityKind::NonTrivialCStruct: {
2070 // If this is a C struct that requires non-trivial copy construction,
2071 // emit a call to its copy constructor.
Akira Hatanaka7275da02018-02-28 07:15:55 +00002072 QualType varType = CI.getVariable()->getType();
2073 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2074 MakeAddrLValue(srcField, varType));
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002075 break;
2076 }
2077 case BlockCaptureEntityKind::ARCStrong: {
John McCall351762c2011-02-07 10:33:21 +00002078 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002079 // At -O0, store null into the destination field (so that the
2080 // storeStrong doesn't over-release) and then call storeStrong.
2081 // This is a workaround to not having an initStrong call.
2082 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2083 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2084 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2085 Builder.CreateStore(null, dstField);
2086 EmitARCStoreStrongCall(dstField, srcValue, true);
John McCalle68b8f42012-10-17 02:28:37 +00002087
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002088 // With optimization enabled, take advantage of the fact that
2089 // the blocks runtime guarantees a memcpy of the block data, and
2090 // just emit a retain of the src field.
John McCalle68b8f42012-10-17 02:28:37 +00002091 } else {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002092 EmitARCRetainNonBlock(srcValue);
John McCall882987f2013-02-28 19:01:20 +00002093
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002094 // Unless EH cleanup is required, we don't need this anymore, so kill
2095 // it. It's not quite worth the annoyance to avoid creating it in the
2096 // first place.
2097 if (!needsEHCleanup(captureType.isDestructedType()))
2098 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00002099 }
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002100 break;
2101 }
2102 case BlockCaptureEntityKind::BlockObject: {
2103 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2104 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2105 llvm::Value *dstAddr =
2106 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2107 llvm::Value *args[] = {
2108 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2109 };
2110
2111 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2112 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2113 else
2114 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2115 break;
2116 }
2117 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002118 continue;
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002119 }
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002120
2121 // Ensure that we destroy the copied object if an exception is thrown later
2122 // in the helper function.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002123 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002124 /*ForCopyHelper*/ true, CI.getVariable(), *this);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002125 }
2126
John McCallad7c5c12011-02-08 08:22:06 +00002127 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002128
John McCalle3dc1702011-02-15 09:22:45 +00002129 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00002130}
2131
Akira Hatanaka7275da02018-02-28 07:15:55 +00002132static BlockFieldFlags
2133getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2134 QualType T) {
2135 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2136 if (T->isBlockPointerType())
2137 Flags = BLOCK_FIELD_IS_BLOCK;
2138 return Flags;
2139}
2140
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002141static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2142computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2143 const LangOptions &LangOpts) {
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002144 if (CI.isEscapingByref()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002145 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002146 if (T.isObjCGCWeak())
2147 Flags |= BLOCK_FIELD_IS_WEAK;
2148 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2149 }
2150
Akira Hatanaka7275da02018-02-28 07:15:55 +00002151 switch (T.isDestructedType()) {
2152 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002153 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00002154 case QualType::DK_objc_strong_lifetime:
2155 // Use objc_storeStrong for __strong direct captures; the
2156 // dynamic tools really like it when we do this.
2157 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2158 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2159 case QualType::DK_objc_weak_lifetime:
2160 // Support __weak direct captures.
2161 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2162 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2163 case QualType::DK_nontrivial_c_struct:
2164 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2165 BlockFieldFlags());
2166 case QualType::DK_none: {
2167 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2168 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2169 !LangOpts.ObjCAutoRefCount)
2170 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2171 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2172 // Otherwise, we have nothing to do.
2173 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002174 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00002175 }
Nico Weberb3897eb2018-02-28 19:28:47 +00002176 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002177}
2178
John McCallf593b102013-01-22 03:56:22 +00002179/// Generate the destroy-helper function for a block closure object:
2180/// static void block_destroy_helper(block_t *theBlock);
2181///
2182/// Note that this destroys a heap-allocated block closure object;
2183/// it should not be confused with a 'byref destroy helper', which
2184/// destroys the heap-allocated contents of an individual __block
2185/// variable.
John McCall351762c2011-02-07 10:33:21 +00002186llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00002187CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002188 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002189 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002190 std::string FuncName =
2191 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002192 CaptureStrKind::DisposeHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002193
2194 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00002195 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002196
John McCall351762c2011-02-07 10:33:21 +00002197 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00002198
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002199 QualType ReturnTy = C.VoidTy;
2200
John McCall351762c2011-02-07 10:33:21 +00002201 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002202 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002203 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002204
John McCallc56a8b32016-03-11 04:30:31 +00002205 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002206 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00002207
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002208 // FIXME: We'd like to put these into a mergable by content, with
2209 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00002210 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00002211
2212 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00002213 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2214 FuncName, &CGM.getModule());
Saleem Abdulrasool89628922019-02-22 16:29:50 +00002215 if (CGM.supportsCOMDAT())
2216 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
Mike Stump0c743272009-03-06 01:33:24 +00002217
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002218 IdentifierInfo *II = &C.Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00002219
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002220 SmallVector<QualType, 1> ArgTys;
2221 ArgTys.push_back(C.VoidPtrTy);
2222 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2223
2224 FunctionDecl *FD = FunctionDecl::Create(
2225 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2226 FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002227
Akira Hatanaka9978da32018-08-10 15:09:24 +00002228 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2229 CGM);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002230 StartFunction(FD, ReturnTy, Fn, FI, args);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002231 markAsIgnoreThreadCheckingAtRuntime(Fn);
2232
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002233 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
Mike Stump6f7d9f82009-03-07 02:53:18 +00002234
Chris Lattner2192fe52011-07-18 04:24:23 +00002235 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00002236
Alexey Bataev56223232017-06-09 13:40:18 +00002237 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002238 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002239 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00002240
John McCallad7c5c12011-02-08 08:22:06 +00002241 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00002242
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002243 for (const auto &DestroyedCapture : DestroyedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002244 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2245 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002246 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
John McCall351762c2011-02-07 10:33:21 +00002247
James Y Knight751fe282019-02-09 22:22:28 +00002248 Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
John McCall351762c2011-02-07 10:33:21 +00002249
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002250 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002251 CI.getVariable()->getType(), flags,
2252 /*ForCopyHelper*/ false, CI.getVariable(), *this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00002253 }
2254
John McCall351762c2011-02-07 10:33:21 +00002255 cleanups.ForceCleanup();
2256
John McCallad7c5c12011-02-08 08:22:06 +00002257 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002258
John McCalle3dc1702011-02-15 09:22:45 +00002259 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00002260}
2261
John McCallf9b056b2011-03-31 08:03:29 +00002262namespace {
2263
2264/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00002265class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002266 BlockFieldFlags Flags;
2267
2268public:
2269 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00002270 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00002271
John McCall7f416cc2015-09-08 08:05:57 +00002272 void emitCopy(CodeGenFunction &CGF, Address destField,
2273 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002274 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2275
2276 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2277 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2278
2279 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2280
2281 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
James Y Knight9871db02019-02-05 16:42:33 +00002282 llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00002283
John McCall7f416cc2015-09-08 08:05:57 +00002284 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00002285 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00002286 }
2287
John McCall7f416cc2015-09-08 08:05:57 +00002288 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002289 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2290 llvm::Value *value = CGF.Builder.CreateLoad(field);
2291
Akira Hatanaka9978da32018-08-10 15:09:24 +00002292 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
John McCallf9b056b2011-03-31 08:03:29 +00002293 }
2294
Craig Topper4f12f102014-03-12 06:41:41 +00002295 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002296 id.AddInteger(Flags.getBitMask());
2297 }
2298};
2299
John McCall31168b02011-06-15 23:02:42 +00002300/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00002301class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002302public:
John McCall7f416cc2015-09-08 08:05:57 +00002303 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002304
John McCall7f416cc2015-09-08 08:05:57 +00002305 void emitCopy(CodeGenFunction &CGF, Address destField,
2306 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002307 CGF.EmitARCMoveWeak(destField, srcField);
2308 }
2309
John McCall7f416cc2015-09-08 08:05:57 +00002310 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00002311 CGF.EmitARCDestroyWeak(field);
2312 }
2313
Craig Topper4f12f102014-03-12 06:41:41 +00002314 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002315 // 0 is distinguishable from all pointers and byref flags
2316 id.AddInteger(0);
2317 }
2318};
2319
2320/// Emits the copy/dispose helpers for an ARC __block __strong variable
2321/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002322class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002323public:
John McCall7f416cc2015-09-08 08:05:57 +00002324 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002325
John McCall7f416cc2015-09-08 08:05:57 +00002326 void emitCopy(CodeGenFunction &CGF, Address destField,
2327 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002328 // Do a "move" by copying the value and then zeroing out the old
2329 // variable.
2330
John McCall7f416cc2015-09-08 08:05:57 +00002331 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002332
John McCall31168b02011-06-15 23:02:42 +00002333 llvm::Value *null =
2334 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00002335
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002336 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002337 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002338 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2339 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2340 return;
2341 }
John McCall7f416cc2015-09-08 08:05:57 +00002342 CGF.Builder.CreateStore(value, destField);
2343 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00002344 }
2345
John McCall7f416cc2015-09-08 08:05:57 +00002346 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002347 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00002348 }
2349
Craig Topper4f12f102014-03-12 06:41:41 +00002350 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002351 // 1 is distinguishable from all pointers and byref flags
2352 id.AddInteger(1);
2353 }
2354};
2355
John McCall3a237aa2011-11-09 03:17:26 +00002356/// Emits the copy/dispose helpers for an ARC __block __strong
2357/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002358class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00002359public:
John McCall7f416cc2015-09-08 08:05:57 +00002360 ARCStrongBlockByrefHelpers(CharUnits alignment)
2361 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00002362
John McCall7f416cc2015-09-08 08:05:57 +00002363 void emitCopy(CodeGenFunction &CGF, Address destField,
2364 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00002365 // Do the copy with objc_retainBlock; that's all that
2366 // _Block_object_assign would do anyway, and we'd have to pass the
2367 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00002368 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00002369 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00002370 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00002371 }
2372
John McCall7f416cc2015-09-08 08:05:57 +00002373 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002374 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00002375 }
2376
Craig Topper4f12f102014-03-12 06:41:41 +00002377 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00002378 // 2 is distinguishable from all pointers and byref flags
2379 id.AddInteger(2);
2380 }
2381};
2382
John McCallf9b056b2011-03-31 08:03:29 +00002383/// Emits the copy/dispose helpers for a __block variable with a
2384/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002385class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002386 QualType VarType;
2387 const Expr *CopyExpr;
2388
2389public:
2390 CXXByrefHelpers(CharUnits alignment, QualType type,
2391 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002392 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002393
Craig Topper8a13c412014-05-21 05:09:00 +00002394 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002395 void emitCopy(CodeGenFunction &CGF, Address destField,
2396 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002397 if (!CopyExpr) return;
2398 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2399 }
2400
John McCall7f416cc2015-09-08 08:05:57 +00002401 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002402 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2403 CGF.PushDestructorCleanup(VarType, field);
2404 CGF.PopCleanupBlocks(cleanupDepth);
2405 }
2406
Craig Topper4f12f102014-03-12 06:41:41 +00002407 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002408 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2409 }
2410};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002411
2412/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2413/// C struct.
2414class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2415 QualType VarType;
2416
2417public:
2418 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2419 : BlockByrefHelpers(alignment), VarType(type) {}
2420
2421 void emitCopy(CodeGenFunction &CGF, Address destField,
2422 Address srcField) override {
2423 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2424 CGF.MakeAddrLValue(srcField, VarType));
2425 }
2426
2427 bool needsDispose() const override {
2428 return VarType.isDestructedType();
2429 }
2430
2431 void emitDispose(CodeGenFunction &CGF, Address field) override {
2432 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2433 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2434 CGF.PopCleanupBlocks(cleanupDepth);
2435 }
2436
2437 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2438 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2439 }
2440};
John McCallf9b056b2011-03-31 08:03:29 +00002441} // end anonymous namespace
2442
2443static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002444generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2445 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002446 ASTContext &Context = CGF.getContext();
2447
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002448 QualType ReturnTy = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002449
John McCalla738c252011-03-09 04:27:21 +00002450 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002451 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002452 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002453
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002454 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002455 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002456
John McCallc56a8b32016-03-11 04:30:31 +00002457 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002458 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002459
John McCall7f416cc2015-09-08 08:05:57 +00002460 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002461
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002462 // FIXME: We'd like to put these into a mergable by content, with
2463 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002464 llvm::Function *Fn =
2465 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002466 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002467
2468 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002469 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002470
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002471 SmallVector<QualType, 2> ArgTys;
2472 ArgTys.push_back(Context.VoidPtrTy);
2473 ArgTys.push_back(Context.VoidPtrTy);
2474 QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2475
2476 FunctionDecl *FD = FunctionDecl::Create(
2477 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2478 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
John McCall31168b02011-06-15 23:02:42 +00002479
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002480 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002481
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002482 CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002483
John McCall7f416cc2015-09-08 08:05:57 +00002484 if (generator.needsCopy()) {
2485 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002486
John McCallf9b056b2011-03-31 08:03:29 +00002487 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002488 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002489 destField = Address(CGF.Builder.CreateLoad(destField),
2490 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002491 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002492 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2493 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002494
John McCallf9b056b2011-03-31 08:03:29 +00002495 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002496 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002497 srcField = Address(CGF.Builder.CreateLoad(srcField),
2498 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002499 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002500 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2501 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002502
John McCall7f416cc2015-09-08 08:05:57 +00002503 generator.emitCopy(CGF, destField, srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002504 }
John McCallf9b056b2011-03-31 08:03:29 +00002505
2506 CGF.FinishFunction();
2507
2508 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002509}
2510
John McCallf9b056b2011-03-31 08:03:29 +00002511/// Build the copy helper for a __block variable.
2512static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002513 const BlockByrefInfo &byrefInfo,
2514 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002515 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002516 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002517}
2518
2519/// Generate code for a __block variable's dispose helper.
2520static llvm::Constant *
2521generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002522 const BlockByrefInfo &byrefInfo,
2523 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002524 ASTContext &Context = CGF.getContext();
2525 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002526
John McCalla738c252011-03-09 04:27:21 +00002527 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002528 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2529 ImplicitParamDecl::Other);
2530 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002531
John McCallc56a8b32016-03-11 04:30:31 +00002532 const CGFunctionInfo &FI =
2533 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002534
John McCall7f416cc2015-09-08 08:05:57 +00002535 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002536
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002537 // FIXME: We'd like to put these into a mergable by content, with
2538 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002539 llvm::Function *Fn =
2540 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002541 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002542 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002543
2544 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002545 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002546
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002547 SmallVector<QualType, 1> ArgTys;
2548 ArgTys.push_back(Context.VoidPtrTy);
2549 QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2550
2551 FunctionDecl *FD = FunctionDecl::Create(
2552 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2553 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002554
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002555 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002556
Adrian Prantl22e66b42014-04-11 01:13:04 +00002557 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002558
John McCall7f416cc2015-09-08 08:05:57 +00002559 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002560 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002561 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2562 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2563 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2564 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002565
John McCall7f416cc2015-09-08 08:05:57 +00002566 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002567 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002568
John McCallf9b056b2011-03-31 08:03:29 +00002569 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002570
John McCallf9b056b2011-03-31 08:03:29 +00002571 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002572}
2573
John McCallf9b056b2011-03-31 08:03:29 +00002574/// Build the dispose helper for a __block variable.
2575static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002576 const BlockByrefInfo &byrefInfo,
2577 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002578 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002579 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002580}
2581
John McCallf593b102013-01-22 03:56:22 +00002582/// Lazily build the copy and dispose helpers for a __block variable
2583/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002584template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002585static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2586 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002587 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002588 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002589
2590 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002591 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002592 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2593 if (node) return static_cast<T*>(node);
2594
John McCall7f416cc2015-09-08 08:05:57 +00002595 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2596 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002597
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002598 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002599 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2600 return copy;
2601}
2602
John McCallf593b102013-01-22 03:56:22 +00002603/// Build the copy and dispose helpers for the given __block variable
2604/// emission. Places the helpers in the global cache. Returns null
2605/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002606BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002607CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002608 const AutoVarEmission &emission) {
2609 const VarDecl &var = *emission.Variable;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002610 assert(var.isEscapingByref() &&
2611 "only escaping __block variables need byref helpers");
2612
John McCallf9b056b2011-03-31 08:03:29 +00002613 QualType type = var.getType();
2614
John McCall7f416cc2015-09-08 08:05:57 +00002615 auto &byrefInfo = getBlockByrefInfo(&var);
2616
2617 // The alignment we care about for the purposes of uniquing byref
2618 // helpers is the alignment of the actual byref value field.
2619 CharUnits valueAlignment =
2620 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002621
John McCallf9b056b2011-03-31 08:03:29 +00002622 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002623 const Expr *copyExpr =
2624 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002625 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002626
David Blaikie92551612015-08-13 23:53:09 +00002627 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002628 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002629 }
2630
Akira Hatanaka7275da02018-02-28 07:15:55 +00002631 // If type is a non-trivial C struct type that is non-trivial to
2632 // destructly move or destroy, build the copy and dispose helpers.
2633 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2634 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2635 return ::buildByrefHelpers(
2636 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2637
John McCall31168b02011-06-15 23:02:42 +00002638 // Otherwise, if we don't have a retainable type, there's nothing to do.
2639 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002640 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002641
2642 Qualifiers qs = type.getQualifiers();
2643
2644 // If we have lifetime, that dominates.
2645 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002646 switch (lifetime) {
2647 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2648
2649 // These are just bits as far as the runtime is concerned.
2650 case Qualifiers::OCL_ExplicitNone:
2651 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002652 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002653
2654 // Tell the runtime that this is ARC __weak, called by the
2655 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002656 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002657 return ::buildByrefHelpers(CGM, byrefInfo,
2658 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002659
2660 // ARC __strong __block variables need to be retained.
2661 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002662 // Block pointers need to be copied, and there's no direct
2663 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002664 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002665 return ::buildByrefHelpers(CGM, byrefInfo,
2666 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002667
2668 // Otherwise, we transfer ownership of the retain from the stack
2669 // to the heap.
2670 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002671 return ::buildByrefHelpers(CGM, byrefInfo,
2672 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002673 }
2674 }
2675 llvm_unreachable("fell out of lifetime switch!");
2676 }
2677
John McCallf9b056b2011-03-31 08:03:29 +00002678 BlockFieldFlags flags;
2679 if (type->isBlockPointerType()) {
2680 flags |= BLOCK_FIELD_IS_BLOCK;
Fangrui Song6907ce22018-07-30 19:24:48 +00002681 } else if (CGM.getContext().isObjCNSObjectType(type) ||
John McCallf9b056b2011-03-31 08:03:29 +00002682 type->isObjCObjectPointerType()) {
2683 flags |= BLOCK_FIELD_IS_OBJECT;
2684 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002685 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002686 }
2687
2688 if (type.isObjCGCWeak())
2689 flags |= BLOCK_FIELD_IS_WEAK;
2690
John McCall7f416cc2015-09-08 08:05:57 +00002691 return ::buildByrefHelpers(CGM, byrefInfo,
2692 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002693}
2694
John McCall7f416cc2015-09-08 08:05:57 +00002695Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2696 const VarDecl *var,
2697 bool followForward) {
2698 auto &info = getBlockByrefInfo(var);
2699 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002700}
2701
John McCall7f416cc2015-09-08 08:05:57 +00002702Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2703 const BlockByrefInfo &info,
2704 bool followForward,
2705 const llvm::Twine &name) {
2706 // Chase the forwarding address if requested.
2707 if (followForward) {
James Y Knight751fe282019-02-09 22:22:28 +00002708 Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
John McCall7f416cc2015-09-08 08:05:57 +00002709 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2710 }
2711
James Y Knight751fe282019-02-09 22:22:28 +00002712 return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
John McCall73064872011-03-31 01:59:53 +00002713}
2714
John McCall7f416cc2015-09-08 08:05:57 +00002715/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002716/// into:
2717///
2718/// struct {
2719/// void *__isa;
2720/// void *__forwarding;
2721/// int32_t __flags;
2722/// int32_t __size;
2723/// void *__copy_helper; // only if needed
2724/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002725/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002726/// char padding[X]; // only if needed
2727/// T x;
2728/// } x
2729///
John McCall7f416cc2015-09-08 08:05:57 +00002730const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2731 auto it = BlockByrefInfos.find(D);
2732 if (it != BlockByrefInfos.end())
2733 return it->second;
John McCall73064872011-03-31 01:59:53 +00002734
John McCall7f416cc2015-09-08 08:05:57 +00002735 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002736 llvm::StructType::create(getLLVMContext(),
2737 "struct.__block_byref_" + D->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00002738
John McCall7f416cc2015-09-08 08:05:57 +00002739 QualType Ty = D->getType();
2740
2741 CharUnits size;
2742 SmallVector<llvm::Type *, 8> types;
Fangrui Song6907ce22018-07-30 19:24:48 +00002743
John McCall73064872011-03-31 01:59:53 +00002744 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002745 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002746 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002747
John McCall73064872011-03-31 01:59:53 +00002748 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002749 types.push_back(llvm::PointerType::getUnqual(byrefType));
2750 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002751
John McCall73064872011-03-31 01:59:53 +00002752 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002753 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002754 size += CharUnits::fromQuantity(4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002755
John McCall73064872011-03-31 01:59:53 +00002756 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002757 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002758 size += CharUnits::fromQuantity(4);
2759
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002760 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002761 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2762 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002763 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002764 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002765 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002766
John McCall73064872011-03-31 01:59:53 +00002767 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002768 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002769 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002770 }
John McCall7f416cc2015-09-08 08:05:57 +00002771
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002772 bool HasByrefExtendedLayout = false;
2773 Qualifiers::ObjCLifetime Lifetime;
2774 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002775 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002776 /// void *__byref_variable_layout;
2777 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002778 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002779 }
2780
2781 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002782 llvm::Type *varTy = ConvertTypeForMem(Ty);
2783
2784 bool packed = false;
2785 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002786 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002787
2788 // We may have to insert padding.
2789 if (varOffset != size) {
2790 llvm::Type *paddingTy =
2791 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2792
2793 types.push_back(paddingTy);
2794 size = varOffset;
2795
2796 // Conversely, we might have to prevent LLVM from inserting padding.
2797 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2798 > varAlign.getQuantity()) {
2799 packed = true;
2800 }
2801 types.push_back(varTy);
2802
2803 byrefType->setBody(types, packed);
2804
2805 BlockByrefInfo info;
2806 info.Type = byrefType;
2807 info.FieldIndex = types.size() - 1;
2808 info.FieldOffset = varOffset;
2809 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2810
2811 auto pair = BlockByrefInfos.insert({D, info});
2812 assert(pair.second && "info was inserted recursively?");
2813 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002814}
2815
2816/// Initialize the structural components of a __block variable, i.e.
2817/// everything but the actual object.
2818void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002819 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002820 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002821
John McCallf9b056b2011-03-31 08:03:29 +00002822 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002823 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002824 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2825
2826 unsigned nextHeaderIndex = 0;
2827 CharUnits nextHeaderOffset;
2828 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2829 const Twine &name) {
James Y Knight751fe282019-02-09 22:22:28 +00002830 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
John McCall7f416cc2015-09-08 08:05:57 +00002831 Builder.CreateStore(value, fieldAddr);
2832
2833 nextHeaderIndex++;
2834 nextHeaderOffset += fieldSize;
2835 };
John McCallf9b056b2011-03-31 08:03:29 +00002836
2837 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002838 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002839
2840 const VarDecl &D = *emission.Variable;
2841 QualType type = D.getType();
2842
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002843 bool HasByrefExtendedLayout;
2844 Qualifiers::ObjCLifetime ByrefLifetime;
2845 bool ByRefHasLifetime =
2846 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002847
John McCallf9b056b2011-03-31 08:03:29 +00002848 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002849
2850 // Initialize the 'isa', which is just 0 or 1.
2851 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002852 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002853 isa = 1;
2854 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002855 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002856
2857 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002858 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002859
2860 // Blocks ABI:
2861 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002862 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002863 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002864 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2865 if (ByRefHasLifetime) {
2866 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2867 else switch (ByrefLifetime) {
2868 case Qualifiers::OCL_Strong:
2869 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2870 break;
2871 case Qualifiers::OCL_Weak:
2872 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2873 break;
2874 case Qualifiers::OCL_ExplicitNone:
2875 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2876 break;
2877 case Qualifiers::OCL_None:
2878 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2879 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2880 break;
2881 default:
2882 break;
2883 }
2884 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2885 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2886 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2887 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2888 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2889 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2890 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2891 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2892 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2893 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2894 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2895 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2896 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2897 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2898 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2899 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2900 }
2901 printf("\n");
2902 }
2903 }
John McCall7f416cc2015-09-08 08:05:57 +00002904 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2905 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002906
John McCallf9b056b2011-03-31 08:03:29 +00002907 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2908 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002909 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002910
John McCallf9b056b2011-03-31 08:03:29 +00002911 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002912 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2913 "byref.copyHelper");
2914 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2915 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002916 }
John McCall7f416cc2015-09-08 08:05:57 +00002917
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002918 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002919 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2920 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002921 }
John McCall73064872011-03-31 01:59:53 +00002922}
2923
Akira Hatanaka9978da32018-08-10 15:09:24 +00002924void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2925 bool CanThrow) {
James Y Knight9871db02019-02-05 16:42:33 +00002926 llvm::FunctionCallee F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002927 llvm::Value *args[] = {
2928 Builder.CreateBitCast(V, Int8PtrTy),
2929 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2930 };
Akira Hatanaka9978da32018-08-10 15:09:24 +00002931
2932 if (CanThrow)
2933 EmitRuntimeCallOrInvoke(F, args);
2934 else
2935 EmitNounwindRuntimeCall(F, args);
Mike Stump626aecc2009-03-05 01:23:13 +00002936}
John McCall73064872011-03-31 01:59:53 +00002937
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002938void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2939 BlockFieldFlags Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002940 bool LoadBlockVarAddr, bool CanThrow) {
2941 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2942 CanThrow);
John McCall73064872011-03-31 01:59:53 +00002943}
John McCall7959fee2011-09-09 20:41:01 +00002944
2945/// Adjust the declaration of something from the blocks API.
2946static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2947 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002948 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002949
2950 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2951 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2952 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2953 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2954
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002955 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2956 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2957 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002958
2959 const NamedDecl *ND = nullptr;
2960 for (const auto &Result : DC->lookup(&II))
2961 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2962 (ND = dyn_cast<VarDecl>(Result)))
2963 break;
2964
2965 // TODO: support static blocks runtime
2966 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2967 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2968 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2969 } else {
2970 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2971 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2972 }
2973 }
2974
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002975 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2976 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002977 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002978
2979 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002980}
2981
James Y Knight9871db02019-02-05 16:42:33 +00002982llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
John McCall7959fee2011-09-09 20:41:01 +00002983 if (BlockObjectDispose)
2984 return BlockObjectDispose;
2985
2986 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2987 llvm::FunctionType *fty
2988 = llvm::FunctionType::get(VoidTy, args, false);
2989 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
James Y Knight9871db02019-02-05 16:42:33 +00002990 configureBlocksRuntimeObject(
2991 *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
John McCall7959fee2011-09-09 20:41:01 +00002992 return BlockObjectDispose;
2993}
2994
James Y Knight9871db02019-02-05 16:42:33 +00002995llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
John McCall7959fee2011-09-09 20:41:01 +00002996 if (BlockObjectAssign)
2997 return BlockObjectAssign;
2998
2999 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
3000 llvm::FunctionType *fty
3001 = llvm::FunctionType::get(VoidTy, args, false);
3002 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
James Y Knight9871db02019-02-05 16:42:33 +00003003 configureBlocksRuntimeObject(
3004 *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
John McCall7959fee2011-09-09 20:41:01 +00003005 return BlockObjectAssign;
3006}
3007
3008llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
3009 if (NSConcreteGlobalBlock)
3010 return NSConcreteGlobalBlock;
3011
3012 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00003013 Int8PtrTy->getPointerTo(),
3014 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00003015 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
3016 return NSConcreteGlobalBlock;
3017}
3018
3019llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
3020 if (NSConcreteStackBlock)
3021 return NSConcreteStackBlock;
3022
3023 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00003024 Int8PtrTy->getPointerTo(),
3025 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00003026 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00003027 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00003028}