/src/llvm-project/clang/lib/CodeGen/CGBlocks.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===// |
2 | | // |
3 | | // 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 |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This contains code to emit blocks. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "CGBlocks.h" |
14 | | #include "CGCXXABI.h" |
15 | | #include "CGDebugInfo.h" |
16 | | #include "CGObjCRuntime.h" |
17 | | #include "CGOpenCLRuntime.h" |
18 | | #include "CodeGenFunction.h" |
19 | | #include "CodeGenModule.h" |
20 | | #include "ConstantEmitter.h" |
21 | | #include "TargetInfo.h" |
22 | | #include "clang/AST/Attr.h" |
23 | | #include "clang/AST/DeclObjC.h" |
24 | | #include "clang/CodeGen/ConstantInitBuilder.h" |
25 | | #include "llvm/ADT/SmallSet.h" |
26 | | #include "llvm/IR/DataLayout.h" |
27 | | #include "llvm/IR/Module.h" |
28 | | #include "llvm/Support/ScopedPrinter.h" |
29 | | #include <algorithm> |
30 | | #include <cstdio> |
31 | | |
32 | | using namespace clang; |
33 | | using namespace CodeGen; |
34 | | |
35 | | CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name) |
36 | | : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false), |
37 | | NoEscape(false), HasCXXObject(false), UsesStret(false), |
38 | | HasCapturedVariableLayout(false), CapturesNonExternalType(false), |
39 | 0 | LocalAddress(Address::invalid()), StructureType(nullptr), Block(block) { |
40 | | |
41 | | // Skip asm prefix, if any. 'name' is usually taken directly from |
42 | | // the mangled name of the enclosing function. |
43 | 0 | if (!name.empty() && name[0] == '\01') |
44 | 0 | name = name.substr(1); |
45 | 0 | } |
46 | | |
47 | | // Anchor the vtable to this translation unit. |
48 | 0 | BlockByrefHelpers::~BlockByrefHelpers() {} |
49 | | |
50 | | /// Build the given block as a global block. |
51 | | static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM, |
52 | | const CGBlockInfo &blockInfo, |
53 | | llvm::Constant *blockFn); |
54 | | |
55 | | /// Build the helper function to copy a block. |
56 | | static llvm::Constant *buildCopyHelper(CodeGenModule &CGM, |
57 | 0 | const CGBlockInfo &blockInfo) { |
58 | 0 | return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo); |
59 | 0 | } |
60 | | |
61 | | /// Build the helper function to dispose of a block. |
62 | | static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM, |
63 | 0 | const CGBlockInfo &blockInfo) { |
64 | 0 | return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo); |
65 | 0 | } |
66 | | |
67 | | namespace { |
68 | | |
69 | | enum class CaptureStrKind { |
70 | | // String for the copy helper. |
71 | | CopyHelper, |
72 | | // String for the dispose helper. |
73 | | DisposeHelper, |
74 | | // Merge the strings for the copy helper and dispose helper. |
75 | | Merged |
76 | | }; |
77 | | |
78 | | } // end anonymous namespace |
79 | | |
80 | | static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap, |
81 | | CaptureStrKind StrKind, |
82 | | CharUnits BlockAlignment, |
83 | | CodeGenModule &CGM); |
84 | | |
85 | | static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo, |
86 | 0 | CodeGenModule &CGM) { |
87 | 0 | std::string Name = "__block_descriptor_"; |
88 | 0 | Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_"; |
89 | |
|
90 | 0 | if (BlockInfo.NeedsCopyDispose) { |
91 | 0 | if (CGM.getLangOpts().Exceptions) |
92 | 0 | Name += "e"; |
93 | 0 | if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) |
94 | 0 | Name += "a"; |
95 | 0 | Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_"; |
96 | |
|
97 | 0 | for (auto &Cap : BlockInfo.SortedCaptures) { |
98 | 0 | if (Cap.isConstantOrTrivial()) |
99 | 0 | continue; |
100 | | |
101 | 0 | Name += llvm::to_string(Cap.getOffset().getQuantity()); |
102 | |
|
103 | 0 | if (Cap.CopyKind == Cap.DisposeKind) { |
104 | | // If CopyKind and DisposeKind are the same, merge the capture |
105 | | // information. |
106 | 0 | assert(Cap.CopyKind != BlockCaptureEntityKind::None && |
107 | 0 | "shouldn't see BlockCaptureManagedEntity that is None"); |
108 | 0 | Name += getBlockCaptureStr(Cap, CaptureStrKind::Merged, |
109 | 0 | BlockInfo.BlockAlign, CGM); |
110 | 0 | } else { |
111 | | // If CopyKind and DisposeKind are not the same, which can happen when |
112 | | // either Kind is None or the captured object is a __strong block, |
113 | | // concatenate the copy and dispose strings. |
114 | 0 | Name += getBlockCaptureStr(Cap, CaptureStrKind::CopyHelper, |
115 | 0 | BlockInfo.BlockAlign, CGM); |
116 | 0 | Name += getBlockCaptureStr(Cap, CaptureStrKind::DisposeHelper, |
117 | 0 | BlockInfo.BlockAlign, CGM); |
118 | 0 | } |
119 | 0 | } |
120 | 0 | Name += "_"; |
121 | 0 | } |
122 | |
|
123 | 0 | std::string TypeAtEncoding = |
124 | 0 | CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr()); |
125 | | /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as |
126 | | /// a separator between symbol name and symbol version. |
127 | 0 | std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1'); |
128 | 0 | Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding; |
129 | 0 | Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo); |
130 | 0 | return Name; |
131 | 0 | } |
132 | | |
133 | | /// buildBlockDescriptor - Build the block descriptor meta-data for a block. |
134 | | /// buildBlockDescriptor is accessed from 5th field of the Block_literal |
135 | | /// meta-data and contains stationary information about the block literal. |
136 | | /// Its definition will have 4 (or optionally 6) words. |
137 | | /// \code |
138 | | /// struct Block_descriptor { |
139 | | /// unsigned long reserved; |
140 | | /// unsigned long size; // size of Block_literal metadata in bytes. |
141 | | /// void *copy_func_helper_decl; // optional copy helper. |
142 | | /// void *destroy_func_decl; // optional destructor helper. |
143 | | /// void *block_method_encoding_address; // @encode for block literal signature. |
144 | | /// void *block_layout_info; // encoding of captured block variables. |
145 | | /// }; |
146 | | /// \endcode |
147 | | static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, |
148 | 0 | const CGBlockInfo &blockInfo) { |
149 | 0 | ASTContext &C = CGM.getContext(); |
150 | |
|
151 | 0 | llvm::IntegerType *ulong = |
152 | 0 | cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy)); |
153 | 0 | llvm::PointerType *i8p = nullptr; |
154 | 0 | if (CGM.getLangOpts().OpenCL) |
155 | 0 | i8p = llvm::PointerType::get( |
156 | 0 | CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant)); |
157 | 0 | else |
158 | 0 | i8p = CGM.VoidPtrTy; |
159 | |
|
160 | 0 | std::string descName; |
161 | | |
162 | | // If an equivalent block descriptor global variable exists, return it. |
163 | 0 | if (C.getLangOpts().ObjC && |
164 | 0 | CGM.getLangOpts().getGC() == LangOptions::NonGC) { |
165 | 0 | descName = getBlockDescriptorName(blockInfo, CGM); |
166 | 0 | if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName)) |
167 | 0 | return desc; |
168 | 0 | } |
169 | | |
170 | | // If there isn't an equivalent block descriptor global variable, create a new |
171 | | // one. |
172 | 0 | ConstantInitBuilder builder(CGM); |
173 | 0 | auto elements = builder.beginStruct(); |
174 | | |
175 | | // reserved |
176 | 0 | elements.addInt(ulong, 0); |
177 | | |
178 | | // Size |
179 | | // FIXME: What is the right way to say this doesn't fit? We should give |
180 | | // a user diagnostic in that case. Better fix would be to change the |
181 | | // API to size_t. |
182 | 0 | elements.addInt(ulong, blockInfo.BlockSize.getQuantity()); |
183 | | |
184 | | // Optional copy/dispose helpers. |
185 | 0 | bool hasInternalHelper = false; |
186 | 0 | if (blockInfo.NeedsCopyDispose) { |
187 | | // copy_func_helper_decl |
188 | 0 | llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo); |
189 | 0 | elements.add(copyHelper); |
190 | | |
191 | | // destroy_func_decl |
192 | 0 | llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo); |
193 | 0 | elements.add(disposeHelper); |
194 | |
|
195 | 0 | if (cast<llvm::Function>(copyHelper->stripPointerCasts()) |
196 | 0 | ->hasInternalLinkage() || |
197 | 0 | cast<llvm::Function>(disposeHelper->stripPointerCasts()) |
198 | 0 | ->hasInternalLinkage()) |
199 | 0 | hasInternalHelper = true; |
200 | 0 | } |
201 | | |
202 | | // Signature. Mandatory ObjC-style method descriptor @encode sequence. |
203 | 0 | std::string typeAtEncoding = |
204 | 0 | CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr()); |
205 | 0 | elements.add(CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer()); |
206 | | |
207 | | // GC layout. |
208 | 0 | if (C.getLangOpts().ObjC) { |
209 | 0 | if (CGM.getLangOpts().getGC() != LangOptions::NonGC) |
210 | 0 | elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo)); |
211 | 0 | else |
212 | 0 | elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo)); |
213 | 0 | } |
214 | 0 | else |
215 | 0 | elements.addNullPointer(i8p); |
216 | |
|
217 | 0 | unsigned AddrSpace = 0; |
218 | 0 | if (C.getLangOpts().OpenCL) |
219 | 0 | AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant); |
220 | |
|
221 | 0 | llvm::GlobalValue::LinkageTypes linkage; |
222 | 0 | if (descName.empty()) { |
223 | 0 | linkage = llvm::GlobalValue::InternalLinkage; |
224 | 0 | descName = "__block_descriptor_tmp"; |
225 | 0 | } else if (hasInternalHelper) { |
226 | | // If either the copy helper or the dispose helper has internal linkage, |
227 | | // the block descriptor must have internal linkage too. |
228 | 0 | linkage = llvm::GlobalValue::InternalLinkage; |
229 | 0 | } else { |
230 | 0 | linkage = llvm::GlobalValue::LinkOnceODRLinkage; |
231 | 0 | } |
232 | |
|
233 | 0 | llvm::GlobalVariable *global = |
234 | 0 | elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(), |
235 | 0 | /*constant*/ true, linkage, AddrSpace); |
236 | |
|
237 | 0 | if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) { |
238 | 0 | if (CGM.supportsCOMDAT()) |
239 | 0 | global->setComdat(CGM.getModule().getOrInsertComdat(descName)); |
240 | 0 | global->setVisibility(llvm::GlobalValue::HiddenVisibility); |
241 | 0 | global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
242 | 0 | } |
243 | |
|
244 | 0 | return global; |
245 | 0 | } |
246 | | |
247 | | /* |
248 | | Purely notional variadic template describing the layout of a block. |
249 | | |
250 | | template <class _ResultType, class... _ParamTypes, class... _CaptureTypes> |
251 | | struct Block_literal { |
252 | | /// Initialized to one of: |
253 | | /// extern void *_NSConcreteStackBlock[]; |
254 | | /// extern void *_NSConcreteGlobalBlock[]; |
255 | | /// |
256 | | /// In theory, we could start one off malloc'ed by setting |
257 | | /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using |
258 | | /// this isa: |
259 | | /// extern void *_NSConcreteMallocBlock[]; |
260 | | struct objc_class *isa; |
261 | | |
262 | | /// These are the flags (with corresponding bit number) that the |
263 | | /// compiler is actually supposed to know about. |
264 | | /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping |
265 | | /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block |
266 | | /// descriptor provides copy and dispose helper functions |
267 | | /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured |
268 | | /// object with a nontrivial destructor or copy constructor |
269 | | /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated |
270 | | /// as global memory |
271 | | /// 29. BLOCK_USE_STRET - indicates that the block function |
272 | | /// uses stret, which objc_msgSend needs to know about |
273 | | /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an |
274 | | /// @encoded signature string |
275 | | /// And we're not supposed to manipulate these: |
276 | | /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved |
277 | | /// to malloc'ed memory |
278 | | /// 27. BLOCK_IS_GC - indicates that the block has been moved to |
279 | | /// to GC-allocated memory |
280 | | /// Additionally, the bottom 16 bits are a reference count which |
281 | | /// should be zero on the stack. |
282 | | int flags; |
283 | | |
284 | | /// Reserved; should be zero-initialized. |
285 | | int reserved; |
286 | | |
287 | | /// Function pointer generated from block literal. |
288 | | _ResultType (*invoke)(Block_literal *, _ParamTypes...); |
289 | | |
290 | | /// Block description metadata generated from block literal. |
291 | | struct Block_descriptor *block_descriptor; |
292 | | |
293 | | /// Captured values follow. |
294 | | _CapturesTypes captures...; |
295 | | }; |
296 | | */ |
297 | | |
298 | | namespace { |
299 | | /// A chunk of data that we actually have to capture in the block. |
300 | | struct BlockLayoutChunk { |
301 | | CharUnits Alignment; |
302 | | CharUnits Size; |
303 | | const BlockDecl::Capture *Capture; // null for 'this' |
304 | | llvm::Type *Type; |
305 | | QualType FieldType; |
306 | | BlockCaptureEntityKind CopyKind, DisposeKind; |
307 | | BlockFieldFlags CopyFlags, DisposeFlags; |
308 | | |
309 | | BlockLayoutChunk(CharUnits align, CharUnits size, |
310 | | const BlockDecl::Capture *capture, llvm::Type *type, |
311 | | QualType fieldType, BlockCaptureEntityKind CopyKind, |
312 | | BlockFieldFlags CopyFlags, |
313 | | BlockCaptureEntityKind DisposeKind, |
314 | | BlockFieldFlags DisposeFlags) |
315 | | : Alignment(align), Size(size), Capture(capture), Type(type), |
316 | | FieldType(fieldType), CopyKind(CopyKind), DisposeKind(DisposeKind), |
317 | 0 | CopyFlags(CopyFlags), DisposeFlags(DisposeFlags) {} |
318 | | |
319 | | /// Tell the block info that this chunk has the given field index. |
320 | 0 | void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) { |
321 | 0 | if (!Capture) { |
322 | 0 | info.CXXThisIndex = index; |
323 | 0 | info.CXXThisOffset = offset; |
324 | 0 | } else { |
325 | 0 | info.SortedCaptures.push_back(CGBlockInfo::Capture::makeIndex( |
326 | 0 | index, offset, FieldType, CopyKind, CopyFlags, DisposeKind, |
327 | 0 | DisposeFlags, Capture)); |
328 | 0 | } |
329 | 0 | } |
330 | | |
331 | 0 | bool isTrivial() const { |
332 | 0 | return CopyKind == BlockCaptureEntityKind::None && |
333 | 0 | DisposeKind == BlockCaptureEntityKind::None; |
334 | 0 | } |
335 | | }; |
336 | | |
337 | | /// Order by 1) all __strong together 2) next, all block together 3) next, |
338 | | /// all byref together 4) next, all __weak together. Preserve descending |
339 | | /// alignment in all situations. |
340 | 0 | bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) { |
341 | 0 | if (left.Alignment != right.Alignment) |
342 | 0 | return left.Alignment > right.Alignment; |
343 | | |
344 | 0 | auto getPrefOrder = [](const BlockLayoutChunk &chunk) { |
345 | 0 | switch (chunk.CopyKind) { |
346 | 0 | case BlockCaptureEntityKind::ARCStrong: |
347 | 0 | return 0; |
348 | 0 | case BlockCaptureEntityKind::BlockObject: |
349 | 0 | switch (chunk.CopyFlags.getBitMask()) { |
350 | 0 | case BLOCK_FIELD_IS_OBJECT: |
351 | 0 | return 0; |
352 | 0 | case BLOCK_FIELD_IS_BLOCK: |
353 | 0 | return 1; |
354 | 0 | case BLOCK_FIELD_IS_BYREF: |
355 | 0 | return 2; |
356 | 0 | default: |
357 | 0 | break; |
358 | 0 | } |
359 | 0 | break; |
360 | 0 | case BlockCaptureEntityKind::ARCWeak: |
361 | 0 | return 3; |
362 | 0 | default: |
363 | 0 | break; |
364 | 0 | } |
365 | 0 | return 4; |
366 | 0 | }; |
367 | |
|
368 | 0 | return getPrefOrder(left) < getPrefOrder(right); |
369 | 0 | } |
370 | | } // end anonymous namespace |
371 | | |
372 | | static std::pair<BlockCaptureEntityKind, BlockFieldFlags> |
373 | | computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T, |
374 | | const LangOptions &LangOpts); |
375 | | |
376 | | static std::pair<BlockCaptureEntityKind, BlockFieldFlags> |
377 | | computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T, |
378 | | const LangOptions &LangOpts); |
379 | | |
380 | | static void addBlockLayout(CharUnits align, CharUnits size, |
381 | | const BlockDecl::Capture *capture, llvm::Type *type, |
382 | | QualType fieldType, |
383 | | SmallVectorImpl<BlockLayoutChunk> &Layout, |
384 | 0 | CGBlockInfo &Info, CodeGenModule &CGM) { |
385 | 0 | if (!capture) { |
386 | | // 'this' capture. |
387 | 0 | Layout.push_back(BlockLayoutChunk( |
388 | 0 | align, size, capture, type, fieldType, BlockCaptureEntityKind::None, |
389 | 0 | BlockFieldFlags(), BlockCaptureEntityKind::None, BlockFieldFlags())); |
390 | 0 | return; |
391 | 0 | } |
392 | | |
393 | 0 | const LangOptions &LangOpts = CGM.getLangOpts(); |
394 | 0 | BlockCaptureEntityKind CopyKind, DisposeKind; |
395 | 0 | BlockFieldFlags CopyFlags, DisposeFlags; |
396 | |
|
397 | 0 | std::tie(CopyKind, CopyFlags) = |
398 | 0 | computeCopyInfoForBlockCapture(*capture, fieldType, LangOpts); |
399 | 0 | std::tie(DisposeKind, DisposeFlags) = |
400 | 0 | computeDestroyInfoForBlockCapture(*capture, fieldType, LangOpts); |
401 | 0 | Layout.push_back(BlockLayoutChunk(align, size, capture, type, fieldType, |
402 | 0 | CopyKind, CopyFlags, DisposeKind, |
403 | 0 | DisposeFlags)); |
404 | |
|
405 | 0 | if (Info.NoEscape) |
406 | 0 | return; |
407 | | |
408 | 0 | if (!Layout.back().isTrivial()) |
409 | 0 | Info.NeedsCopyDispose = true; |
410 | 0 | } |
411 | | |
412 | | /// Determines if the given type is safe for constant capture in C++. |
413 | 0 | static bool isSafeForCXXConstantCapture(QualType type) { |
414 | 0 | const RecordType *recordType = |
415 | 0 | type->getBaseElementTypeUnsafe()->getAs<RecordType>(); |
416 | | |
417 | | // Only records can be unsafe. |
418 | 0 | if (!recordType) return true; |
419 | | |
420 | 0 | const auto *record = cast<CXXRecordDecl>(recordType->getDecl()); |
421 | | |
422 | | // Maintain semantics for classes with non-trivial dtors or copy ctors. |
423 | 0 | if (!record->hasTrivialDestructor()) return false; |
424 | 0 | if (record->hasNonTrivialCopyConstructor()) return false; |
425 | | |
426 | | // Otherwise, we just have to make sure there aren't any mutable |
427 | | // fields that might have changed since initialization. |
428 | 0 | return !record->hasMutableFields(); |
429 | 0 | } |
430 | | |
431 | | /// It is illegal to modify a const object after initialization. |
432 | | /// Therefore, if a const object has a constant initializer, we don't |
433 | | /// actually need to keep storage for it in the block; we'll just |
434 | | /// rematerialize it at the start of the block function. This is |
435 | | /// acceptable because we make no promises about address stability of |
436 | | /// captured variables. |
437 | | static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM, |
438 | | CodeGenFunction *CGF, |
439 | 0 | const VarDecl *var) { |
440 | | // Return if this is a function parameter. We shouldn't try to |
441 | | // rematerialize default arguments of function parameters. |
442 | 0 | if (isa<ParmVarDecl>(var)) |
443 | 0 | return nullptr; |
444 | | |
445 | 0 | QualType type = var->getType(); |
446 | | |
447 | | // We can only do this if the variable is const. |
448 | 0 | if (!type.isConstQualified()) return nullptr; |
449 | | |
450 | | // Furthermore, in C++ we have to worry about mutable fields: |
451 | | // C++ [dcl.type.cv]p4: |
452 | | // Except that any class member declared mutable can be |
453 | | // modified, any attempt to modify a const object during its |
454 | | // lifetime results in undefined behavior. |
455 | 0 | if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type)) |
456 | 0 | return nullptr; |
457 | | |
458 | | // If the variable doesn't have any initializer (shouldn't this be |
459 | | // invalid?), it's not clear what we should do. Maybe capture as |
460 | | // zero? |
461 | 0 | const Expr *init = var->getInit(); |
462 | 0 | if (!init) return nullptr; |
463 | | |
464 | 0 | return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var); |
465 | 0 | } |
466 | | |
467 | | /// Get the low bit of a nonzero character count. This is the |
468 | | /// alignment of the nth byte if the 0th byte is universally aligned. |
469 | 0 | static CharUnits getLowBit(CharUnits v) { |
470 | 0 | return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1)); |
471 | 0 | } |
472 | | |
473 | | static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info, |
474 | 0 | SmallVectorImpl<llvm::Type*> &elementTypes) { |
475 | |
|
476 | 0 | assert(elementTypes.empty()); |
477 | 0 | if (CGM.getLangOpts().OpenCL) { |
478 | | // The header is basically 'struct { int; int; generic void *; |
479 | | // custom_fields; }'. Assert that struct is packed. |
480 | 0 | auto GenPtrAlign = CharUnits::fromQuantity( |
481 | 0 | CGM.getTarget().getPointerAlign(LangAS::opencl_generic) / 8); |
482 | 0 | auto GenPtrSize = CharUnits::fromQuantity( |
483 | 0 | CGM.getTarget().getPointerWidth(LangAS::opencl_generic) / 8); |
484 | 0 | assert(CGM.getIntSize() <= GenPtrSize); |
485 | 0 | assert(CGM.getIntAlign() <= GenPtrAlign); |
486 | 0 | assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign)); |
487 | 0 | elementTypes.push_back(CGM.IntTy); /* total size */ |
488 | 0 | elementTypes.push_back(CGM.IntTy); /* align */ |
489 | 0 | elementTypes.push_back( |
490 | 0 | CGM.getOpenCLRuntime() |
491 | 0 | .getGenericVoidPointerType()); /* invoke function */ |
492 | 0 | unsigned Offset = |
493 | 0 | 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity(); |
494 | 0 | unsigned BlockAlign = GenPtrAlign.getQuantity(); |
495 | 0 | if (auto *Helper = |
496 | 0 | CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) { |
497 | 0 | for (auto *I : Helper->getCustomFieldTypes()) /* custom fields */ { |
498 | | // TargetOpenCLBlockHelp needs to make sure the struct is packed. |
499 | | // If necessary, add padding fields to the custom fields. |
500 | 0 | unsigned Align = CGM.getDataLayout().getABITypeAlign(I).value(); |
501 | 0 | if (BlockAlign < Align) |
502 | 0 | BlockAlign = Align; |
503 | 0 | assert(Offset % Align == 0); |
504 | 0 | Offset += CGM.getDataLayout().getTypeAllocSize(I); |
505 | 0 | elementTypes.push_back(I); |
506 | 0 | } |
507 | 0 | } |
508 | 0 | info.BlockAlign = CharUnits::fromQuantity(BlockAlign); |
509 | 0 | info.BlockSize = CharUnits::fromQuantity(Offset); |
510 | 0 | } else { |
511 | | // The header is basically 'struct { void *; int; int; void *; void *; }'. |
512 | | // Assert that the struct is packed. |
513 | 0 | assert(CGM.getIntSize() <= CGM.getPointerSize()); |
514 | 0 | assert(CGM.getIntAlign() <= CGM.getPointerAlign()); |
515 | 0 | assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign())); |
516 | 0 | info.BlockAlign = CGM.getPointerAlign(); |
517 | 0 | info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize(); |
518 | 0 | elementTypes.push_back(CGM.VoidPtrTy); |
519 | 0 | elementTypes.push_back(CGM.IntTy); |
520 | 0 | elementTypes.push_back(CGM.IntTy); |
521 | 0 | elementTypes.push_back(CGM.VoidPtrTy); |
522 | 0 | elementTypes.push_back(CGM.getBlockDescriptorType()); |
523 | 0 | } |
524 | 0 | } |
525 | | |
526 | | static QualType getCaptureFieldType(const CodeGenFunction &CGF, |
527 | 0 | const BlockDecl::Capture &CI) { |
528 | 0 | const VarDecl *VD = CI.getVariable(); |
529 | | |
530 | | // If the variable is captured by an enclosing block or lambda expression, |
531 | | // use the type of the capture field. |
532 | 0 | if (CGF.BlockInfo && CI.isNested()) |
533 | 0 | return CGF.BlockInfo->getCapture(VD).fieldType(); |
534 | 0 | if (auto *FD = CGF.LambdaCaptureFields.lookup(VD)) |
535 | 0 | return FD->getType(); |
536 | | // If the captured variable is a non-escaping __block variable, the field |
537 | | // type is the reference type. If the variable is a __block variable that |
538 | | // already has a reference type, the field type is the variable's type. |
539 | 0 | return VD->isNonEscapingByref() ? |
540 | 0 | CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType(); |
541 | 0 | } |
542 | | |
543 | | /// Compute the layout of the given block. Attempts to lay the block |
544 | | /// out with minimal space requirements. |
545 | | static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, |
546 | 0 | CGBlockInfo &info) { |
547 | 0 | ASTContext &C = CGM.getContext(); |
548 | 0 | const BlockDecl *block = info.getBlockDecl(); |
549 | |
|
550 | 0 | SmallVector<llvm::Type*, 8> elementTypes; |
551 | 0 | initializeForBlockHeader(CGM, info, elementTypes); |
552 | 0 | bool hasNonConstantCustomFields = false; |
553 | 0 | if (auto *OpenCLHelper = |
554 | 0 | CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) |
555 | 0 | hasNonConstantCustomFields = |
556 | 0 | !OpenCLHelper->areAllCustomFieldValuesConstant(info); |
557 | 0 | if (!block->hasCaptures() && !hasNonConstantCustomFields) { |
558 | 0 | info.StructureType = |
559 | 0 | llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); |
560 | 0 | info.CanBeGlobal = true; |
561 | 0 | return; |
562 | 0 | } |
563 | 0 | else if (C.getLangOpts().ObjC && |
564 | 0 | CGM.getLangOpts().getGC() == LangOptions::NonGC) |
565 | 0 | info.HasCapturedVariableLayout = true; |
566 | | |
567 | 0 | if (block->doesNotEscape()) |
568 | 0 | info.NoEscape = true; |
569 | | |
570 | | // Collect the layout chunks. |
571 | 0 | SmallVector<BlockLayoutChunk, 16> layout; |
572 | 0 | layout.reserve(block->capturesCXXThis() + |
573 | 0 | (block->capture_end() - block->capture_begin())); |
574 | |
|
575 | 0 | CharUnits maxFieldAlign; |
576 | | |
577 | | // First, 'this'. |
578 | 0 | if (block->capturesCXXThis()) { |
579 | 0 | assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) && |
580 | 0 | "Can't capture 'this' outside a method"); |
581 | 0 | QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(); |
582 | | |
583 | | // Theoretically, this could be in a different address space, so |
584 | | // don't assume standard pointer size/align. |
585 | 0 | llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType); |
586 | 0 | auto TInfo = CGM.getContext().getTypeInfoInChars(thisType); |
587 | 0 | maxFieldAlign = std::max(maxFieldAlign, TInfo.Align); |
588 | |
|
589 | 0 | addBlockLayout(TInfo.Align, TInfo.Width, nullptr, llvmType, thisType, |
590 | 0 | layout, info, CGM); |
591 | 0 | } |
592 | | |
593 | | // Next, all the block captures. |
594 | 0 | for (const auto &CI : block->captures()) { |
595 | 0 | const VarDecl *variable = CI.getVariable(); |
596 | |
|
597 | 0 | if (CI.isEscapingByref()) { |
598 | | // Just use void* instead of a pointer to the byref type. |
599 | 0 | CharUnits align = CGM.getPointerAlign(); |
600 | 0 | maxFieldAlign = std::max(maxFieldAlign, align); |
601 | | |
602 | | // Since a __block variable cannot be captured by lambdas, its type and |
603 | | // the capture field type should always match. |
604 | 0 | assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() && |
605 | 0 | "capture type differs from the variable type"); |
606 | 0 | addBlockLayout(align, CGM.getPointerSize(), &CI, CGM.VoidPtrTy, |
607 | 0 | variable->getType(), layout, info, CGM); |
608 | 0 | continue; |
609 | 0 | } |
610 | | |
611 | | // Otherwise, build a layout chunk with the size and alignment of |
612 | | // the declaration. |
613 | 0 | if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) { |
614 | 0 | info.SortedCaptures.push_back( |
615 | 0 | CGBlockInfo::Capture::makeConstant(constant, &CI)); |
616 | 0 | continue; |
617 | 0 | } |
618 | | |
619 | 0 | QualType VT = getCaptureFieldType(*CGF, CI); |
620 | |
|
621 | 0 | if (CGM.getLangOpts().CPlusPlus) |
622 | 0 | if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) |
623 | 0 | if (CI.hasCopyExpr() || !record->hasTrivialDestructor()) { |
624 | 0 | info.HasCXXObject = true; |
625 | 0 | if (!record->isExternallyVisible()) |
626 | 0 | info.CapturesNonExternalType = true; |
627 | 0 | } |
628 | |
|
629 | 0 | CharUnits size = C.getTypeSizeInChars(VT); |
630 | 0 | CharUnits align = C.getDeclAlign(variable); |
631 | |
|
632 | 0 | maxFieldAlign = std::max(maxFieldAlign, align); |
633 | |
|
634 | 0 | llvm::Type *llvmType = |
635 | 0 | CGM.getTypes().ConvertTypeForMem(VT); |
636 | |
|
637 | 0 | addBlockLayout(align, size, &CI, llvmType, VT, layout, info, CGM); |
638 | 0 | } |
639 | | |
640 | | // If that was everything, we're done here. |
641 | 0 | if (layout.empty()) { |
642 | 0 | info.StructureType = |
643 | 0 | llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); |
644 | 0 | info.CanBeGlobal = true; |
645 | 0 | info.buildCaptureMap(); |
646 | 0 | return; |
647 | 0 | } |
648 | | |
649 | | // Sort the layout by alignment. We have to use a stable sort here |
650 | | // to get reproducible results. There should probably be an |
651 | | // llvm::array_pod_stable_sort. |
652 | 0 | llvm::stable_sort(layout); |
653 | | |
654 | | // Needed for blocks layout info. |
655 | 0 | info.BlockHeaderForcedGapOffset = info.BlockSize; |
656 | 0 | info.BlockHeaderForcedGapSize = CharUnits::Zero(); |
657 | |
|
658 | 0 | CharUnits &blockSize = info.BlockSize; |
659 | 0 | info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign); |
660 | | |
661 | | // Assuming that the first byte in the header is maximally aligned, |
662 | | // get the alignment of the first byte following the header. |
663 | 0 | CharUnits endAlign = getLowBit(blockSize); |
664 | | |
665 | | // If the end of the header isn't satisfactorily aligned for the |
666 | | // maximum thing, look for things that are okay with the header-end |
667 | | // alignment, and keep appending them until we get something that's |
668 | | // aligned right. This algorithm is only guaranteed optimal if |
669 | | // that condition is satisfied at some point; otherwise we can get |
670 | | // things like: |
671 | | // header // next byte has alignment 4 |
672 | | // something_with_size_5; // next byte has alignment 1 |
673 | | // something_with_alignment_8; |
674 | | // which has 7 bytes of padding, as opposed to the naive solution |
675 | | // which might have less (?). |
676 | 0 | if (endAlign < maxFieldAlign) { |
677 | 0 | SmallVectorImpl<BlockLayoutChunk>::iterator |
678 | 0 | li = layout.begin() + 1, le = layout.end(); |
679 | | |
680 | | // Look for something that the header end is already |
681 | | // satisfactorily aligned for. |
682 | 0 | for (; li != le && endAlign < li->Alignment; ++li) |
683 | 0 | ; |
684 | | |
685 | | // If we found something that's naturally aligned for the end of |
686 | | // the header, keep adding things... |
687 | 0 | if (li != le) { |
688 | 0 | SmallVectorImpl<BlockLayoutChunk>::iterator first = li; |
689 | 0 | for (; li != le; ++li) { |
690 | 0 | assert(endAlign >= li->Alignment); |
691 | | |
692 | 0 | li->setIndex(info, elementTypes.size(), blockSize); |
693 | 0 | elementTypes.push_back(li->Type); |
694 | 0 | blockSize += li->Size; |
695 | 0 | endAlign = getLowBit(blockSize); |
696 | | |
697 | | // ...until we get to the alignment of the maximum field. |
698 | 0 | if (endAlign >= maxFieldAlign) { |
699 | 0 | ++li; |
700 | 0 | break; |
701 | 0 | } |
702 | 0 | } |
703 | | // Don't re-append everything we just appended. |
704 | 0 | layout.erase(first, li); |
705 | 0 | } |
706 | 0 | } |
707 | |
|
708 | 0 | assert(endAlign == getLowBit(blockSize)); |
709 | | |
710 | | // At this point, we just have to add padding if the end align still |
711 | | // isn't aligned right. |
712 | 0 | if (endAlign < maxFieldAlign) { |
713 | 0 | CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign); |
714 | 0 | CharUnits padding = newBlockSize - blockSize; |
715 | | |
716 | | // If we haven't yet added any fields, remember that there was an |
717 | | // initial gap; this need to go into the block layout bit map. |
718 | 0 | if (blockSize == info.BlockHeaderForcedGapOffset) { |
719 | 0 | info.BlockHeaderForcedGapSize = padding; |
720 | 0 | } |
721 | |
|
722 | 0 | elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty, |
723 | 0 | padding.getQuantity())); |
724 | 0 | blockSize = newBlockSize; |
725 | 0 | endAlign = getLowBit(blockSize); // might be > maxFieldAlign |
726 | 0 | } |
727 | |
|
728 | 0 | assert(endAlign >= maxFieldAlign); |
729 | 0 | assert(endAlign == getLowBit(blockSize)); |
730 | | // Slam everything else on now. This works because they have |
731 | | // strictly decreasing alignment and we expect that size is always a |
732 | | // multiple of alignment. |
733 | 0 | for (SmallVectorImpl<BlockLayoutChunk>::iterator |
734 | 0 | li = layout.begin(), le = layout.end(); li != le; ++li) { |
735 | 0 | if (endAlign < li->Alignment) { |
736 | | // size may not be multiple of alignment. This can only happen with |
737 | | // an over-aligned variable. We will be adding a padding field to |
738 | | // make the size be multiple of alignment. |
739 | 0 | CharUnits padding = li->Alignment - endAlign; |
740 | 0 | elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty, |
741 | 0 | padding.getQuantity())); |
742 | 0 | blockSize += padding; |
743 | 0 | endAlign = getLowBit(blockSize); |
744 | 0 | } |
745 | 0 | assert(endAlign >= li->Alignment); |
746 | 0 | li->setIndex(info, elementTypes.size(), blockSize); |
747 | 0 | elementTypes.push_back(li->Type); |
748 | 0 | blockSize += li->Size; |
749 | 0 | endAlign = getLowBit(blockSize); |
750 | 0 | } |
751 | |
|
752 | 0 | info.buildCaptureMap(); |
753 | 0 | info.StructureType = |
754 | 0 | llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); |
755 | 0 | } |
756 | | |
757 | | /// Emit a block literal expression in the current function. |
758 | 0 | llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) { |
759 | | // If the block has no captures, we won't have a pre-computed |
760 | | // layout for it. |
761 | 0 | if (!blockExpr->getBlockDecl()->hasCaptures()) |
762 | | // The block literal is emitted as a global variable, and the block invoke |
763 | | // function has to be extracted from its initializer. |
764 | 0 | if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) |
765 | 0 | return Block; |
766 | | |
767 | 0 | CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName()); |
768 | 0 | computeBlockInfo(CGM, this, blockInfo); |
769 | 0 | blockInfo.BlockExpression = blockExpr; |
770 | 0 | if (!blockInfo.CanBeGlobal) |
771 | 0 | blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType, |
772 | 0 | blockInfo.BlockAlign, "block"); |
773 | 0 | return EmitBlockLiteral(blockInfo); |
774 | 0 | } |
775 | | |
776 | 0 | llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) { |
777 | 0 | bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL; |
778 | 0 | auto GenVoidPtrTy = |
779 | 0 | IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy; |
780 | 0 | LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default; |
781 | 0 | auto GenVoidPtrSize = CharUnits::fromQuantity( |
782 | 0 | CGM.getTarget().getPointerWidth(GenVoidPtrAddr) / 8); |
783 | | // Using the computed layout, generate the actual block function. |
784 | 0 | bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda(); |
785 | 0 | CodeGenFunction BlockCGF{CGM, true}; |
786 | 0 | BlockCGF.SanOpts = SanOpts; |
787 | 0 | auto *InvokeFn = BlockCGF.GenerateBlockFunction( |
788 | 0 | CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal); |
789 | 0 | auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy); |
790 | | |
791 | | // If there is nothing to capture, we can emit this as a global block. |
792 | 0 | if (blockInfo.CanBeGlobal) |
793 | 0 | return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression); |
794 | | |
795 | | // Otherwise, we have to emit this as a local block. |
796 | | |
797 | 0 | Address blockAddr = blockInfo.LocalAddress; |
798 | 0 | assert(blockAddr.isValid() && "block has no address!"); |
799 | | |
800 | 0 | llvm::Constant *isa; |
801 | 0 | llvm::Constant *descriptor; |
802 | 0 | BlockFlags flags; |
803 | 0 | if (!IsOpenCL) { |
804 | | // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock |
805 | | // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping |
806 | | // block just returns the original block and releasing it is a no-op. |
807 | 0 | llvm::Constant *blockISA = blockInfo.NoEscape |
808 | 0 | ? CGM.getNSConcreteGlobalBlock() |
809 | 0 | : CGM.getNSConcreteStackBlock(); |
810 | 0 | isa = blockISA; |
811 | | |
812 | | // Build the block descriptor. |
813 | 0 | descriptor = buildBlockDescriptor(CGM, blockInfo); |
814 | | |
815 | | // Compute the initial on-stack block flags. |
816 | 0 | flags = BLOCK_HAS_SIGNATURE; |
817 | 0 | if (blockInfo.HasCapturedVariableLayout) |
818 | 0 | flags |= BLOCK_HAS_EXTENDED_LAYOUT; |
819 | 0 | if (blockInfo.NeedsCopyDispose) |
820 | 0 | flags |= BLOCK_HAS_COPY_DISPOSE; |
821 | 0 | if (blockInfo.HasCXXObject) |
822 | 0 | flags |= BLOCK_HAS_CXX_OBJ; |
823 | 0 | if (blockInfo.UsesStret) |
824 | 0 | flags |= BLOCK_USE_STRET; |
825 | 0 | if (blockInfo.NoEscape) |
826 | 0 | flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL; |
827 | 0 | } |
828 | |
|
829 | 0 | auto projectField = [&](unsigned index, const Twine &name) -> Address { |
830 | 0 | return Builder.CreateStructGEP(blockAddr, index, name); |
831 | 0 | }; |
832 | 0 | auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) { |
833 | 0 | Builder.CreateStore(value, projectField(index, name)); |
834 | 0 | }; |
835 | | |
836 | | // Initialize the block header. |
837 | 0 | { |
838 | | // We assume all the header fields are densely packed. |
839 | 0 | unsigned index = 0; |
840 | 0 | CharUnits offset; |
841 | 0 | auto addHeaderField = [&](llvm::Value *value, CharUnits size, |
842 | 0 | const Twine &name) { |
843 | 0 | storeField(value, index, name); |
844 | 0 | offset += size; |
845 | 0 | index++; |
846 | 0 | }; |
847 | |
|
848 | 0 | if (!IsOpenCL) { |
849 | 0 | addHeaderField(isa, getPointerSize(), "block.isa"); |
850 | 0 | addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()), |
851 | 0 | getIntSize(), "block.flags"); |
852 | 0 | addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(), |
853 | 0 | "block.reserved"); |
854 | 0 | } else { |
855 | 0 | addHeaderField( |
856 | 0 | llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()), |
857 | 0 | getIntSize(), "block.size"); |
858 | 0 | addHeaderField( |
859 | 0 | llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()), |
860 | 0 | getIntSize(), "block.align"); |
861 | 0 | } |
862 | 0 | addHeaderField(blockFn, GenVoidPtrSize, "block.invoke"); |
863 | 0 | if (!IsOpenCL) |
864 | 0 | addHeaderField(descriptor, getPointerSize(), "block.descriptor"); |
865 | 0 | else if (auto *Helper = |
866 | 0 | CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) { |
867 | 0 | for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) { |
868 | 0 | addHeaderField( |
869 | 0 | I.first, |
870 | 0 | CharUnits::fromQuantity( |
871 | 0 | CGM.getDataLayout().getTypeAllocSize(I.first->getType())), |
872 | 0 | I.second); |
873 | 0 | } |
874 | 0 | } |
875 | 0 | } |
876 | | |
877 | | // Finally, capture all the values into the block. |
878 | 0 | const BlockDecl *blockDecl = blockInfo.getBlockDecl(); |
879 | | |
880 | | // First, 'this'. |
881 | 0 | if (blockDecl->capturesCXXThis()) { |
882 | 0 | Address addr = |
883 | 0 | projectField(blockInfo.CXXThisIndex, "block.captured-this.addr"); |
884 | 0 | Builder.CreateStore(LoadCXXThis(), addr); |
885 | 0 | } |
886 | | |
887 | | // Next, captured variables. |
888 | 0 | for (const auto &CI : blockDecl->captures()) { |
889 | 0 | const VarDecl *variable = CI.getVariable(); |
890 | 0 | const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); |
891 | | |
892 | | // Ignore constant captures. |
893 | 0 | if (capture.isConstant()) continue; |
894 | | |
895 | 0 | QualType type = capture.fieldType(); |
896 | | |
897 | | // This will be a [[type]]*, except that a byref entry will just be |
898 | | // an i8**. |
899 | 0 | Address blockField = projectField(capture.getIndex(), "block.captured"); |
900 | | |
901 | | // Compute the address of the thing we're going to move into the |
902 | | // block literal. |
903 | 0 | Address src = Address::invalid(); |
904 | |
|
905 | 0 | if (blockDecl->isConversionFromLambda()) { |
906 | | // The lambda capture in a lambda's conversion-to-block-pointer is |
907 | | // special; we'll simply emit it directly. |
908 | 0 | src = Address::invalid(); |
909 | 0 | } else if (CI.isEscapingByref()) { |
910 | 0 | if (BlockInfo && CI.isNested()) { |
911 | | // We need to use the capture from the enclosing block. |
912 | 0 | const CGBlockInfo::Capture &enclosingCapture = |
913 | 0 | BlockInfo->getCapture(variable); |
914 | | |
915 | | // This is a [[type]]*, except that a byref entry will just be an i8**. |
916 | 0 | src = Builder.CreateStructGEP(LoadBlockStruct(), |
917 | 0 | enclosingCapture.getIndex(), |
918 | 0 | "block.capture.addr"); |
919 | 0 | } else { |
920 | 0 | auto I = LocalDeclMap.find(variable); |
921 | 0 | assert(I != LocalDeclMap.end()); |
922 | 0 | src = I->second; |
923 | 0 | } |
924 | 0 | } else { |
925 | 0 | DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable), |
926 | 0 | /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), |
927 | 0 | type.getNonReferenceType(), VK_LValue, |
928 | 0 | SourceLocation()); |
929 | 0 | src = EmitDeclRefLValue(&declRef).getAddress(*this); |
930 | 0 | }; |
931 | | |
932 | | // For byrefs, we just write the pointer to the byref struct into |
933 | | // the block field. There's no need to chase the forwarding |
934 | | // pointer at this point, since we're building something that will |
935 | | // live a shorter life than the stack byref anyway. |
936 | 0 | if (CI.isEscapingByref()) { |
937 | | // Get a void* that points to the byref struct. |
938 | 0 | llvm::Value *byrefPointer; |
939 | 0 | if (CI.isNested()) |
940 | 0 | byrefPointer = Builder.CreateLoad(src, "byref.capture"); |
941 | 0 | else |
942 | 0 | byrefPointer = src.getPointer(); |
943 | | |
944 | | // Write that void* into the capture field. |
945 | 0 | Builder.CreateStore(byrefPointer, blockField); |
946 | | |
947 | | // If we have a copy constructor, evaluate that into the block field. |
948 | 0 | } else if (const Expr *copyExpr = CI.getCopyExpr()) { |
949 | 0 | if (blockDecl->isConversionFromLambda()) { |
950 | | // If we have a lambda conversion, emit the expression |
951 | | // directly into the block instead. |
952 | 0 | AggValueSlot Slot = |
953 | 0 | AggValueSlot::forAddr(blockField, Qualifiers(), |
954 | 0 | AggValueSlot::IsDestructed, |
955 | 0 | AggValueSlot::DoesNotNeedGCBarriers, |
956 | 0 | AggValueSlot::IsNotAliased, |
957 | 0 | AggValueSlot::DoesNotOverlap); |
958 | 0 | EmitAggExpr(copyExpr, Slot); |
959 | 0 | } else { |
960 | 0 | EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr); |
961 | 0 | } |
962 | | |
963 | | // If it's a reference variable, copy the reference into the block field. |
964 | 0 | } else if (type->isReferenceType()) { |
965 | 0 | Builder.CreateStore(src.getPointer(), blockField); |
966 | | |
967 | | // If type is const-qualified, copy the value into the block field. |
968 | 0 | } else if (type.isConstQualified() && |
969 | 0 | type.getObjCLifetime() == Qualifiers::OCL_Strong && |
970 | 0 | CGM.getCodeGenOpts().OptimizationLevel != 0) { |
971 | 0 | llvm::Value *value = Builder.CreateLoad(src, "captured"); |
972 | 0 | Builder.CreateStore(value, blockField); |
973 | | |
974 | | // If this is an ARC __strong block-pointer variable, don't do a |
975 | | // block copy. |
976 | | // |
977 | | // TODO: this can be generalized into the normal initialization logic: |
978 | | // we should never need to do a block-copy when initializing a local |
979 | | // variable, because the local variable's lifetime should be strictly |
980 | | // contained within the stack block's. |
981 | 0 | } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong && |
982 | 0 | type->isBlockPointerType()) { |
983 | | // Load the block and do a simple retain. |
984 | 0 | llvm::Value *value = Builder.CreateLoad(src, "block.captured_block"); |
985 | 0 | value = EmitARCRetainNonBlock(value); |
986 | | |
987 | | // Do a primitive store to the block field. |
988 | 0 | Builder.CreateStore(value, blockField); |
989 | | |
990 | | // Otherwise, fake up a POD copy into the block field. |
991 | 0 | } else { |
992 | | // Fake up a new variable so that EmitScalarInit doesn't think |
993 | | // we're referring to the variable in its own initializer. |
994 | 0 | ImplicitParamDecl BlockFieldPseudoVar(getContext(), type, |
995 | 0 | ImplicitParamKind::Other); |
996 | | |
997 | | // We use one of these or the other depending on whether the |
998 | | // reference is nested. |
999 | 0 | DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable), |
1000 | 0 | /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), |
1001 | 0 | type, VK_LValue, SourceLocation()); |
1002 | |
|
1003 | 0 | ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue, |
1004 | 0 | &declRef, VK_PRValue, FPOptionsOverride()); |
1005 | | // FIXME: Pass a specific location for the expr init so that the store is |
1006 | | // attributed to a reasonable location - otherwise it may be attributed to |
1007 | | // locations of subexpressions in the initialization. |
1008 | 0 | EmitExprAsInit(&l2r, &BlockFieldPseudoVar, |
1009 | 0 | MakeAddrLValue(blockField, type, AlignmentSource::Decl), |
1010 | 0 | /*captured by init*/ false); |
1011 | 0 | } |
1012 | | |
1013 | | // Push a cleanup for the capture if necessary. |
1014 | 0 | if (!blockInfo.NoEscape && !blockInfo.NeedsCopyDispose) |
1015 | 0 | continue; |
1016 | | |
1017 | | // Ignore __block captures; there's nothing special in the on-stack block |
1018 | | // that we need to do for them. |
1019 | 0 | if (CI.isByRef()) |
1020 | 0 | continue; |
1021 | | |
1022 | | // Ignore objects that aren't destructed. |
1023 | 0 | QualType::DestructionKind dtorKind = type.isDestructedType(); |
1024 | 0 | if (dtorKind == QualType::DK_none) |
1025 | 0 | continue; |
1026 | | |
1027 | 0 | CodeGenFunction::Destroyer *destroyer; |
1028 | | |
1029 | | // Block captures count as local values and have imprecise semantics. |
1030 | | // They also can't be arrays, so need to worry about that. |
1031 | | // |
1032 | | // For const-qualified captures, emit clang.arc.use to ensure the captured |
1033 | | // object doesn't get released while we are still depending on its validity |
1034 | | // within the block. |
1035 | 0 | if (type.isConstQualified() && |
1036 | 0 | type.getObjCLifetime() == Qualifiers::OCL_Strong && |
1037 | 0 | CGM.getCodeGenOpts().OptimizationLevel != 0) { |
1038 | 0 | assert(CGM.getLangOpts().ObjCAutoRefCount && |
1039 | 0 | "expected ObjC ARC to be enabled"); |
1040 | 0 | destroyer = emitARCIntrinsicUse; |
1041 | 0 | } else if (dtorKind == QualType::DK_objc_strong_lifetime) { |
1042 | 0 | destroyer = destroyARCStrongImprecise; |
1043 | 0 | } else { |
1044 | 0 | destroyer = getDestroyer(dtorKind); |
1045 | 0 | } |
1046 | | |
1047 | 0 | CleanupKind cleanupKind = NormalCleanup; |
1048 | 0 | bool useArrayEHCleanup = needsEHCleanup(dtorKind); |
1049 | 0 | if (useArrayEHCleanup) |
1050 | 0 | cleanupKind = NormalAndEHCleanup; |
1051 | | |
1052 | | // Extend the lifetime of the capture to the end of the scope enclosing the |
1053 | | // block expression except when the block decl is in the list of RetExpr's |
1054 | | // cleanup objects, in which case its lifetime ends after the full |
1055 | | // expression. |
1056 | 0 | auto IsBlockDeclInRetExpr = [&]() { |
1057 | 0 | auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr); |
1058 | 0 | if (EWC) |
1059 | 0 | for (auto &C : EWC->getObjects()) |
1060 | 0 | if (auto *BD = C.dyn_cast<BlockDecl *>()) |
1061 | 0 | if (BD == blockDecl) |
1062 | 0 | return true; |
1063 | 0 | return false; |
1064 | 0 | }; |
1065 | |
|
1066 | 0 | if (IsBlockDeclInRetExpr()) |
1067 | 0 | pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup); |
1068 | 0 | else |
1069 | 0 | pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer, |
1070 | 0 | useArrayEHCleanup); |
1071 | 0 | } |
1072 | | |
1073 | | // Cast to the converted block-pointer type, which happens (somewhat |
1074 | | // unfortunately) to be a pointer to function type. |
1075 | 0 | llvm::Value *result = Builder.CreatePointerCast( |
1076 | 0 | blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType())); |
1077 | |
|
1078 | 0 | if (IsOpenCL) { |
1079 | 0 | CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn, |
1080 | 0 | result, blockInfo.StructureType); |
1081 | 0 | } |
1082 | |
|
1083 | 0 | return result; |
1084 | 0 | } |
1085 | | |
1086 | | |
1087 | 0 | llvm::Type *CodeGenModule::getBlockDescriptorType() { |
1088 | 0 | if (BlockDescriptorType) |
1089 | 0 | return BlockDescriptorType; |
1090 | | |
1091 | 0 | llvm::Type *UnsignedLongTy = |
1092 | 0 | getTypes().ConvertType(getContext().UnsignedLongTy); |
1093 | | |
1094 | | // struct __block_descriptor { |
1095 | | // unsigned long reserved; |
1096 | | // unsigned long block_size; |
1097 | | // |
1098 | | // // later, the following will be added |
1099 | | // |
1100 | | // struct { |
1101 | | // void (*copyHelper)(); |
1102 | | // void (*copyHelper)(); |
1103 | | // } helpers; // !!! optional |
1104 | | // |
1105 | | // const char *signature; // the block signature |
1106 | | // const char *layout; // reserved |
1107 | | // }; |
1108 | 0 | BlockDescriptorType = llvm::StructType::create( |
1109 | 0 | "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy); |
1110 | | |
1111 | | // Now form a pointer to that. |
1112 | 0 | unsigned AddrSpace = 0; |
1113 | 0 | if (getLangOpts().OpenCL) |
1114 | 0 | AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant); |
1115 | 0 | BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace); |
1116 | 0 | return BlockDescriptorType; |
1117 | 0 | } |
1118 | | |
1119 | 0 | llvm::Type *CodeGenModule::getGenericBlockLiteralType() { |
1120 | 0 | if (GenericBlockLiteralType) |
1121 | 0 | return GenericBlockLiteralType; |
1122 | | |
1123 | 0 | llvm::Type *BlockDescPtrTy = getBlockDescriptorType(); |
1124 | |
|
1125 | 0 | if (getLangOpts().OpenCL) { |
1126 | | // struct __opencl_block_literal_generic { |
1127 | | // int __size; |
1128 | | // int __align; |
1129 | | // __generic void *__invoke; |
1130 | | // /* custom fields */ |
1131 | | // }; |
1132 | 0 | SmallVector<llvm::Type *, 8> StructFields( |
1133 | 0 | {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()}); |
1134 | 0 | if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) { |
1135 | 0 | llvm::append_range(StructFields, Helper->getCustomFieldTypes()); |
1136 | 0 | } |
1137 | 0 | GenericBlockLiteralType = llvm::StructType::create( |
1138 | 0 | StructFields, "struct.__opencl_block_literal_generic"); |
1139 | 0 | } else { |
1140 | | // struct __block_literal_generic { |
1141 | | // void *__isa; |
1142 | | // int __flags; |
1143 | | // int __reserved; |
1144 | | // void (*__invoke)(void *); |
1145 | | // struct __block_descriptor *__descriptor; |
1146 | | // }; |
1147 | 0 | GenericBlockLiteralType = |
1148 | 0 | llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy, |
1149 | 0 | IntTy, IntTy, VoidPtrTy, BlockDescPtrTy); |
1150 | 0 | } |
1151 | |
|
1152 | 0 | return GenericBlockLiteralType; |
1153 | 0 | } |
1154 | | |
1155 | | RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E, |
1156 | 0 | ReturnValueSlot ReturnValue) { |
1157 | 0 | const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>(); |
1158 | 0 | llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee()); |
1159 | 0 | llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType(); |
1160 | 0 | llvm::Value *Func = nullptr; |
1161 | 0 | QualType FnType = BPT->getPointeeType(); |
1162 | 0 | ASTContext &Ctx = getContext(); |
1163 | 0 | CallArgList Args; |
1164 | |
|
1165 | 0 | if (getLangOpts().OpenCL) { |
1166 | | // For OpenCL, BlockPtr is already casted to generic block literal. |
1167 | | |
1168 | | // First argument of a block call is a generic block literal casted to |
1169 | | // generic void pointer, i.e. i8 addrspace(4)* |
1170 | 0 | llvm::Type *GenericVoidPtrTy = |
1171 | 0 | CGM.getOpenCLRuntime().getGenericVoidPointerType(); |
1172 | 0 | llvm::Value *BlockDescriptor = Builder.CreatePointerCast( |
1173 | 0 | BlockPtr, GenericVoidPtrTy); |
1174 | 0 | QualType VoidPtrQualTy = Ctx.getPointerType( |
1175 | 0 | Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic)); |
1176 | 0 | Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy); |
1177 | | // And the rest of the arguments. |
1178 | 0 | EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments()); |
1179 | | |
1180 | | // We *can* call the block directly unless it is a function argument. |
1181 | 0 | if (!isa<ParmVarDecl>(E->getCalleeDecl())) |
1182 | 0 | Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee()); |
1183 | 0 | else { |
1184 | 0 | llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2); |
1185 | 0 | Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr, |
1186 | 0 | getPointerAlign()); |
1187 | 0 | } |
1188 | 0 | } else { |
1189 | | // Bitcast the block literal to a generic block literal. |
1190 | 0 | BlockPtr = |
1191 | 0 | Builder.CreatePointerCast(BlockPtr, UnqualPtrTy, "block.literal"); |
1192 | | // Get pointer to the block invoke function |
1193 | 0 | llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3); |
1194 | | |
1195 | | // First argument is a block literal casted to a void pointer |
1196 | 0 | BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy); |
1197 | 0 | Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy); |
1198 | | // And the rest of the arguments. |
1199 | 0 | EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments()); |
1200 | | |
1201 | | // Load the function. |
1202 | 0 | Func = Builder.CreateAlignedLoad(VoidPtrTy, FuncPtr, getPointerAlign()); |
1203 | 0 | } |
1204 | |
|
1205 | 0 | const FunctionType *FuncTy = FnType->castAs<FunctionType>(); |
1206 | 0 | const CGFunctionInfo &FnInfo = |
1207 | 0 | CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy); |
1208 | | |
1209 | | // Prepare the callee. |
1210 | 0 | CGCallee Callee(CGCalleeInfo(), Func); |
1211 | | |
1212 | | // And call the block. |
1213 | 0 | return EmitCall(FnInfo, Callee, ReturnValue, Args); |
1214 | 0 | } |
1215 | | |
1216 | 0 | Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) { |
1217 | 0 | assert(BlockInfo && "evaluating block ref without block information?"); |
1218 | 0 | const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable); |
1219 | | |
1220 | | // Handle constant captures. |
1221 | 0 | if (capture.isConstant()) return LocalDeclMap.find(variable)->second; |
1222 | | |
1223 | 0 | Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(), |
1224 | 0 | "block.capture.addr"); |
1225 | |
|
1226 | 0 | if (variable->isEscapingByref()) { |
1227 | | // addr should be a void** right now. Load, then cast the result |
1228 | | // to byref*. |
1229 | |
|
1230 | 0 | auto &byrefInfo = getBlockByrefInfo(variable); |
1231 | 0 | addr = Address(Builder.CreateLoad(addr), byrefInfo.Type, |
1232 | 0 | byrefInfo.ByrefAlignment); |
1233 | |
|
1234 | 0 | addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true, |
1235 | 0 | variable->getName()); |
1236 | 0 | } |
1237 | |
|
1238 | 0 | assert((!variable->isNonEscapingByref() || |
1239 | 0 | capture.fieldType()->isReferenceType()) && |
1240 | 0 | "the capture field of a non-escaping variable should have a " |
1241 | 0 | "reference type"); |
1242 | 0 | if (capture.fieldType()->isReferenceType()) |
1243 | 0 | addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType())); |
1244 | |
|
1245 | 0 | return addr; |
1246 | 0 | } |
1247 | | |
1248 | | void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE, |
1249 | 0 | llvm::Constant *Addr) { |
1250 | 0 | bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second; |
1251 | 0 | (void)Ok; |
1252 | 0 | assert(Ok && "Trying to replace an already-existing global block!"); |
1253 | 0 | } |
1254 | | |
1255 | | llvm::Constant * |
1256 | | CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, |
1257 | 0 | StringRef Name) { |
1258 | 0 | if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE)) |
1259 | 0 | return Block; |
1260 | | |
1261 | 0 | CGBlockInfo blockInfo(BE->getBlockDecl(), Name); |
1262 | 0 | blockInfo.BlockExpression = BE; |
1263 | | |
1264 | | // Compute information about the layout, etc., of this block. |
1265 | 0 | computeBlockInfo(*this, nullptr, blockInfo); |
1266 | | |
1267 | | // Using that metadata, generate the actual block function. |
1268 | 0 | { |
1269 | 0 | CodeGenFunction::DeclMapTy LocalDeclMap; |
1270 | 0 | CodeGenFunction(*this).GenerateBlockFunction( |
1271 | 0 | GlobalDecl(), blockInfo, LocalDeclMap, |
1272 | 0 | /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true); |
1273 | 0 | } |
1274 | |
|
1275 | 0 | return getAddrOfGlobalBlockIfEmitted(BE); |
1276 | 0 | } |
1277 | | |
1278 | | static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM, |
1279 | | const CGBlockInfo &blockInfo, |
1280 | 0 | llvm::Constant *blockFn) { |
1281 | 0 | assert(blockInfo.CanBeGlobal); |
1282 | | // Callers should detect this case on their own: calling this function |
1283 | | // generally requires computing layout information, which is a waste of time |
1284 | | // if we've already emitted this block. |
1285 | 0 | assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) && |
1286 | 0 | "Refusing to re-emit a global block."); |
1287 | | |
1288 | | // Generate the constants for the block literal initializer. |
1289 | 0 | ConstantInitBuilder builder(CGM); |
1290 | 0 | auto fields = builder.beginStruct(); |
1291 | |
|
1292 | 0 | bool IsOpenCL = CGM.getLangOpts().OpenCL; |
1293 | 0 | bool IsWindows = CGM.getTarget().getTriple().isOSWindows(); |
1294 | 0 | if (!IsOpenCL) { |
1295 | | // isa |
1296 | 0 | if (IsWindows) |
1297 | 0 | fields.addNullPointer(CGM.Int8PtrPtrTy); |
1298 | 0 | else |
1299 | 0 | fields.add(CGM.getNSConcreteGlobalBlock()); |
1300 | | |
1301 | | // __flags |
1302 | 0 | BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE; |
1303 | 0 | if (blockInfo.UsesStret) |
1304 | 0 | flags |= BLOCK_USE_STRET; |
1305 | |
|
1306 | 0 | fields.addInt(CGM.IntTy, flags.getBitMask()); |
1307 | | |
1308 | | // Reserved |
1309 | 0 | fields.addInt(CGM.IntTy, 0); |
1310 | 0 | } else { |
1311 | 0 | fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity()); |
1312 | 0 | fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity()); |
1313 | 0 | } |
1314 | | |
1315 | | // Function |
1316 | 0 | fields.add(blockFn); |
1317 | |
|
1318 | 0 | if (!IsOpenCL) { |
1319 | | // Descriptor |
1320 | 0 | fields.add(buildBlockDescriptor(CGM, blockInfo)); |
1321 | 0 | } else if (auto *Helper = |
1322 | 0 | CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) { |
1323 | 0 | for (auto *I : Helper->getCustomFieldValues(CGM, blockInfo)) { |
1324 | 0 | fields.add(I); |
1325 | 0 | } |
1326 | 0 | } |
1327 | |
|
1328 | 0 | unsigned AddrSpace = 0; |
1329 | 0 | if (CGM.getContext().getLangOpts().OpenCL) |
1330 | 0 | AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global); |
1331 | |
|
1332 | 0 | llvm::GlobalVariable *literal = fields.finishAndCreateGlobal( |
1333 | 0 | "__block_literal_global", blockInfo.BlockAlign, |
1334 | 0 | /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace); |
1335 | |
|
1336 | 0 | literal->addAttribute("objc_arc_inert"); |
1337 | | |
1338 | | // Windows does not allow globals to be initialised to point to globals in |
1339 | | // different DLLs. Any such variables must run code to initialise them. |
1340 | 0 | if (IsWindows) { |
1341 | 0 | auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy, |
1342 | 0 | {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init", |
1343 | 0 | &CGM.getModule()); |
1344 | 0 | llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry", |
1345 | 0 | Init)); |
1346 | 0 | b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(), |
1347 | 0 | b.CreateStructGEP(literal->getValueType(), literal, 0), |
1348 | 0 | CGM.getPointerAlign().getAsAlign()); |
1349 | 0 | b.CreateRetVoid(); |
1350 | | // We can't use the normal LLVM global initialisation array, because we |
1351 | | // need to specify that this runs early in library initialisation. |
1352 | 0 | auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), |
1353 | 0 | /*isConstant*/true, llvm::GlobalValue::InternalLinkage, |
1354 | 0 | Init, ".block_isa_init_ptr"); |
1355 | 0 | InitVar->setSection(".CRT$XCLa"); |
1356 | 0 | CGM.addUsedGlobal(InitVar); |
1357 | 0 | } |
1358 | | |
1359 | | // Return a constant of the appropriately-casted type. |
1360 | 0 | llvm::Type *RequiredType = |
1361 | 0 | CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType()); |
1362 | 0 | llvm::Constant *Result = |
1363 | 0 | llvm::ConstantExpr::getPointerCast(literal, RequiredType); |
1364 | 0 | CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result); |
1365 | 0 | if (CGM.getContext().getLangOpts().OpenCL) |
1366 | 0 | CGM.getOpenCLRuntime().recordBlockInfo( |
1367 | 0 | blockInfo.BlockExpression, |
1368 | 0 | cast<llvm::Function>(blockFn->stripPointerCasts()), Result, |
1369 | 0 | literal->getValueType()); |
1370 | 0 | return Result; |
1371 | 0 | } |
1372 | | |
1373 | | void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D, |
1374 | | unsigned argNum, |
1375 | 0 | llvm::Value *arg) { |
1376 | 0 | assert(BlockInfo && "not emitting prologue of block invocation function?!"); |
1377 | | |
1378 | | // Allocate a stack slot like for any local variable to guarantee optimal |
1379 | | // debug info at -O0. The mem2reg pass will eliminate it when optimizing. |
1380 | 0 | Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr"); |
1381 | 0 | Builder.CreateStore(arg, alloc); |
1382 | 0 | if (CGDebugInfo *DI = getDebugInfo()) { |
1383 | 0 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { |
1384 | 0 | DI->setLocation(D->getLocation()); |
1385 | 0 | DI->EmitDeclareOfBlockLiteralArgVariable( |
1386 | 0 | *BlockInfo, D->getName(), argNum, |
1387 | 0 | cast<llvm::AllocaInst>(alloc.getPointer()), Builder); |
1388 | 0 | } |
1389 | 0 | } |
1390 | |
|
1391 | 0 | SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc(); |
1392 | 0 | ApplyDebugLocation Scope(*this, StartLoc); |
1393 | | |
1394 | | // Instead of messing around with LocalDeclMap, just set the value |
1395 | | // directly as BlockPointer. |
1396 | 0 | BlockPointer = Builder.CreatePointerCast( |
1397 | 0 | arg, |
1398 | 0 | llvm::PointerType::get( |
1399 | 0 | getLLVMContext(), |
1400 | 0 | getContext().getLangOpts().OpenCL |
1401 | 0 | ? getContext().getTargetAddressSpace(LangAS::opencl_generic) |
1402 | 0 | : 0), |
1403 | 0 | "block"); |
1404 | 0 | } |
1405 | | |
1406 | 0 | Address CodeGenFunction::LoadBlockStruct() { |
1407 | 0 | assert(BlockInfo && "not in a block invocation function!"); |
1408 | 0 | assert(BlockPointer && "no block pointer set!"); |
1409 | 0 | return Address(BlockPointer, BlockInfo->StructureType, BlockInfo->BlockAlign); |
1410 | 0 | } |
1411 | | |
1412 | | llvm::Function *CodeGenFunction::GenerateBlockFunction( |
1413 | | GlobalDecl GD, const CGBlockInfo &blockInfo, const DeclMapTy &ldm, |
1414 | 0 | bool IsLambdaConversionToBlock, bool BuildGlobalBlock) { |
1415 | 0 | const BlockDecl *blockDecl = blockInfo.getBlockDecl(); |
1416 | |
|
1417 | 0 | CurGD = GD; |
1418 | |
|
1419 | 0 | CurEHLocation = blockInfo.getBlockExpr()->getEndLoc(); |
1420 | |
|
1421 | 0 | BlockInfo = &blockInfo; |
1422 | | |
1423 | | // Arrange for local static and local extern declarations to appear |
1424 | | // to be local to this function as well, in case they're directly |
1425 | | // referenced in a block. |
1426 | 0 | for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) { |
1427 | 0 | const auto *var = dyn_cast<VarDecl>(i->first); |
1428 | 0 | if (var && !var->hasLocalStorage()) |
1429 | 0 | setAddrOfLocalVar(var, i->second); |
1430 | 0 | } |
1431 | | |
1432 | | // Begin building the function declaration. |
1433 | | |
1434 | | // Build the argument list. |
1435 | 0 | FunctionArgList args; |
1436 | | |
1437 | | // The first argument is the block pointer. Just take it as a void* |
1438 | | // and cast it later. |
1439 | 0 | QualType selfTy = getContext().VoidPtrTy; |
1440 | | |
1441 | | // For OpenCL passed block pointer can be private AS local variable or |
1442 | | // global AS program scope variable (for the case with and without captures). |
1443 | | // Generic AS is used therefore to be able to accommodate both private and |
1444 | | // generic AS in one implementation. |
1445 | 0 | if (getLangOpts().OpenCL) |
1446 | 0 | selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType( |
1447 | 0 | getContext().VoidTy, LangAS::opencl_generic)); |
1448 | |
|
1449 | 0 | IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor"); |
1450 | |
|
1451 | 0 | ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl), |
1452 | 0 | SourceLocation(), II, selfTy, |
1453 | 0 | ImplicitParamKind::ObjCSelf); |
1454 | 0 | args.push_back(&SelfDecl); |
1455 | | |
1456 | | // Now add the rest of the parameters. |
1457 | 0 | args.append(blockDecl->param_begin(), blockDecl->param_end()); |
1458 | | |
1459 | | // Create the function declaration. |
1460 | 0 | const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType(); |
1461 | 0 | const CGFunctionInfo &fnInfo = |
1462 | 0 | CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args); |
1463 | 0 | if (CGM.ReturnSlotInterferesWithArgs(fnInfo)) |
1464 | 0 | blockInfo.UsesStret = true; |
1465 | |
|
1466 | 0 | llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo); |
1467 | |
|
1468 | 0 | StringRef name = CGM.getBlockMangledName(GD, blockDecl); |
1469 | 0 | llvm::Function *fn = llvm::Function::Create( |
1470 | 0 | fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule()); |
1471 | 0 | CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo); |
1472 | |
|
1473 | 0 | if (BuildGlobalBlock) { |
1474 | 0 | auto GenVoidPtrTy = getContext().getLangOpts().OpenCL |
1475 | 0 | ? CGM.getOpenCLRuntime().getGenericVoidPointerType() |
1476 | 0 | : VoidPtrTy; |
1477 | 0 | buildGlobalBlock(CGM, blockInfo, |
1478 | 0 | llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy)); |
1479 | 0 | } |
1480 | | |
1481 | | // Begin generating the function. |
1482 | 0 | StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args, |
1483 | 0 | blockDecl->getLocation(), |
1484 | 0 | blockInfo.getBlockExpr()->getBody()->getBeginLoc()); |
1485 | | |
1486 | | // Okay. Undo some of what StartFunction did. |
1487 | | |
1488 | | // At -O0 we generate an explicit alloca for the BlockPointer, so the RA |
1489 | | // won't delete the dbg.declare intrinsics for captured variables. |
1490 | 0 | llvm::Value *BlockPointerDbgLoc = BlockPointer; |
1491 | 0 | if (CGM.getCodeGenOpts().OptimizationLevel == 0) { |
1492 | | // Allocate a stack slot for it, so we can point the debugger to it |
1493 | 0 | Address Alloca = CreateTempAlloca(BlockPointer->getType(), |
1494 | 0 | getPointerAlign(), |
1495 | 0 | "block.addr"); |
1496 | | // Set the DebugLocation to empty, so the store is recognized as a |
1497 | | // frame setup instruction by llvm::DwarfDebug::beginFunction(). |
1498 | 0 | auto NL = ApplyDebugLocation::CreateEmpty(*this); |
1499 | 0 | Builder.CreateStore(BlockPointer, Alloca); |
1500 | 0 | BlockPointerDbgLoc = Alloca.getPointer(); |
1501 | 0 | } |
1502 | | |
1503 | | // If we have a C++ 'this' reference, go ahead and force it into |
1504 | | // existence now. |
1505 | 0 | if (blockDecl->capturesCXXThis()) { |
1506 | 0 | Address addr = Builder.CreateStructGEP( |
1507 | 0 | LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this"); |
1508 | 0 | CXXThisValue = Builder.CreateLoad(addr, "this"); |
1509 | 0 | } |
1510 | | |
1511 | | // Also force all the constant captures. |
1512 | 0 | for (const auto &CI : blockDecl->captures()) { |
1513 | 0 | const VarDecl *variable = CI.getVariable(); |
1514 | 0 | const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); |
1515 | 0 | if (!capture.isConstant()) continue; |
1516 | | |
1517 | 0 | CharUnits align = getContext().getDeclAlign(variable); |
1518 | 0 | Address alloca = |
1519 | 0 | CreateMemTemp(variable->getType(), align, "block.captured-const"); |
1520 | |
|
1521 | 0 | Builder.CreateStore(capture.getConstant(), alloca); |
1522 | |
|
1523 | 0 | setAddrOfLocalVar(variable, alloca); |
1524 | 0 | } |
1525 | | |
1526 | | // Save a spot to insert the debug information for all the DeclRefExprs. |
1527 | 0 | llvm::BasicBlock *entry = Builder.GetInsertBlock(); |
1528 | 0 | llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint(); |
1529 | 0 | --entry_ptr; |
1530 | |
|
1531 | 0 | if (IsLambdaConversionToBlock) |
1532 | 0 | EmitLambdaBlockInvokeBody(); |
1533 | 0 | else { |
1534 | 0 | PGO.assignRegionCounters(GlobalDecl(blockDecl), fn); |
1535 | 0 | incrementProfileCounter(blockDecl->getBody()); |
1536 | 0 | EmitStmt(blockDecl->getBody()); |
1537 | 0 | } |
1538 | | |
1539 | | // Remember where we were... |
1540 | 0 | llvm::BasicBlock *resume = Builder.GetInsertBlock(); |
1541 | | |
1542 | | // Go back to the entry. |
1543 | 0 | ++entry_ptr; |
1544 | 0 | Builder.SetInsertPoint(entry, entry_ptr); |
1545 | | |
1546 | | // Emit debug information for all the DeclRefExprs. |
1547 | | // FIXME: also for 'this' |
1548 | 0 | if (CGDebugInfo *DI = getDebugInfo()) { |
1549 | 0 | for (const auto &CI : blockDecl->captures()) { |
1550 | 0 | const VarDecl *variable = CI.getVariable(); |
1551 | 0 | DI->EmitLocation(Builder, variable->getLocation()); |
1552 | |
|
1553 | 0 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { |
1554 | 0 | const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); |
1555 | 0 | if (capture.isConstant()) { |
1556 | 0 | auto addr = LocalDeclMap.find(variable)->second; |
1557 | 0 | (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(), |
1558 | 0 | Builder); |
1559 | 0 | continue; |
1560 | 0 | } |
1561 | | |
1562 | 0 | DI->EmitDeclareOfBlockDeclRefVariable( |
1563 | 0 | variable, BlockPointerDbgLoc, Builder, blockInfo, |
1564 | 0 | entry_ptr == entry->end() ? nullptr : &*entry_ptr); |
1565 | 0 | } |
1566 | 0 | } |
1567 | | // Recover location if it was changed in the above loop. |
1568 | 0 | DI->EmitLocation(Builder, |
1569 | 0 | cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc()); |
1570 | 0 | } |
1571 | | |
1572 | | // And resume where we left off. |
1573 | 0 | if (resume == nullptr) |
1574 | 0 | Builder.ClearInsertionPoint(); |
1575 | 0 | else |
1576 | 0 | Builder.SetInsertPoint(resume); |
1577 | |
|
1578 | 0 | FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc()); |
1579 | |
|
1580 | 0 | return fn; |
1581 | 0 | } |
1582 | | |
1583 | | static std::pair<BlockCaptureEntityKind, BlockFieldFlags> |
1584 | | computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T, |
1585 | 0 | const LangOptions &LangOpts) { |
1586 | 0 | if (CI.getCopyExpr()) { |
1587 | 0 | assert(!CI.isByRef()); |
1588 | | // don't bother computing flags |
1589 | 0 | return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags()); |
1590 | 0 | } |
1591 | 0 | BlockFieldFlags Flags; |
1592 | 0 | if (CI.isEscapingByref()) { |
1593 | 0 | Flags = BLOCK_FIELD_IS_BYREF; |
1594 | 0 | if (T.isObjCGCWeak()) |
1595 | 0 | Flags |= BLOCK_FIELD_IS_WEAK; |
1596 | 0 | return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags); |
1597 | 0 | } |
1598 | | |
1599 | 0 | Flags = BLOCK_FIELD_IS_OBJECT; |
1600 | 0 | bool isBlockPointer = T->isBlockPointerType(); |
1601 | 0 | if (isBlockPointer) |
1602 | 0 | Flags = BLOCK_FIELD_IS_BLOCK; |
1603 | |
|
1604 | 0 | switch (T.isNonTrivialToPrimitiveCopy()) { |
1605 | 0 | case QualType::PCK_Struct: |
1606 | 0 | return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct, |
1607 | 0 | BlockFieldFlags()); |
1608 | 0 | case QualType::PCK_ARCWeak: |
1609 | | // We need to register __weak direct captures with the runtime. |
1610 | 0 | return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags); |
1611 | 0 | case QualType::PCK_ARCStrong: |
1612 | | // We need to retain the copied value for __strong direct captures. |
1613 | | // If it's a block pointer, we have to copy the block and assign that to |
1614 | | // the destination pointer, so we might as well use _Block_object_assign. |
1615 | | // Otherwise we can avoid that. |
1616 | 0 | return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong |
1617 | 0 | : BlockCaptureEntityKind::BlockObject, |
1618 | 0 | Flags); |
1619 | 0 | case QualType::PCK_Trivial: |
1620 | 0 | case QualType::PCK_VolatileTrivial: { |
1621 | 0 | if (!T->isObjCRetainableType()) |
1622 | | // For all other types, the memcpy is fine. |
1623 | 0 | return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags()); |
1624 | | |
1625 | | // Honor the inert __unsafe_unretained qualifier, which doesn't actually |
1626 | | // make it into the type system. |
1627 | 0 | if (T->isObjCInertUnsafeUnretainedType()) |
1628 | 0 | return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags()); |
1629 | | |
1630 | | // Special rules for ARC captures: |
1631 | 0 | Qualifiers QS = T.getQualifiers(); |
1632 | | |
1633 | | // Non-ARC captures of retainable pointers are strong and |
1634 | | // therefore require a call to _Block_object_assign. |
1635 | 0 | if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount) |
1636 | 0 | return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags); |
1637 | | |
1638 | | // Otherwise the memcpy is fine. |
1639 | 0 | return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags()); |
1640 | 0 | } |
1641 | 0 | } |
1642 | 0 | llvm_unreachable("after exhaustive PrimitiveCopyKind switch"); |
1643 | 0 | } |
1644 | | |
1645 | | namespace { |
1646 | | /// Release a __block variable. |
1647 | | struct CallBlockRelease final : EHScopeStack::Cleanup { |
1648 | | Address Addr; |
1649 | | BlockFieldFlags FieldFlags; |
1650 | | bool LoadBlockVarAddr, CanThrow; |
1651 | | |
1652 | | CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue, |
1653 | | bool CT) |
1654 | | : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue), |
1655 | 0 | CanThrow(CT) {} |
1656 | | |
1657 | 0 | void Emit(CodeGenFunction &CGF, Flags flags) override { |
1658 | 0 | llvm::Value *BlockVarAddr; |
1659 | 0 | if (LoadBlockVarAddr) { |
1660 | 0 | BlockVarAddr = CGF.Builder.CreateLoad(Addr); |
1661 | 0 | } else { |
1662 | 0 | BlockVarAddr = Addr.getPointer(); |
1663 | 0 | } |
1664 | |
|
1665 | 0 | CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow); |
1666 | 0 | } |
1667 | | }; |
1668 | | } // end anonymous namespace |
1669 | | |
1670 | | /// Check if \p T is a C++ class that has a destructor that can throw. |
1671 | 0 | bool CodeGenFunction::cxxDestructorCanThrow(QualType T) { |
1672 | 0 | if (const auto *RD = T->getAsCXXRecordDecl()) |
1673 | 0 | if (const CXXDestructorDecl *DD = RD->getDestructor()) |
1674 | 0 | return DD->getType()->castAs<FunctionProtoType>()->canThrow(); |
1675 | 0 | return false; |
1676 | 0 | } |
1677 | | |
1678 | | // Return a string that has the information about a capture. |
1679 | | static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap, |
1680 | | CaptureStrKind StrKind, |
1681 | | CharUnits BlockAlignment, |
1682 | 0 | CodeGenModule &CGM) { |
1683 | 0 | std::string Str; |
1684 | 0 | ASTContext &Ctx = CGM.getContext(); |
1685 | 0 | const BlockDecl::Capture &CI = *Cap.Cap; |
1686 | 0 | QualType CaptureTy = CI.getVariable()->getType(); |
1687 | |
|
1688 | 0 | BlockCaptureEntityKind Kind; |
1689 | 0 | BlockFieldFlags Flags; |
1690 | | |
1691 | | // CaptureStrKind::Merged should be passed only when the operations and the |
1692 | | // flags are the same for copy and dispose. |
1693 | 0 | assert((StrKind != CaptureStrKind::Merged || |
1694 | 0 | (Cap.CopyKind == Cap.DisposeKind && |
1695 | 0 | Cap.CopyFlags == Cap.DisposeFlags)) && |
1696 | 0 | "different operations and flags"); |
1697 | | |
1698 | 0 | if (StrKind == CaptureStrKind::DisposeHelper) { |
1699 | 0 | Kind = Cap.DisposeKind; |
1700 | 0 | Flags = Cap.DisposeFlags; |
1701 | 0 | } else { |
1702 | 0 | Kind = Cap.CopyKind; |
1703 | 0 | Flags = Cap.CopyFlags; |
1704 | 0 | } |
1705 | |
|
1706 | 0 | switch (Kind) { |
1707 | 0 | case BlockCaptureEntityKind::CXXRecord: { |
1708 | 0 | Str += "c"; |
1709 | 0 | SmallString<256> TyStr; |
1710 | 0 | llvm::raw_svector_ostream Out(TyStr); |
1711 | 0 | CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(CaptureTy, Out); |
1712 | 0 | Str += llvm::to_string(TyStr.size()) + TyStr.c_str(); |
1713 | 0 | break; |
1714 | 0 | } |
1715 | 0 | case BlockCaptureEntityKind::ARCWeak: |
1716 | 0 | Str += "w"; |
1717 | 0 | break; |
1718 | 0 | case BlockCaptureEntityKind::ARCStrong: |
1719 | 0 | Str += "s"; |
1720 | 0 | break; |
1721 | 0 | case BlockCaptureEntityKind::BlockObject: { |
1722 | 0 | const VarDecl *Var = CI.getVariable(); |
1723 | 0 | unsigned F = Flags.getBitMask(); |
1724 | 0 | if (F & BLOCK_FIELD_IS_BYREF) { |
1725 | 0 | Str += "r"; |
1726 | 0 | if (F & BLOCK_FIELD_IS_WEAK) |
1727 | 0 | Str += "w"; |
1728 | 0 | else { |
1729 | | // If CaptureStrKind::Merged is passed, check both the copy expression |
1730 | | // and the destructor. |
1731 | 0 | if (StrKind != CaptureStrKind::DisposeHelper) { |
1732 | 0 | if (Ctx.getBlockVarCopyInit(Var).canThrow()) |
1733 | 0 | Str += "c"; |
1734 | 0 | } |
1735 | 0 | if (StrKind != CaptureStrKind::CopyHelper) { |
1736 | 0 | if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy)) |
1737 | 0 | Str += "d"; |
1738 | 0 | } |
1739 | 0 | } |
1740 | 0 | } else { |
1741 | 0 | assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value"); |
1742 | 0 | if (F == BLOCK_FIELD_IS_BLOCK) |
1743 | 0 | Str += "b"; |
1744 | 0 | else |
1745 | 0 | Str += "o"; |
1746 | 0 | } |
1747 | 0 | break; |
1748 | 0 | } |
1749 | 0 | case BlockCaptureEntityKind::NonTrivialCStruct: { |
1750 | 0 | bool IsVolatile = CaptureTy.isVolatileQualified(); |
1751 | 0 | CharUnits Alignment = BlockAlignment.alignmentAtOffset(Cap.getOffset()); |
1752 | |
|
1753 | 0 | Str += "n"; |
1754 | 0 | std::string FuncStr; |
1755 | 0 | if (StrKind == CaptureStrKind::DisposeHelper) |
1756 | 0 | FuncStr = CodeGenFunction::getNonTrivialDestructorStr( |
1757 | 0 | CaptureTy, Alignment, IsVolatile, Ctx); |
1758 | 0 | else |
1759 | | // If CaptureStrKind::Merged is passed, use the copy constructor string. |
1760 | | // It has all the information that the destructor string has. |
1761 | 0 | FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr( |
1762 | 0 | CaptureTy, Alignment, IsVolatile, Ctx); |
1763 | | // The underscore is necessary here because non-trivial copy constructor |
1764 | | // and destructor strings can start with a number. |
1765 | 0 | Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr; |
1766 | 0 | break; |
1767 | 0 | } |
1768 | 0 | case BlockCaptureEntityKind::None: |
1769 | 0 | break; |
1770 | 0 | } |
1771 | | |
1772 | 0 | return Str; |
1773 | 0 | } |
1774 | | |
1775 | | static std::string getCopyDestroyHelperFuncName( |
1776 | | const SmallVectorImpl<CGBlockInfo::Capture> &Captures, |
1777 | 0 | CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) { |
1778 | 0 | assert((StrKind == CaptureStrKind::CopyHelper || |
1779 | 0 | StrKind == CaptureStrKind::DisposeHelper) && |
1780 | 0 | "unexpected CaptureStrKind"); |
1781 | 0 | std::string Name = StrKind == CaptureStrKind::CopyHelper |
1782 | 0 | ? "__copy_helper_block_" |
1783 | 0 | : "__destroy_helper_block_"; |
1784 | 0 | if (CGM.getLangOpts().Exceptions) |
1785 | 0 | Name += "e"; |
1786 | 0 | if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) |
1787 | 0 | Name += "a"; |
1788 | 0 | Name += llvm::to_string(BlockAlignment.getQuantity()) + "_"; |
1789 | |
|
1790 | 0 | for (auto &Cap : Captures) { |
1791 | 0 | if (Cap.isConstantOrTrivial()) |
1792 | 0 | continue; |
1793 | 0 | Name += llvm::to_string(Cap.getOffset().getQuantity()); |
1794 | 0 | Name += getBlockCaptureStr(Cap, StrKind, BlockAlignment, CGM); |
1795 | 0 | } |
1796 | |
|
1797 | 0 | return Name; |
1798 | 0 | } |
1799 | | |
1800 | | static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind, |
1801 | | Address Field, QualType CaptureType, |
1802 | | BlockFieldFlags Flags, bool ForCopyHelper, |
1803 | 0 | VarDecl *Var, CodeGenFunction &CGF) { |
1804 | 0 | bool EHOnly = ForCopyHelper; |
1805 | |
|
1806 | 0 | switch (CaptureKind) { |
1807 | 0 | case BlockCaptureEntityKind::CXXRecord: |
1808 | 0 | case BlockCaptureEntityKind::ARCWeak: |
1809 | 0 | case BlockCaptureEntityKind::NonTrivialCStruct: |
1810 | 0 | case BlockCaptureEntityKind::ARCStrong: { |
1811 | 0 | if (CaptureType.isDestructedType() && |
1812 | 0 | (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) { |
1813 | 0 | CodeGenFunction::Destroyer *Destroyer = |
1814 | 0 | CaptureKind == BlockCaptureEntityKind::ARCStrong |
1815 | 0 | ? CodeGenFunction::destroyARCStrongImprecise |
1816 | 0 | : CGF.getDestroyer(CaptureType.isDestructedType()); |
1817 | 0 | CleanupKind Kind = |
1818 | 0 | EHOnly ? EHCleanup |
1819 | 0 | : CGF.getCleanupKind(CaptureType.isDestructedType()); |
1820 | 0 | CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup); |
1821 | 0 | } |
1822 | 0 | break; |
1823 | 0 | } |
1824 | 0 | case BlockCaptureEntityKind::BlockObject: { |
1825 | 0 | if (!EHOnly || CGF.getLangOpts().Exceptions) { |
1826 | 0 | CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup; |
1827 | | // Calls to _Block_object_dispose along the EH path in the copy helper |
1828 | | // function don't throw as newly-copied __block variables always have a |
1829 | | // reference count of 2. |
1830 | 0 | bool CanThrow = |
1831 | 0 | !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType); |
1832 | 0 | CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true, |
1833 | 0 | CanThrow); |
1834 | 0 | } |
1835 | 0 | break; |
1836 | 0 | } |
1837 | 0 | case BlockCaptureEntityKind::None: |
1838 | 0 | break; |
1839 | 0 | } |
1840 | 0 | } |
1841 | | |
1842 | | static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType, |
1843 | | llvm::Function *Fn, |
1844 | | const CGFunctionInfo &FI, |
1845 | 0 | CodeGenModule &CGM) { |
1846 | 0 | if (CapturesNonExternalType) { |
1847 | 0 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); |
1848 | 0 | } else { |
1849 | 0 | Fn->setVisibility(llvm::GlobalValue::HiddenVisibility); |
1850 | 0 | Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
1851 | 0 | CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false); |
1852 | 0 | CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn); |
1853 | 0 | } |
1854 | 0 | } |
1855 | | /// Generate the copy-helper function for a block closure object: |
1856 | | /// static void block_copy_helper(block_t *dst, block_t *src); |
1857 | | /// The runtime will have previously initialized 'dst' by doing a |
1858 | | /// bit-copy of 'src'. |
1859 | | /// |
1860 | | /// Note that this copies an entire block closure object to the heap; |
1861 | | /// it should not be confused with a 'byref copy helper', which moves |
1862 | | /// the contents of an individual __block variable to the heap. |
1863 | | llvm::Constant * |
1864 | 0 | CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) { |
1865 | 0 | std::string FuncName = getCopyDestroyHelperFuncName( |
1866 | 0 | blockInfo.SortedCaptures, blockInfo.BlockAlign, |
1867 | 0 | CaptureStrKind::CopyHelper, CGM); |
1868 | |
|
1869 | 0 | if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName)) |
1870 | 0 | return Func; |
1871 | | |
1872 | 0 | ASTContext &C = getContext(); |
1873 | |
|
1874 | 0 | QualType ReturnTy = C.VoidTy; |
1875 | |
|
1876 | 0 | FunctionArgList args; |
1877 | 0 | ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamKind::Other); |
1878 | 0 | args.push_back(&DstDecl); |
1879 | 0 | ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamKind::Other); |
1880 | 0 | args.push_back(&SrcDecl); |
1881 | |
|
1882 | 0 | const CGFunctionInfo &FI = |
1883 | 0 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args); |
1884 | | |
1885 | | // FIXME: it would be nice if these were mergeable with things with |
1886 | | // identical semantics. |
1887 | 0 | llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); |
1888 | |
|
1889 | 0 | llvm::Function *Fn = |
1890 | 0 | llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage, |
1891 | 0 | FuncName, &CGM.getModule()); |
1892 | 0 | if (CGM.supportsCOMDAT()) |
1893 | 0 | Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName)); |
1894 | |
|
1895 | 0 | SmallVector<QualType, 2> ArgTys; |
1896 | 0 | ArgTys.push_back(C.VoidPtrTy); |
1897 | 0 | ArgTys.push_back(C.VoidPtrTy); |
1898 | |
|
1899 | 0 | setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI, |
1900 | 0 | CGM); |
1901 | 0 | StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args); |
1902 | 0 | auto AL = ApplyDebugLocation::CreateArtificial(*this); |
1903 | |
|
1904 | 0 | Address src = GetAddrOfLocalVar(&SrcDecl); |
1905 | 0 | src = Address(Builder.CreateLoad(src), blockInfo.StructureType, |
1906 | 0 | blockInfo.BlockAlign); |
1907 | |
|
1908 | 0 | Address dst = GetAddrOfLocalVar(&DstDecl); |
1909 | 0 | dst = Address(Builder.CreateLoad(dst), blockInfo.StructureType, |
1910 | 0 | blockInfo.BlockAlign); |
1911 | |
|
1912 | 0 | for (auto &capture : blockInfo.SortedCaptures) { |
1913 | 0 | if (capture.isConstantOrTrivial()) |
1914 | 0 | continue; |
1915 | | |
1916 | 0 | const BlockDecl::Capture &CI = *capture.Cap; |
1917 | 0 | QualType captureType = CI.getVariable()->getType(); |
1918 | 0 | BlockFieldFlags flags = capture.CopyFlags; |
1919 | |
|
1920 | 0 | unsigned index = capture.getIndex(); |
1921 | 0 | Address srcField = Builder.CreateStructGEP(src, index); |
1922 | 0 | Address dstField = Builder.CreateStructGEP(dst, index); |
1923 | |
|
1924 | 0 | switch (capture.CopyKind) { |
1925 | 0 | case BlockCaptureEntityKind::CXXRecord: |
1926 | | // If there's an explicit copy expression, we do that. |
1927 | 0 | assert(CI.getCopyExpr() && "copy expression for variable is missing"); |
1928 | 0 | EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr()); |
1929 | 0 | break; |
1930 | 0 | case BlockCaptureEntityKind::ARCWeak: |
1931 | 0 | EmitARCCopyWeak(dstField, srcField); |
1932 | 0 | break; |
1933 | 0 | case BlockCaptureEntityKind::NonTrivialCStruct: { |
1934 | | // If this is a C struct that requires non-trivial copy construction, |
1935 | | // emit a call to its copy constructor. |
1936 | 0 | QualType varType = CI.getVariable()->getType(); |
1937 | 0 | callCStructCopyConstructor(MakeAddrLValue(dstField, varType), |
1938 | 0 | MakeAddrLValue(srcField, varType)); |
1939 | 0 | break; |
1940 | 0 | } |
1941 | 0 | case BlockCaptureEntityKind::ARCStrong: { |
1942 | 0 | llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src"); |
1943 | | // At -O0, store null into the destination field (so that the |
1944 | | // storeStrong doesn't over-release) and then call storeStrong. |
1945 | | // This is a workaround to not having an initStrong call. |
1946 | 0 | if (CGM.getCodeGenOpts().OptimizationLevel == 0) { |
1947 | 0 | auto *ty = cast<llvm::PointerType>(srcValue->getType()); |
1948 | 0 | llvm::Value *null = llvm::ConstantPointerNull::get(ty); |
1949 | 0 | Builder.CreateStore(null, dstField); |
1950 | 0 | EmitARCStoreStrongCall(dstField, srcValue, true); |
1951 | | |
1952 | | // With optimization enabled, take advantage of the fact that |
1953 | | // the blocks runtime guarantees a memcpy of the block data, and |
1954 | | // just emit a retain of the src field. |
1955 | 0 | } else { |
1956 | 0 | EmitARCRetainNonBlock(srcValue); |
1957 | | |
1958 | | // Unless EH cleanup is required, we don't need this anymore, so kill |
1959 | | // it. It's not quite worth the annoyance to avoid creating it in the |
1960 | | // first place. |
1961 | 0 | if (!needsEHCleanup(captureType.isDestructedType())) |
1962 | 0 | cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent(); |
1963 | 0 | } |
1964 | 0 | break; |
1965 | 0 | } |
1966 | 0 | case BlockCaptureEntityKind::BlockObject: { |
1967 | 0 | llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src"); |
1968 | 0 | llvm::Value *dstAddr = dstField.getPointer(); |
1969 | 0 | llvm::Value *args[] = { |
1970 | 0 | dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask()) |
1971 | 0 | }; |
1972 | |
|
1973 | 0 | if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow()) |
1974 | 0 | EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args); |
1975 | 0 | else |
1976 | 0 | EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args); |
1977 | 0 | break; |
1978 | 0 | } |
1979 | 0 | case BlockCaptureEntityKind::None: |
1980 | 0 | continue; |
1981 | 0 | } |
1982 | | |
1983 | | // Ensure that we destroy the copied object if an exception is thrown later |
1984 | | // in the helper function. |
1985 | 0 | pushCaptureCleanup(capture.CopyKind, dstField, captureType, flags, |
1986 | 0 | /*ForCopyHelper*/ true, CI.getVariable(), *this); |
1987 | 0 | } |
1988 | | |
1989 | 0 | FinishFunction(); |
1990 | |
|
1991 | 0 | return Fn; |
1992 | 0 | } |
1993 | | |
1994 | | static BlockFieldFlags |
1995 | | getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI, |
1996 | 0 | QualType T) { |
1997 | 0 | BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT; |
1998 | 0 | if (T->isBlockPointerType()) |
1999 | 0 | Flags = BLOCK_FIELD_IS_BLOCK; |
2000 | 0 | return Flags; |
2001 | 0 | } |
2002 | | |
2003 | | static std::pair<BlockCaptureEntityKind, BlockFieldFlags> |
2004 | | computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T, |
2005 | 0 | const LangOptions &LangOpts) { |
2006 | 0 | if (CI.isEscapingByref()) { |
2007 | 0 | BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF; |
2008 | 0 | if (T.isObjCGCWeak()) |
2009 | 0 | Flags |= BLOCK_FIELD_IS_WEAK; |
2010 | 0 | return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags); |
2011 | 0 | } |
2012 | | |
2013 | 0 | switch (T.isDestructedType()) { |
2014 | 0 | case QualType::DK_cxx_destructor: |
2015 | 0 | return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags()); |
2016 | 0 | case QualType::DK_objc_strong_lifetime: |
2017 | | // Use objc_storeStrong for __strong direct captures; the |
2018 | | // dynamic tools really like it when we do this. |
2019 | 0 | return std::make_pair(BlockCaptureEntityKind::ARCStrong, |
2020 | 0 | getBlockFieldFlagsForObjCObjectPointer(CI, T)); |
2021 | 0 | case QualType::DK_objc_weak_lifetime: |
2022 | | // Support __weak direct captures. |
2023 | 0 | return std::make_pair(BlockCaptureEntityKind::ARCWeak, |
2024 | 0 | getBlockFieldFlagsForObjCObjectPointer(CI, T)); |
2025 | 0 | case QualType::DK_nontrivial_c_struct: |
2026 | 0 | return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct, |
2027 | 0 | BlockFieldFlags()); |
2028 | 0 | case QualType::DK_none: { |
2029 | | // Non-ARC captures are strong, and we need to use _Block_object_dispose. |
2030 | | // But honor the inert __unsafe_unretained qualifier, which doesn't actually |
2031 | | // make it into the type system. |
2032 | 0 | if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() && |
2033 | 0 | !LangOpts.ObjCAutoRefCount && !T->isObjCInertUnsafeUnretainedType()) |
2034 | 0 | return std::make_pair(BlockCaptureEntityKind::BlockObject, |
2035 | 0 | getBlockFieldFlagsForObjCObjectPointer(CI, T)); |
2036 | | // Otherwise, we have nothing to do. |
2037 | 0 | return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags()); |
2038 | 0 | } |
2039 | 0 | } |
2040 | 0 | llvm_unreachable("after exhaustive DestructionKind switch"); |
2041 | 0 | } |
2042 | | |
2043 | | /// Generate the destroy-helper function for a block closure object: |
2044 | | /// static void block_destroy_helper(block_t *theBlock); |
2045 | | /// |
2046 | | /// Note that this destroys a heap-allocated block closure object; |
2047 | | /// it should not be confused with a 'byref destroy helper', which |
2048 | | /// destroys the heap-allocated contents of an individual __block |
2049 | | /// variable. |
2050 | | llvm::Constant * |
2051 | 0 | CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) { |
2052 | 0 | std::string FuncName = getCopyDestroyHelperFuncName( |
2053 | 0 | blockInfo.SortedCaptures, blockInfo.BlockAlign, |
2054 | 0 | CaptureStrKind::DisposeHelper, CGM); |
2055 | |
|
2056 | 0 | if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName)) |
2057 | 0 | return Func; |
2058 | | |
2059 | 0 | ASTContext &C = getContext(); |
2060 | |
|
2061 | 0 | QualType ReturnTy = C.VoidTy; |
2062 | |
|
2063 | 0 | FunctionArgList args; |
2064 | 0 | ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamKind::Other); |
2065 | 0 | args.push_back(&SrcDecl); |
2066 | |
|
2067 | 0 | const CGFunctionInfo &FI = |
2068 | 0 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args); |
2069 | | |
2070 | | // FIXME: We'd like to put these into a mergable by content, with |
2071 | | // internal linkage. |
2072 | 0 | llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); |
2073 | |
|
2074 | 0 | llvm::Function *Fn = |
2075 | 0 | llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage, |
2076 | 0 | FuncName, &CGM.getModule()); |
2077 | 0 | if (CGM.supportsCOMDAT()) |
2078 | 0 | Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName)); |
2079 | |
|
2080 | 0 | SmallVector<QualType, 1> ArgTys; |
2081 | 0 | ArgTys.push_back(C.VoidPtrTy); |
2082 | |
|
2083 | 0 | setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI, |
2084 | 0 | CGM); |
2085 | 0 | StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args); |
2086 | 0 | markAsIgnoreThreadCheckingAtRuntime(Fn); |
2087 | |
|
2088 | 0 | auto AL = ApplyDebugLocation::CreateArtificial(*this); |
2089 | |
|
2090 | 0 | Address src = GetAddrOfLocalVar(&SrcDecl); |
2091 | 0 | src = Address(Builder.CreateLoad(src), blockInfo.StructureType, |
2092 | 0 | blockInfo.BlockAlign); |
2093 | |
|
2094 | 0 | CodeGenFunction::RunCleanupsScope cleanups(*this); |
2095 | |
|
2096 | 0 | for (auto &capture : blockInfo.SortedCaptures) { |
2097 | 0 | if (capture.isConstantOrTrivial()) |
2098 | 0 | continue; |
2099 | | |
2100 | 0 | const BlockDecl::Capture &CI = *capture.Cap; |
2101 | 0 | BlockFieldFlags flags = capture.DisposeFlags; |
2102 | |
|
2103 | 0 | Address srcField = Builder.CreateStructGEP(src, capture.getIndex()); |
2104 | |
|
2105 | 0 | pushCaptureCleanup(capture.DisposeKind, srcField, |
2106 | 0 | CI.getVariable()->getType(), flags, |
2107 | 0 | /*ForCopyHelper*/ false, CI.getVariable(), *this); |
2108 | 0 | } |
2109 | |
|
2110 | 0 | cleanups.ForceCleanup(); |
2111 | |
|
2112 | 0 | FinishFunction(); |
2113 | |
|
2114 | 0 | return Fn; |
2115 | 0 | } |
2116 | | |
2117 | | namespace { |
2118 | | |
2119 | | /// Emits the copy/dispose helper functions for a __block object of id type. |
2120 | | class ObjectByrefHelpers final : public BlockByrefHelpers { |
2121 | | BlockFieldFlags Flags; |
2122 | | |
2123 | | public: |
2124 | | ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags) |
2125 | 0 | : BlockByrefHelpers(alignment), Flags(flags) {} |
2126 | | |
2127 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2128 | 0 | Address srcField) override { |
2129 | 0 | destField = destField.withElementType(CGF.Int8Ty); |
2130 | |
|
2131 | 0 | srcField = srcField.withElementType(CGF.Int8PtrTy); |
2132 | 0 | llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField); |
2133 | |
|
2134 | 0 | unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask(); |
2135 | |
|
2136 | 0 | llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags); |
2137 | 0 | llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign(); |
2138 | |
|
2139 | 0 | llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal }; |
2140 | 0 | CGF.EmitNounwindRuntimeCall(fn, args); |
2141 | 0 | } |
2142 | | |
2143 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2144 | 0 | field = field.withElementType(CGF.Int8PtrTy); |
2145 | 0 | llvm::Value *value = CGF.Builder.CreateLoad(field); |
2146 | |
|
2147 | 0 | CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false); |
2148 | 0 | } |
2149 | | |
2150 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2151 | 0 | id.AddInteger(Flags.getBitMask()); |
2152 | 0 | } |
2153 | | }; |
2154 | | |
2155 | | /// Emits the copy/dispose helpers for an ARC __block __weak variable. |
2156 | | class ARCWeakByrefHelpers final : public BlockByrefHelpers { |
2157 | | public: |
2158 | 0 | ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {} |
2159 | | |
2160 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2161 | 0 | Address srcField) override { |
2162 | 0 | CGF.EmitARCMoveWeak(destField, srcField); |
2163 | 0 | } |
2164 | | |
2165 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2166 | 0 | CGF.EmitARCDestroyWeak(field); |
2167 | 0 | } |
2168 | | |
2169 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2170 | | // 0 is distinguishable from all pointers and byref flags |
2171 | 0 | id.AddInteger(0); |
2172 | 0 | } |
2173 | | }; |
2174 | | |
2175 | | /// Emits the copy/dispose helpers for an ARC __block __strong variable |
2176 | | /// that's not of block-pointer type. |
2177 | | class ARCStrongByrefHelpers final : public BlockByrefHelpers { |
2178 | | public: |
2179 | 0 | ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {} |
2180 | | |
2181 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2182 | 0 | Address srcField) override { |
2183 | | // Do a "move" by copying the value and then zeroing out the old |
2184 | | // variable. |
2185 | |
|
2186 | 0 | llvm::Value *value = CGF.Builder.CreateLoad(srcField); |
2187 | |
|
2188 | 0 | llvm::Value *null = |
2189 | 0 | llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType())); |
2190 | |
|
2191 | 0 | if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) { |
2192 | 0 | CGF.Builder.CreateStore(null, destField); |
2193 | 0 | CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true); |
2194 | 0 | CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true); |
2195 | 0 | return; |
2196 | 0 | } |
2197 | 0 | CGF.Builder.CreateStore(value, destField); |
2198 | 0 | CGF.Builder.CreateStore(null, srcField); |
2199 | 0 | } |
2200 | | |
2201 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2202 | 0 | CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime); |
2203 | 0 | } |
2204 | | |
2205 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2206 | | // 1 is distinguishable from all pointers and byref flags |
2207 | 0 | id.AddInteger(1); |
2208 | 0 | } |
2209 | | }; |
2210 | | |
2211 | | /// Emits the copy/dispose helpers for an ARC __block __strong |
2212 | | /// variable that's of block-pointer type. |
2213 | | class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers { |
2214 | | public: |
2215 | | ARCStrongBlockByrefHelpers(CharUnits alignment) |
2216 | 0 | : BlockByrefHelpers(alignment) {} |
2217 | | |
2218 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2219 | 0 | Address srcField) override { |
2220 | | // Do the copy with objc_retainBlock; that's all that |
2221 | | // _Block_object_assign would do anyway, and we'd have to pass the |
2222 | | // right arguments to make sure it doesn't get no-op'ed. |
2223 | 0 | llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField); |
2224 | 0 | llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true); |
2225 | 0 | CGF.Builder.CreateStore(copy, destField); |
2226 | 0 | } |
2227 | | |
2228 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2229 | 0 | CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime); |
2230 | 0 | } |
2231 | | |
2232 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2233 | | // 2 is distinguishable from all pointers and byref flags |
2234 | 0 | id.AddInteger(2); |
2235 | 0 | } |
2236 | | }; |
2237 | | |
2238 | | /// Emits the copy/dispose helpers for a __block variable with a |
2239 | | /// nontrivial copy constructor or destructor. |
2240 | | class CXXByrefHelpers final : public BlockByrefHelpers { |
2241 | | QualType VarType; |
2242 | | const Expr *CopyExpr; |
2243 | | |
2244 | | public: |
2245 | | CXXByrefHelpers(CharUnits alignment, QualType type, |
2246 | | const Expr *copyExpr) |
2247 | 0 | : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {} |
2248 | | |
2249 | 0 | bool needsCopy() const override { return CopyExpr != nullptr; } |
2250 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2251 | 0 | Address srcField) override { |
2252 | 0 | if (!CopyExpr) return; |
2253 | 0 | CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr); |
2254 | 0 | } |
2255 | | |
2256 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2257 | 0 | EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin(); |
2258 | 0 | CGF.PushDestructorCleanup(VarType, field); |
2259 | 0 | CGF.PopCleanupBlocks(cleanupDepth); |
2260 | 0 | } |
2261 | | |
2262 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2263 | 0 | id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr()); |
2264 | 0 | } |
2265 | | }; |
2266 | | |
2267 | | /// Emits the copy/dispose helpers for a __block variable that is a non-trivial |
2268 | | /// C struct. |
2269 | | class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers { |
2270 | | QualType VarType; |
2271 | | |
2272 | | public: |
2273 | | NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type) |
2274 | 0 | : BlockByrefHelpers(alignment), VarType(type) {} |
2275 | | |
2276 | | void emitCopy(CodeGenFunction &CGF, Address destField, |
2277 | 0 | Address srcField) override { |
2278 | 0 | CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType), |
2279 | 0 | CGF.MakeAddrLValue(srcField, VarType)); |
2280 | 0 | } |
2281 | | |
2282 | 0 | bool needsDispose() const override { |
2283 | 0 | return VarType.isDestructedType(); |
2284 | 0 | } |
2285 | | |
2286 | 0 | void emitDispose(CodeGenFunction &CGF, Address field) override { |
2287 | 0 | EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin(); |
2288 | 0 | CGF.pushDestroy(VarType.isDestructedType(), field, VarType); |
2289 | 0 | CGF.PopCleanupBlocks(cleanupDepth); |
2290 | 0 | } |
2291 | | |
2292 | 0 | void profileImpl(llvm::FoldingSetNodeID &id) const override { |
2293 | 0 | id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr()); |
2294 | 0 | } |
2295 | | }; |
2296 | | } // end anonymous namespace |
2297 | | |
2298 | | static llvm::Constant * |
2299 | | generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo, |
2300 | 0 | BlockByrefHelpers &generator) { |
2301 | 0 | ASTContext &Context = CGF.getContext(); |
2302 | |
|
2303 | 0 | QualType ReturnTy = Context.VoidTy; |
2304 | |
|
2305 | 0 | FunctionArgList args; |
2306 | 0 | ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamKind::Other); |
2307 | 0 | args.push_back(&Dst); |
2308 | |
|
2309 | 0 | ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamKind::Other); |
2310 | 0 | args.push_back(&Src); |
2311 | |
|
2312 | 0 | const CGFunctionInfo &FI = |
2313 | 0 | CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args); |
2314 | |
|
2315 | 0 | llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI); |
2316 | | |
2317 | | // FIXME: We'd like to put these into a mergable by content, with |
2318 | | // internal linkage. |
2319 | 0 | llvm::Function *Fn = |
2320 | 0 | llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, |
2321 | 0 | "__Block_byref_object_copy_", &CGF.CGM.getModule()); |
2322 | |
|
2323 | 0 | SmallVector<QualType, 2> ArgTys; |
2324 | 0 | ArgTys.push_back(Context.VoidPtrTy); |
2325 | 0 | ArgTys.push_back(Context.VoidPtrTy); |
2326 | |
|
2327 | 0 | CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); |
2328 | |
|
2329 | 0 | CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args); |
2330 | | // Create a scope with an artificial location for the body of this function. |
2331 | 0 | auto AL = ApplyDebugLocation::CreateArtificial(CGF); |
2332 | |
|
2333 | 0 | if (generator.needsCopy()) { |
2334 | | // dst->x |
2335 | 0 | Address destField = CGF.GetAddrOfLocalVar(&Dst); |
2336 | 0 | destField = Address(CGF.Builder.CreateLoad(destField), byrefInfo.Type, |
2337 | 0 | byrefInfo.ByrefAlignment); |
2338 | 0 | destField = |
2339 | 0 | CGF.emitBlockByrefAddress(destField, byrefInfo, false, "dest-object"); |
2340 | | |
2341 | | // src->x |
2342 | 0 | Address srcField = CGF.GetAddrOfLocalVar(&Src); |
2343 | 0 | srcField = Address(CGF.Builder.CreateLoad(srcField), byrefInfo.Type, |
2344 | 0 | byrefInfo.ByrefAlignment); |
2345 | 0 | srcField = |
2346 | 0 | CGF.emitBlockByrefAddress(srcField, byrefInfo, false, "src-object"); |
2347 | |
|
2348 | 0 | generator.emitCopy(CGF, destField, srcField); |
2349 | 0 | } |
2350 | |
|
2351 | 0 | CGF.FinishFunction(); |
2352 | |
|
2353 | 0 | return Fn; |
2354 | 0 | } |
2355 | | |
2356 | | /// Build the copy helper for a __block variable. |
2357 | | static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM, |
2358 | | const BlockByrefInfo &byrefInfo, |
2359 | 0 | BlockByrefHelpers &generator) { |
2360 | 0 | CodeGenFunction CGF(CGM); |
2361 | 0 | return generateByrefCopyHelper(CGF, byrefInfo, generator); |
2362 | 0 | } |
2363 | | |
2364 | | /// Generate code for a __block variable's dispose helper. |
2365 | | static llvm::Constant * |
2366 | | generateByrefDisposeHelper(CodeGenFunction &CGF, |
2367 | | const BlockByrefInfo &byrefInfo, |
2368 | 0 | BlockByrefHelpers &generator) { |
2369 | 0 | ASTContext &Context = CGF.getContext(); |
2370 | 0 | QualType R = Context.VoidTy; |
2371 | |
|
2372 | 0 | FunctionArgList args; |
2373 | 0 | ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy, |
2374 | 0 | ImplicitParamKind::Other); |
2375 | 0 | args.push_back(&Src); |
2376 | |
|
2377 | 0 | const CGFunctionInfo &FI = |
2378 | 0 | CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args); |
2379 | |
|
2380 | 0 | llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI); |
2381 | | |
2382 | | // FIXME: We'd like to put these into a mergable by content, with |
2383 | | // internal linkage. |
2384 | 0 | llvm::Function *Fn = |
2385 | 0 | llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, |
2386 | 0 | "__Block_byref_object_dispose_", |
2387 | 0 | &CGF.CGM.getModule()); |
2388 | |
|
2389 | 0 | SmallVector<QualType, 1> ArgTys; |
2390 | 0 | ArgTys.push_back(Context.VoidPtrTy); |
2391 | |
|
2392 | 0 | CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); |
2393 | |
|
2394 | 0 | CGF.StartFunction(GlobalDecl(), R, Fn, FI, args); |
2395 | | // Create a scope with an artificial location for the body of this function. |
2396 | 0 | auto AL = ApplyDebugLocation::CreateArtificial(CGF); |
2397 | |
|
2398 | 0 | if (generator.needsDispose()) { |
2399 | 0 | Address addr = CGF.GetAddrOfLocalVar(&Src); |
2400 | 0 | addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.Type, |
2401 | 0 | byrefInfo.ByrefAlignment); |
2402 | 0 | addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object"); |
2403 | |
|
2404 | 0 | generator.emitDispose(CGF, addr); |
2405 | 0 | } |
2406 | |
|
2407 | 0 | CGF.FinishFunction(); |
2408 | |
|
2409 | 0 | return Fn; |
2410 | 0 | } |
2411 | | |
2412 | | /// Build the dispose helper for a __block variable. |
2413 | | static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM, |
2414 | | const BlockByrefInfo &byrefInfo, |
2415 | 0 | BlockByrefHelpers &generator) { |
2416 | 0 | CodeGenFunction CGF(CGM); |
2417 | 0 | return generateByrefDisposeHelper(CGF, byrefInfo, generator); |
2418 | 0 | } |
2419 | | |
2420 | | /// Lazily build the copy and dispose helpers for a __block variable |
2421 | | /// with the given information. |
2422 | | template <class T> |
2423 | | static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo, |
2424 | 0 | T &&generator) { |
2425 | 0 | llvm::FoldingSetNodeID id; |
2426 | 0 | generator.Profile(id); |
2427 | |
|
2428 | 0 | void *insertPos; |
2429 | 0 | BlockByrefHelpers *node |
2430 | 0 | = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos); |
2431 | 0 | if (node) return static_cast<T*>(node); |
2432 | | |
2433 | 0 | generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator); |
2434 | 0 | generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator); |
2435 | |
|
2436 | 0 | T *copy = new (CGM.getContext()) T(std::forward<T>(generator)); |
2437 | 0 | CGM.ByrefHelpersCache.InsertNode(copy, insertPos); |
2438 | 0 | return copy; |
2439 | 0 | } Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::CXXByrefHelpers* buildByrefHelpers<(anonymous namespace)::CXXByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::CXXByrefHelpers&&) Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::NonTrivialCStructByrefHelpers* buildByrefHelpers<(anonymous namespace)::NonTrivialCStructByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::NonTrivialCStructByrefHelpers&&) Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::ARCWeakByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCWeakByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCWeakByrefHelpers&&) Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::ARCStrongBlockByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCStrongBlockByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCStrongBlockByrefHelpers&&) Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::ARCStrongByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCStrongByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCStrongByrefHelpers&&) Unexecuted instantiation: CGBlocks.cpp:(anonymous namespace)::ObjectByrefHelpers* buildByrefHelpers<(anonymous namespace)::ObjectByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ObjectByrefHelpers&&) |
2440 | | |
2441 | | /// Build the copy and dispose helpers for the given __block variable |
2442 | | /// emission. Places the helpers in the global cache. Returns null |
2443 | | /// if no helpers are required. |
2444 | | BlockByrefHelpers * |
2445 | | CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType, |
2446 | 0 | const AutoVarEmission &emission) { |
2447 | 0 | const VarDecl &var = *emission.Variable; |
2448 | 0 | assert(var.isEscapingByref() && |
2449 | 0 | "only escaping __block variables need byref helpers"); |
2450 | | |
2451 | 0 | QualType type = var.getType(); |
2452 | |
|
2453 | 0 | auto &byrefInfo = getBlockByrefInfo(&var); |
2454 | | |
2455 | | // The alignment we care about for the purposes of uniquing byref |
2456 | | // helpers is the alignment of the actual byref value field. |
2457 | 0 | CharUnits valueAlignment = |
2458 | 0 | byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset); |
2459 | |
|
2460 | 0 | if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) { |
2461 | 0 | const Expr *copyExpr = |
2462 | 0 | CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr(); |
2463 | 0 | if (!copyExpr && record->hasTrivialDestructor()) return nullptr; |
2464 | | |
2465 | 0 | return ::buildByrefHelpers( |
2466 | 0 | CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr)); |
2467 | 0 | } |
2468 | | |
2469 | | // If type is a non-trivial C struct type that is non-trivial to |
2470 | | // destructly move or destroy, build the copy and dispose helpers. |
2471 | 0 | if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct || |
2472 | 0 | type.isDestructedType() == QualType::DK_nontrivial_c_struct) |
2473 | 0 | return ::buildByrefHelpers( |
2474 | 0 | CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type)); |
2475 | | |
2476 | | // Otherwise, if we don't have a retainable type, there's nothing to do. |
2477 | | // that the runtime does extra copies. |
2478 | 0 | if (!type->isObjCRetainableType()) return nullptr; |
2479 | | |
2480 | 0 | Qualifiers qs = type.getQualifiers(); |
2481 | | |
2482 | | // If we have lifetime, that dominates. |
2483 | 0 | if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { |
2484 | 0 | switch (lifetime) { |
2485 | 0 | case Qualifiers::OCL_None: llvm_unreachable("impossible"); |
2486 | | |
2487 | | // These are just bits as far as the runtime is concerned. |
2488 | 0 | case Qualifiers::OCL_ExplicitNone: |
2489 | 0 | case Qualifiers::OCL_Autoreleasing: |
2490 | 0 | return nullptr; |
2491 | | |
2492 | | // Tell the runtime that this is ARC __weak, called by the |
2493 | | // byref routines. |
2494 | 0 | case Qualifiers::OCL_Weak: |
2495 | 0 | return ::buildByrefHelpers(CGM, byrefInfo, |
2496 | 0 | ARCWeakByrefHelpers(valueAlignment)); |
2497 | | |
2498 | | // ARC __strong __block variables need to be retained. |
2499 | 0 | case Qualifiers::OCL_Strong: |
2500 | | // Block pointers need to be copied, and there's no direct |
2501 | | // transfer possible. |
2502 | 0 | if (type->isBlockPointerType()) { |
2503 | 0 | return ::buildByrefHelpers(CGM, byrefInfo, |
2504 | 0 | ARCStrongBlockByrefHelpers(valueAlignment)); |
2505 | | |
2506 | | // Otherwise, we transfer ownership of the retain from the stack |
2507 | | // to the heap. |
2508 | 0 | } else { |
2509 | 0 | return ::buildByrefHelpers(CGM, byrefInfo, |
2510 | 0 | ARCStrongByrefHelpers(valueAlignment)); |
2511 | 0 | } |
2512 | 0 | } |
2513 | 0 | llvm_unreachable("fell out of lifetime switch!"); |
2514 | 0 | } |
2515 | | |
2516 | 0 | BlockFieldFlags flags; |
2517 | 0 | if (type->isBlockPointerType()) { |
2518 | 0 | flags |= BLOCK_FIELD_IS_BLOCK; |
2519 | 0 | } else if (CGM.getContext().isObjCNSObjectType(type) || |
2520 | 0 | type->isObjCObjectPointerType()) { |
2521 | 0 | flags |= BLOCK_FIELD_IS_OBJECT; |
2522 | 0 | } else { |
2523 | 0 | return nullptr; |
2524 | 0 | } |
2525 | | |
2526 | 0 | if (type.isObjCGCWeak()) |
2527 | 0 | flags |= BLOCK_FIELD_IS_WEAK; |
2528 | |
|
2529 | 0 | return ::buildByrefHelpers(CGM, byrefInfo, |
2530 | 0 | ObjectByrefHelpers(valueAlignment, flags)); |
2531 | 0 | } |
2532 | | |
2533 | | Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr, |
2534 | | const VarDecl *var, |
2535 | 0 | bool followForward) { |
2536 | 0 | auto &info = getBlockByrefInfo(var); |
2537 | 0 | return emitBlockByrefAddress(baseAddr, info, followForward, var->getName()); |
2538 | 0 | } |
2539 | | |
2540 | | Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr, |
2541 | | const BlockByrefInfo &info, |
2542 | | bool followForward, |
2543 | 0 | const llvm::Twine &name) { |
2544 | | // Chase the forwarding address if requested. |
2545 | 0 | if (followForward) { |
2546 | 0 | Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding"); |
2547 | 0 | baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.Type, |
2548 | 0 | info.ByrefAlignment); |
2549 | 0 | } |
2550 | |
|
2551 | 0 | return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name); |
2552 | 0 | } |
2553 | | |
2554 | | /// BuildByrefInfo - This routine changes a __block variable declared as T x |
2555 | | /// into: |
2556 | | /// |
2557 | | /// struct { |
2558 | | /// void *__isa; |
2559 | | /// void *__forwarding; |
2560 | | /// int32_t __flags; |
2561 | | /// int32_t __size; |
2562 | | /// void *__copy_helper; // only if needed |
2563 | | /// void *__destroy_helper; // only if needed |
2564 | | /// void *__byref_variable_layout;// only if needed |
2565 | | /// char padding[X]; // only if needed |
2566 | | /// T x; |
2567 | | /// } x |
2568 | | /// |
2569 | 0 | const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) { |
2570 | 0 | auto it = BlockByrefInfos.find(D); |
2571 | 0 | if (it != BlockByrefInfos.end()) |
2572 | 0 | return it->second; |
2573 | | |
2574 | 0 | llvm::StructType *byrefType = |
2575 | 0 | llvm::StructType::create(getLLVMContext(), |
2576 | 0 | "struct.__block_byref_" + D->getNameAsString()); |
2577 | |
|
2578 | 0 | QualType Ty = D->getType(); |
2579 | |
|
2580 | 0 | CharUnits size; |
2581 | 0 | SmallVector<llvm::Type *, 8> types; |
2582 | | |
2583 | | // void *__isa; |
2584 | 0 | types.push_back(VoidPtrTy); |
2585 | 0 | size += getPointerSize(); |
2586 | | |
2587 | | // void *__forwarding; |
2588 | 0 | types.push_back(VoidPtrTy); |
2589 | 0 | size += getPointerSize(); |
2590 | | |
2591 | | // int32_t __flags; |
2592 | 0 | types.push_back(Int32Ty); |
2593 | 0 | size += CharUnits::fromQuantity(4); |
2594 | | |
2595 | | // int32_t __size; |
2596 | 0 | types.push_back(Int32Ty); |
2597 | 0 | size += CharUnits::fromQuantity(4); |
2598 | | |
2599 | | // Note that this must match *exactly* the logic in buildByrefHelpers. |
2600 | 0 | bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D); |
2601 | 0 | if (hasCopyAndDispose) { |
2602 | | /// void *__copy_helper; |
2603 | 0 | types.push_back(VoidPtrTy); |
2604 | 0 | size += getPointerSize(); |
2605 | | |
2606 | | /// void *__destroy_helper; |
2607 | 0 | types.push_back(VoidPtrTy); |
2608 | 0 | size += getPointerSize(); |
2609 | 0 | } |
2610 | |
|
2611 | 0 | bool HasByrefExtendedLayout = false; |
2612 | 0 | Qualifiers::ObjCLifetime Lifetime = Qualifiers::OCL_None; |
2613 | 0 | if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) && |
2614 | 0 | HasByrefExtendedLayout) { |
2615 | | /// void *__byref_variable_layout; |
2616 | 0 | types.push_back(VoidPtrTy); |
2617 | 0 | size += CharUnits::fromQuantity(PointerSizeInBytes); |
2618 | 0 | } |
2619 | | |
2620 | | // T x; |
2621 | 0 | llvm::Type *varTy = ConvertTypeForMem(Ty); |
2622 | |
|
2623 | 0 | bool packed = false; |
2624 | 0 | CharUnits varAlign = getContext().getDeclAlign(D); |
2625 | 0 | CharUnits varOffset = size.alignTo(varAlign); |
2626 | | |
2627 | | // We may have to insert padding. |
2628 | 0 | if (varOffset != size) { |
2629 | 0 | llvm::Type *paddingTy = |
2630 | 0 | llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity()); |
2631 | |
|
2632 | 0 | types.push_back(paddingTy); |
2633 | 0 | size = varOffset; |
2634 | | |
2635 | | // Conversely, we might have to prevent LLVM from inserting padding. |
2636 | 0 | } else if (CGM.getDataLayout().getABITypeAlign(varTy) > |
2637 | 0 | uint64_t(varAlign.getQuantity())) { |
2638 | 0 | packed = true; |
2639 | 0 | } |
2640 | 0 | types.push_back(varTy); |
2641 | |
|
2642 | 0 | byrefType->setBody(types, packed); |
2643 | |
|
2644 | 0 | BlockByrefInfo info; |
2645 | 0 | info.Type = byrefType; |
2646 | 0 | info.FieldIndex = types.size() - 1; |
2647 | 0 | info.FieldOffset = varOffset; |
2648 | 0 | info.ByrefAlignment = std::max(varAlign, getPointerAlign()); |
2649 | |
|
2650 | 0 | auto pair = BlockByrefInfos.insert({D, info}); |
2651 | 0 | assert(pair.second && "info was inserted recursively?"); |
2652 | 0 | return pair.first->second; |
2653 | 0 | } |
2654 | | |
2655 | | /// Initialize the structural components of a __block variable, i.e. |
2656 | | /// everything but the actual object. |
2657 | 0 | void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) { |
2658 | | // Find the address of the local. |
2659 | 0 | Address addr = emission.Addr; |
2660 | | |
2661 | | // That's an alloca of the byref structure type. |
2662 | 0 | llvm::StructType *byrefType = cast<llvm::StructType>(addr.getElementType()); |
2663 | |
|
2664 | 0 | unsigned nextHeaderIndex = 0; |
2665 | 0 | CharUnits nextHeaderOffset; |
2666 | 0 | auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize, |
2667 | 0 | const Twine &name) { |
2668 | 0 | auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name); |
2669 | 0 | Builder.CreateStore(value, fieldAddr); |
2670 | |
|
2671 | 0 | nextHeaderIndex++; |
2672 | 0 | nextHeaderOffset += fieldSize; |
2673 | 0 | }; |
2674 | | |
2675 | | // Build the byref helpers if necessary. This is null if we don't need any. |
2676 | 0 | BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission); |
2677 | |
|
2678 | 0 | const VarDecl &D = *emission.Variable; |
2679 | 0 | QualType type = D.getType(); |
2680 | |
|
2681 | 0 | bool HasByrefExtendedLayout = false; |
2682 | 0 | Qualifiers::ObjCLifetime ByrefLifetime = Qualifiers::OCL_None; |
2683 | 0 | bool ByRefHasLifetime = |
2684 | 0 | getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout); |
2685 | |
|
2686 | 0 | llvm::Value *V; |
2687 | | |
2688 | | // Initialize the 'isa', which is just 0 or 1. |
2689 | 0 | int isa = 0; |
2690 | 0 | if (type.isObjCGCWeak()) |
2691 | 0 | isa = 1; |
2692 | 0 | V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa"); |
2693 | 0 | storeHeaderField(V, getPointerSize(), "byref.isa"); |
2694 | | |
2695 | | // Store the address of the variable into its own forwarding pointer. |
2696 | 0 | storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding"); |
2697 | | |
2698 | | // Blocks ABI: |
2699 | | // c) the flags field is set to either 0 if no helper functions are |
2700 | | // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are, |
2701 | 0 | BlockFlags flags; |
2702 | 0 | if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE; |
2703 | 0 | if (ByRefHasLifetime) { |
2704 | 0 | if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED; |
2705 | 0 | else switch (ByrefLifetime) { |
2706 | 0 | case Qualifiers::OCL_Strong: |
2707 | 0 | flags |= BLOCK_BYREF_LAYOUT_STRONG; |
2708 | 0 | break; |
2709 | 0 | case Qualifiers::OCL_Weak: |
2710 | 0 | flags |= BLOCK_BYREF_LAYOUT_WEAK; |
2711 | 0 | break; |
2712 | 0 | case Qualifiers::OCL_ExplicitNone: |
2713 | 0 | flags |= BLOCK_BYREF_LAYOUT_UNRETAINED; |
2714 | 0 | break; |
2715 | 0 | case Qualifiers::OCL_None: |
2716 | 0 | if (!type->isObjCObjectPointerType() && !type->isBlockPointerType()) |
2717 | 0 | flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT; |
2718 | 0 | break; |
2719 | 0 | default: |
2720 | 0 | break; |
2721 | 0 | } |
2722 | 0 | if (CGM.getLangOpts().ObjCGCBitmapPrint) { |
2723 | 0 | printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask()); |
2724 | 0 | if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE) |
2725 | 0 | printf(" BLOCK_BYREF_HAS_COPY_DISPOSE"); |
2726 | 0 | if (flags & BLOCK_BYREF_LAYOUT_MASK) { |
2727 | 0 | BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK); |
2728 | 0 | if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED) |
2729 | 0 | printf(" BLOCK_BYREF_LAYOUT_EXTENDED"); |
2730 | 0 | if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG) |
2731 | 0 | printf(" BLOCK_BYREF_LAYOUT_STRONG"); |
2732 | 0 | if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK) |
2733 | 0 | printf(" BLOCK_BYREF_LAYOUT_WEAK"); |
2734 | 0 | if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED) |
2735 | 0 | printf(" BLOCK_BYREF_LAYOUT_UNRETAINED"); |
2736 | 0 | if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT) |
2737 | 0 | printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT"); |
2738 | 0 | } |
2739 | 0 | printf("\n"); |
2740 | 0 | } |
2741 | 0 | } |
2742 | 0 | storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()), |
2743 | 0 | getIntSize(), "byref.flags"); |
2744 | |
|
2745 | 0 | CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType); |
2746 | 0 | V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity()); |
2747 | 0 | storeHeaderField(V, getIntSize(), "byref.size"); |
2748 | |
|
2749 | 0 | if (helpers) { |
2750 | 0 | storeHeaderField(helpers->CopyHelper, getPointerSize(), |
2751 | 0 | "byref.copyHelper"); |
2752 | 0 | storeHeaderField(helpers->DisposeHelper, getPointerSize(), |
2753 | 0 | "byref.disposeHelper"); |
2754 | 0 | } |
2755 | |
|
2756 | 0 | if (ByRefHasLifetime && HasByrefExtendedLayout) { |
2757 | 0 | auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type); |
2758 | 0 | storeHeaderField(layoutInfo, getPointerSize(), "byref.layout"); |
2759 | 0 | } |
2760 | 0 | } |
2761 | | |
2762 | | void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags, |
2763 | 0 | bool CanThrow) { |
2764 | 0 | llvm::FunctionCallee F = CGM.getBlockObjectDispose(); |
2765 | 0 | llvm::Value *args[] = {V, |
2766 | 0 | llvm::ConstantInt::get(Int32Ty, flags.getBitMask())}; |
2767 | |
|
2768 | 0 | if (CanThrow) |
2769 | 0 | EmitRuntimeCallOrInvoke(F, args); |
2770 | 0 | else |
2771 | 0 | EmitNounwindRuntimeCall(F, args); |
2772 | 0 | } |
2773 | | |
2774 | | void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr, |
2775 | | BlockFieldFlags Flags, |
2776 | 0 | bool LoadBlockVarAddr, bool CanThrow) { |
2777 | 0 | EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr, |
2778 | 0 | CanThrow); |
2779 | 0 | } |
2780 | | |
2781 | | /// Adjust the declaration of something from the blocks API. |
2782 | | static void configureBlocksRuntimeObject(CodeGenModule &CGM, |
2783 | 0 | llvm::Constant *C) { |
2784 | 0 | auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts()); |
2785 | |
|
2786 | 0 | if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) { |
2787 | 0 | IdentifierInfo &II = CGM.getContext().Idents.get(C->getName()); |
2788 | 0 | TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); |
2789 | 0 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); |
2790 | |
|
2791 | 0 | assert((isa<llvm::Function>(C->stripPointerCasts()) || |
2792 | 0 | isa<llvm::GlobalVariable>(C->stripPointerCasts())) && |
2793 | 0 | "expected Function or GlobalVariable"); |
2794 | | |
2795 | 0 | const NamedDecl *ND = nullptr; |
2796 | 0 | for (const auto *Result : DC->lookup(&II)) |
2797 | 0 | if ((ND = dyn_cast<FunctionDecl>(Result)) || |
2798 | 0 | (ND = dyn_cast<VarDecl>(Result))) |
2799 | 0 | break; |
2800 | | |
2801 | | // TODO: support static blocks runtime |
2802 | 0 | if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) { |
2803 | 0 | GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
2804 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
2805 | 0 | } else { |
2806 | 0 | GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); |
2807 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
2808 | 0 | } |
2809 | 0 | } |
2810 | | |
2811 | 0 | if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() && |
2812 | 0 | GV->hasExternalLinkage()) |
2813 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); |
2814 | |
|
2815 | 0 | CGM.setDSOLocal(GV); |
2816 | 0 | } |
2817 | | |
2818 | 0 | llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() { |
2819 | 0 | if (BlockObjectDispose) |
2820 | 0 | return BlockObjectDispose; |
2821 | | |
2822 | 0 | llvm::Type *args[] = { Int8PtrTy, Int32Ty }; |
2823 | 0 | llvm::FunctionType *fty |
2824 | 0 | = llvm::FunctionType::get(VoidTy, args, false); |
2825 | 0 | BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose"); |
2826 | 0 | configureBlocksRuntimeObject( |
2827 | 0 | *this, cast<llvm::Constant>(BlockObjectDispose.getCallee())); |
2828 | 0 | return BlockObjectDispose; |
2829 | 0 | } |
2830 | | |
2831 | 0 | llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() { |
2832 | 0 | if (BlockObjectAssign) |
2833 | 0 | return BlockObjectAssign; |
2834 | | |
2835 | 0 | llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty }; |
2836 | 0 | llvm::FunctionType *fty |
2837 | 0 | = llvm::FunctionType::get(VoidTy, args, false); |
2838 | 0 | BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign"); |
2839 | 0 | configureBlocksRuntimeObject( |
2840 | 0 | *this, cast<llvm::Constant>(BlockObjectAssign.getCallee())); |
2841 | 0 | return BlockObjectAssign; |
2842 | 0 | } |
2843 | | |
2844 | 0 | llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() { |
2845 | 0 | if (NSConcreteGlobalBlock) |
2846 | 0 | return NSConcreteGlobalBlock; |
2847 | | |
2848 | 0 | NSConcreteGlobalBlock = GetOrCreateLLVMGlobal( |
2849 | 0 | "_NSConcreteGlobalBlock", Int8PtrTy, LangAS::Default, nullptr); |
2850 | 0 | configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock); |
2851 | 0 | return NSConcreteGlobalBlock; |
2852 | 0 | } |
2853 | | |
2854 | 0 | llvm::Constant *CodeGenModule::getNSConcreteStackBlock() { |
2855 | 0 | if (NSConcreteStackBlock) |
2856 | 0 | return NSConcreteStackBlock; |
2857 | | |
2858 | 0 | NSConcreteStackBlock = GetOrCreateLLVMGlobal( |
2859 | 0 | "_NSConcreteStackBlock", Int8PtrTy, LangAS::Default, nullptr); |
2860 | 0 | configureBlocksRuntimeObject(*this, NSConcreteStackBlock); |
2861 | 0 | return NSConcreteStackBlock; |
2862 | 0 | } |