xref: /aosp_15_r20/external/clang/lib/CodeGen/CGBlocks.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This contains code to emit blocks.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "CGBlocks.h"
15*67e74705SXin Li #include "CGDebugInfo.h"
16*67e74705SXin Li #include "CGObjCRuntime.h"
17*67e74705SXin Li #include "CodeGenFunction.h"
18*67e74705SXin Li #include "CodeGenModule.h"
19*67e74705SXin Li #include "clang/AST/DeclObjC.h"
20*67e74705SXin Li #include "llvm/ADT/SmallSet.h"
21*67e74705SXin Li #include "llvm/IR/CallSite.h"
22*67e74705SXin Li #include "llvm/IR/DataLayout.h"
23*67e74705SXin Li #include "llvm/IR/Module.h"
24*67e74705SXin Li #include <algorithm>
25*67e74705SXin Li #include <cstdio>
26*67e74705SXin Li 
27*67e74705SXin Li using namespace clang;
28*67e74705SXin Li using namespace CodeGen;
29*67e74705SXin Li 
CGBlockInfo(const BlockDecl * block,StringRef name)30*67e74705SXin Li CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31*67e74705SXin Li   : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32*67e74705SXin Li     HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33*67e74705SXin Li     LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
34*67e74705SXin Li     DominatingIP(nullptr) {
35*67e74705SXin Li 
36*67e74705SXin Li   // Skip asm prefix, if any.  'name' is usually taken directly from
37*67e74705SXin Li   // the mangled name of the enclosing function.
38*67e74705SXin Li   if (!name.empty() && name[0] == '\01')
39*67e74705SXin Li     name = name.substr(1);
40*67e74705SXin Li }
41*67e74705SXin Li 
42*67e74705SXin Li // Anchor the vtable to this translation unit.
~BlockByrefHelpers()43*67e74705SXin Li BlockByrefHelpers::~BlockByrefHelpers() {}
44*67e74705SXin Li 
45*67e74705SXin Li /// Build the given block as a global block.
46*67e74705SXin Li static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47*67e74705SXin Li                                         const CGBlockInfo &blockInfo,
48*67e74705SXin Li                                         llvm::Constant *blockFn);
49*67e74705SXin Li 
50*67e74705SXin Li /// Build the helper function to copy a block.
buildCopyHelper(CodeGenModule & CGM,const CGBlockInfo & blockInfo)51*67e74705SXin Li static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52*67e74705SXin Li                                        const CGBlockInfo &blockInfo) {
53*67e74705SXin Li   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54*67e74705SXin Li }
55*67e74705SXin Li 
56*67e74705SXin Li /// Build the helper function to dispose of a block.
buildDisposeHelper(CodeGenModule & CGM,const CGBlockInfo & blockInfo)57*67e74705SXin Li static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58*67e74705SXin Li                                           const CGBlockInfo &blockInfo) {
59*67e74705SXin Li   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60*67e74705SXin Li }
61*67e74705SXin Li 
62*67e74705SXin Li /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63*67e74705SXin Li /// buildBlockDescriptor is accessed from 5th field of the Block_literal
64*67e74705SXin Li /// meta-data and contains stationary information about the block literal.
65*67e74705SXin Li /// Its definition will have 4 (or optinally 6) words.
66*67e74705SXin Li /// \code
67*67e74705SXin Li /// struct Block_descriptor {
68*67e74705SXin Li ///   unsigned long reserved;
69*67e74705SXin Li ///   unsigned long size;  // size of Block_literal metadata in bytes.
70*67e74705SXin Li ///   void *copy_func_helper_decl;  // optional copy helper.
71*67e74705SXin Li ///   void *destroy_func_decl; // optioanl destructor helper.
72*67e74705SXin Li ///   void *block_method_encoding_address; // @encode for block literal signature.
73*67e74705SXin Li ///   void *block_layout_info; // encoding of captured block variables.
74*67e74705SXin Li /// };
75*67e74705SXin Li /// \endcode
buildBlockDescriptor(CodeGenModule & CGM,const CGBlockInfo & blockInfo)76*67e74705SXin Li static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77*67e74705SXin Li                                             const CGBlockInfo &blockInfo) {
78*67e74705SXin Li   ASTContext &C = CGM.getContext();
79*67e74705SXin Li 
80*67e74705SXin Li   llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
81*67e74705SXin Li   llvm::Type *i8p = nullptr;
82*67e74705SXin Li   if (CGM.getLangOpts().OpenCL)
83*67e74705SXin Li     i8p =
84*67e74705SXin Li       llvm::Type::getInt8PtrTy(
85*67e74705SXin Li            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
86*67e74705SXin Li   else
87*67e74705SXin Li     i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
88*67e74705SXin Li 
89*67e74705SXin Li   SmallVector<llvm::Constant*, 6> elements;
90*67e74705SXin Li 
91*67e74705SXin Li   // reserved
92*67e74705SXin Li   elements.push_back(llvm::ConstantInt::get(ulong, 0));
93*67e74705SXin Li 
94*67e74705SXin Li   // Size
95*67e74705SXin Li   // FIXME: What is the right way to say this doesn't fit?  We should give
96*67e74705SXin Li   // a user diagnostic in that case.  Better fix would be to change the
97*67e74705SXin Li   // API to size_t.
98*67e74705SXin Li   elements.push_back(llvm::ConstantInt::get(ulong,
99*67e74705SXin Li                                             blockInfo.BlockSize.getQuantity()));
100*67e74705SXin Li 
101*67e74705SXin Li   // Optional copy/dispose helpers.
102*67e74705SXin Li   if (blockInfo.NeedsCopyDispose) {
103*67e74705SXin Li     // copy_func_helper_decl
104*67e74705SXin Li     elements.push_back(buildCopyHelper(CGM, blockInfo));
105*67e74705SXin Li 
106*67e74705SXin Li     // destroy_func_decl
107*67e74705SXin Li     elements.push_back(buildDisposeHelper(CGM, blockInfo));
108*67e74705SXin Li   }
109*67e74705SXin Li 
110*67e74705SXin Li   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
111*67e74705SXin Li   std::string typeAtEncoding =
112*67e74705SXin Li     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113*67e74705SXin Li   elements.push_back(llvm::ConstantExpr::getBitCast(
114*67e74705SXin Li     CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
115*67e74705SXin Li 
116*67e74705SXin Li   // GC layout.
117*67e74705SXin Li   if (C.getLangOpts().ObjC1) {
118*67e74705SXin Li     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119*67e74705SXin Li       elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120*67e74705SXin Li     else
121*67e74705SXin Li       elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122*67e74705SXin Li   }
123*67e74705SXin Li   else
124*67e74705SXin Li     elements.push_back(llvm::Constant::getNullValue(i8p));
125*67e74705SXin Li 
126*67e74705SXin Li   llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
127*67e74705SXin Li 
128*67e74705SXin Li   llvm::GlobalVariable *global =
129*67e74705SXin Li     new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130*67e74705SXin Li                              llvm::GlobalValue::InternalLinkage,
131*67e74705SXin Li                              init, "__block_descriptor_tmp");
132*67e74705SXin Li 
133*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
134*67e74705SXin Li }
135*67e74705SXin Li 
136*67e74705SXin Li /*
137*67e74705SXin Li   Purely notional variadic template describing the layout of a block.
138*67e74705SXin Li 
139*67e74705SXin Li   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140*67e74705SXin Li   struct Block_literal {
141*67e74705SXin Li     /// Initialized to one of:
142*67e74705SXin Li     ///   extern void *_NSConcreteStackBlock[];
143*67e74705SXin Li     ///   extern void *_NSConcreteGlobalBlock[];
144*67e74705SXin Li     ///
145*67e74705SXin Li     /// In theory, we could start one off malloc'ed by setting
146*67e74705SXin Li     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147*67e74705SXin Li     /// this isa:
148*67e74705SXin Li     ///   extern void *_NSConcreteMallocBlock[];
149*67e74705SXin Li     struct objc_class *isa;
150*67e74705SXin Li 
151*67e74705SXin Li     /// These are the flags (with corresponding bit number) that the
152*67e74705SXin Li     /// compiler is actually supposed to know about.
153*67e74705SXin Li     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154*67e74705SXin Li     ///   descriptor provides copy and dispose helper functions
155*67e74705SXin Li     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156*67e74705SXin Li     ///   object with a nontrivial destructor or copy constructor
157*67e74705SXin Li     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158*67e74705SXin Li     ///   as global memory
159*67e74705SXin Li     ///  29. BLOCK_USE_STRET - indicates that the block function
160*67e74705SXin Li     ///   uses stret, which objc_msgSend needs to know about
161*67e74705SXin Li     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162*67e74705SXin Li     ///   @encoded signature string
163*67e74705SXin Li     /// And we're not supposed to manipulate these:
164*67e74705SXin Li     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165*67e74705SXin Li     ///   to malloc'ed memory
166*67e74705SXin Li     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
167*67e74705SXin Li     ///   to GC-allocated memory
168*67e74705SXin Li     /// Additionally, the bottom 16 bits are a reference count which
169*67e74705SXin Li     /// should be zero on the stack.
170*67e74705SXin Li     int flags;
171*67e74705SXin Li 
172*67e74705SXin Li     /// Reserved;  should be zero-initialized.
173*67e74705SXin Li     int reserved;
174*67e74705SXin Li 
175*67e74705SXin Li     /// Function pointer generated from block literal.
176*67e74705SXin Li     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
177*67e74705SXin Li 
178*67e74705SXin Li     /// Block description metadata generated from block literal.
179*67e74705SXin Li     struct Block_descriptor *block_descriptor;
180*67e74705SXin Li 
181*67e74705SXin Li     /// Captured values follow.
182*67e74705SXin Li     _CapturesTypes captures...;
183*67e74705SXin Li   };
184*67e74705SXin Li  */
185*67e74705SXin Li 
186*67e74705SXin Li /// The number of fields in a block header.
187*67e74705SXin Li const unsigned BlockHeaderSize = 5;
188*67e74705SXin Li 
189*67e74705SXin Li namespace {
190*67e74705SXin Li   /// A chunk of data that we actually have to capture in the block.
191*67e74705SXin Li   struct BlockLayoutChunk {
192*67e74705SXin Li     CharUnits Alignment;
193*67e74705SXin Li     CharUnits Size;
194*67e74705SXin Li     Qualifiers::ObjCLifetime Lifetime;
195*67e74705SXin Li     const BlockDecl::Capture *Capture; // null for 'this'
196*67e74705SXin Li     llvm::Type *Type;
197*67e74705SXin Li 
BlockLayoutChunk__anonf4e099be0111::BlockLayoutChunk198*67e74705SXin Li     BlockLayoutChunk(CharUnits align, CharUnits size,
199*67e74705SXin Li                      Qualifiers::ObjCLifetime lifetime,
200*67e74705SXin Li                      const BlockDecl::Capture *capture,
201*67e74705SXin Li                      llvm::Type *type)
202*67e74705SXin Li       : Alignment(align), Size(size), Lifetime(lifetime),
203*67e74705SXin Li         Capture(capture), Type(type) {}
204*67e74705SXin Li 
205*67e74705SXin Li     /// Tell the block info that this chunk has the given field index.
setIndex__anonf4e099be0111::BlockLayoutChunk206*67e74705SXin Li     void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
207*67e74705SXin Li       if (!Capture) {
208*67e74705SXin Li         info.CXXThisIndex = index;
209*67e74705SXin Li         info.CXXThisOffset = offset;
210*67e74705SXin Li       } else {
211*67e74705SXin Li         info.Captures.insert({Capture->getVariable(),
212*67e74705SXin Li                               CGBlockInfo::Capture::makeIndex(index, offset)});
213*67e74705SXin Li       }
214*67e74705SXin Li     }
215*67e74705SXin Li   };
216*67e74705SXin Li 
217*67e74705SXin Li   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218*67e74705SXin Li   /// all __weak together. Preserve descending alignment in all situations.
operator <(const BlockLayoutChunk & left,const BlockLayoutChunk & right)219*67e74705SXin Li   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
220*67e74705SXin Li     if (left.Alignment != right.Alignment)
221*67e74705SXin Li       return left.Alignment > right.Alignment;
222*67e74705SXin Li 
223*67e74705SXin Li     auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
224*67e74705SXin Li       if (chunk.Capture && chunk.Capture->isByRef())
225*67e74705SXin Li         return 1;
226*67e74705SXin Li       if (chunk.Lifetime == Qualifiers::OCL_Strong)
227*67e74705SXin Li         return 0;
228*67e74705SXin Li       if (chunk.Lifetime == Qualifiers::OCL_Weak)
229*67e74705SXin Li         return 2;
230*67e74705SXin Li       return 3;
231*67e74705SXin Li     };
232*67e74705SXin Li 
233*67e74705SXin Li     return getPrefOrder(left) < getPrefOrder(right);
234*67e74705SXin Li   }
235*67e74705SXin Li } // end anonymous namespace
236*67e74705SXin Li 
237*67e74705SXin Li /// Determines if the given type is safe for constant capture in C++.
isSafeForCXXConstantCapture(QualType type)238*67e74705SXin Li static bool isSafeForCXXConstantCapture(QualType type) {
239*67e74705SXin Li   const RecordType *recordType =
240*67e74705SXin Li     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
241*67e74705SXin Li 
242*67e74705SXin Li   // Only records can be unsafe.
243*67e74705SXin Li   if (!recordType) return true;
244*67e74705SXin Li 
245*67e74705SXin Li   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
246*67e74705SXin Li 
247*67e74705SXin Li   // Maintain semantics for classes with non-trivial dtors or copy ctors.
248*67e74705SXin Li   if (!record->hasTrivialDestructor()) return false;
249*67e74705SXin Li   if (record->hasNonTrivialCopyConstructor()) return false;
250*67e74705SXin Li 
251*67e74705SXin Li   // Otherwise, we just have to make sure there aren't any mutable
252*67e74705SXin Li   // fields that might have changed since initialization.
253*67e74705SXin Li   return !record->hasMutableFields();
254*67e74705SXin Li }
255*67e74705SXin Li 
256*67e74705SXin Li /// It is illegal to modify a const object after initialization.
257*67e74705SXin Li /// Therefore, if a const object has a constant initializer, we don't
258*67e74705SXin Li /// actually need to keep storage for it in the block; we'll just
259*67e74705SXin Li /// rematerialize it at the start of the block function.  This is
260*67e74705SXin Li /// acceptable because we make no promises about address stability of
261*67e74705SXin Li /// captured variables.
tryCaptureAsConstant(CodeGenModule & CGM,CodeGenFunction * CGF,const VarDecl * var)262*67e74705SXin Li static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
263*67e74705SXin Li                                             CodeGenFunction *CGF,
264*67e74705SXin Li                                             const VarDecl *var) {
265*67e74705SXin Li   // Return if this is a function paramter. We shouldn't try to
266*67e74705SXin Li   // rematerialize default arguments of function parameters.
267*67e74705SXin Li   if (isa<ParmVarDecl>(var))
268*67e74705SXin Li     return nullptr;
269*67e74705SXin Li 
270*67e74705SXin Li   QualType type = var->getType();
271*67e74705SXin Li 
272*67e74705SXin Li   // We can only do this if the variable is const.
273*67e74705SXin Li   if (!type.isConstQualified()) return nullptr;
274*67e74705SXin Li 
275*67e74705SXin Li   // Furthermore, in C++ we have to worry about mutable fields:
276*67e74705SXin Li   // C++ [dcl.type.cv]p4:
277*67e74705SXin Li   //   Except that any class member declared mutable can be
278*67e74705SXin Li   //   modified, any attempt to modify a const object during its
279*67e74705SXin Li   //   lifetime results in undefined behavior.
280*67e74705SXin Li   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
281*67e74705SXin Li     return nullptr;
282*67e74705SXin Li 
283*67e74705SXin Li   // If the variable doesn't have any initializer (shouldn't this be
284*67e74705SXin Li   // invalid?), it's not clear what we should do.  Maybe capture as
285*67e74705SXin Li   // zero?
286*67e74705SXin Li   const Expr *init = var->getInit();
287*67e74705SXin Li   if (!init) return nullptr;
288*67e74705SXin Li 
289*67e74705SXin Li   return CGM.EmitConstantInit(*var, CGF);
290*67e74705SXin Li }
291*67e74705SXin Li 
292*67e74705SXin Li /// Get the low bit of a nonzero character count.  This is the
293*67e74705SXin Li /// alignment of the nth byte if the 0th byte is universally aligned.
getLowBit(CharUnits v)294*67e74705SXin Li static CharUnits getLowBit(CharUnits v) {
295*67e74705SXin Li   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
296*67e74705SXin Li }
297*67e74705SXin Li 
initializeForBlockHeader(CodeGenModule & CGM,CGBlockInfo & info,SmallVectorImpl<llvm::Type * > & elementTypes)298*67e74705SXin Li static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
299*67e74705SXin Li                              SmallVectorImpl<llvm::Type*> &elementTypes) {
300*67e74705SXin Li   // The header is basically 'struct { void *; int; int; void *; void *; }'.
301*67e74705SXin Li   // Assert that that struct is packed.
302*67e74705SXin Li   assert(CGM.getIntSize() <= CGM.getPointerSize());
303*67e74705SXin Li   assert(CGM.getIntAlign() <= CGM.getPointerAlign());
304*67e74705SXin Li   assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
305*67e74705SXin Li 
306*67e74705SXin Li   info.BlockAlign = CGM.getPointerAlign();
307*67e74705SXin Li   info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
308*67e74705SXin Li 
309*67e74705SXin Li   assert(elementTypes.empty());
310*67e74705SXin Li   elementTypes.push_back(CGM.VoidPtrTy);
311*67e74705SXin Li   elementTypes.push_back(CGM.IntTy);
312*67e74705SXin Li   elementTypes.push_back(CGM.IntTy);
313*67e74705SXin Li   elementTypes.push_back(CGM.VoidPtrTy);
314*67e74705SXin Li   elementTypes.push_back(CGM.getBlockDescriptorType());
315*67e74705SXin Li 
316*67e74705SXin Li   assert(elementTypes.size() == BlockHeaderSize);
317*67e74705SXin Li }
318*67e74705SXin Li 
319*67e74705SXin Li /// Compute the layout of the given block.  Attempts to lay the block
320*67e74705SXin Li /// out with minimal space requirements.
computeBlockInfo(CodeGenModule & CGM,CodeGenFunction * CGF,CGBlockInfo & info)321*67e74705SXin Li static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
322*67e74705SXin Li                              CGBlockInfo &info) {
323*67e74705SXin Li   ASTContext &C = CGM.getContext();
324*67e74705SXin Li   const BlockDecl *block = info.getBlockDecl();
325*67e74705SXin Li 
326*67e74705SXin Li   SmallVector<llvm::Type*, 8> elementTypes;
327*67e74705SXin Li   initializeForBlockHeader(CGM, info, elementTypes);
328*67e74705SXin Li 
329*67e74705SXin Li   if (!block->hasCaptures()) {
330*67e74705SXin Li     info.StructureType =
331*67e74705SXin Li       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
332*67e74705SXin Li     info.CanBeGlobal = true;
333*67e74705SXin Li     return;
334*67e74705SXin Li   }
335*67e74705SXin Li   else if (C.getLangOpts().ObjC1 &&
336*67e74705SXin Li            CGM.getLangOpts().getGC() == LangOptions::NonGC)
337*67e74705SXin Li     info.HasCapturedVariableLayout = true;
338*67e74705SXin Li 
339*67e74705SXin Li   // Collect the layout chunks.
340*67e74705SXin Li   SmallVector<BlockLayoutChunk, 16> layout;
341*67e74705SXin Li   layout.reserve(block->capturesCXXThis() +
342*67e74705SXin Li                  (block->capture_end() - block->capture_begin()));
343*67e74705SXin Li 
344*67e74705SXin Li   CharUnits maxFieldAlign;
345*67e74705SXin Li 
346*67e74705SXin Li   // First, 'this'.
347*67e74705SXin Li   if (block->capturesCXXThis()) {
348*67e74705SXin Li     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
349*67e74705SXin Li            "Can't capture 'this' outside a method");
350*67e74705SXin Li     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
351*67e74705SXin Li 
352*67e74705SXin Li     // Theoretically, this could be in a different address space, so
353*67e74705SXin Li     // don't assume standard pointer size/align.
354*67e74705SXin Li     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
355*67e74705SXin Li     std::pair<CharUnits,CharUnits> tinfo
356*67e74705SXin Li       = CGM.getContext().getTypeInfoInChars(thisType);
357*67e74705SXin Li     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
358*67e74705SXin Li 
359*67e74705SXin Li     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
360*67e74705SXin Li                                       Qualifiers::OCL_None,
361*67e74705SXin Li                                       nullptr, llvmType));
362*67e74705SXin Li   }
363*67e74705SXin Li 
364*67e74705SXin Li   // Next, all the block captures.
365*67e74705SXin Li   for (const auto &CI : block->captures()) {
366*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
367*67e74705SXin Li 
368*67e74705SXin Li     if (CI.isByRef()) {
369*67e74705SXin Li       // We have to copy/dispose of the __block reference.
370*67e74705SXin Li       info.NeedsCopyDispose = true;
371*67e74705SXin Li 
372*67e74705SXin Li       // Just use void* instead of a pointer to the byref type.
373*67e74705SXin Li       CharUnits align = CGM.getPointerAlign();
374*67e74705SXin Li       maxFieldAlign = std::max(maxFieldAlign, align);
375*67e74705SXin Li 
376*67e74705SXin Li       layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
377*67e74705SXin Li                                         Qualifiers::OCL_None, &CI,
378*67e74705SXin Li                                         CGM.VoidPtrTy));
379*67e74705SXin Li       continue;
380*67e74705SXin Li     }
381*67e74705SXin Li 
382*67e74705SXin Li     // Otherwise, build a layout chunk with the size and alignment of
383*67e74705SXin Li     // the declaration.
384*67e74705SXin Li     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
385*67e74705SXin Li       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
386*67e74705SXin Li       continue;
387*67e74705SXin Li     }
388*67e74705SXin Li 
389*67e74705SXin Li     // If we have a lifetime qualifier, honor it for capture purposes.
390*67e74705SXin Li     // That includes *not* copying it if it's __unsafe_unretained.
391*67e74705SXin Li     Qualifiers::ObjCLifetime lifetime =
392*67e74705SXin Li       variable->getType().getObjCLifetime();
393*67e74705SXin Li     if (lifetime) {
394*67e74705SXin Li       switch (lifetime) {
395*67e74705SXin Li       case Qualifiers::OCL_None: llvm_unreachable("impossible");
396*67e74705SXin Li       case Qualifiers::OCL_ExplicitNone:
397*67e74705SXin Li       case Qualifiers::OCL_Autoreleasing:
398*67e74705SXin Li         break;
399*67e74705SXin Li 
400*67e74705SXin Li       case Qualifiers::OCL_Strong:
401*67e74705SXin Li       case Qualifiers::OCL_Weak:
402*67e74705SXin Li         info.NeedsCopyDispose = true;
403*67e74705SXin Li       }
404*67e74705SXin Li 
405*67e74705SXin Li     // Block pointers require copy/dispose.  So do Objective-C pointers.
406*67e74705SXin Li     } else if (variable->getType()->isObjCRetainableType()) {
407*67e74705SXin Li       // But honor the inert __unsafe_unretained qualifier, which doesn't
408*67e74705SXin Li       // actually make it into the type system.
409*67e74705SXin Li        if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
410*67e74705SXin Li         lifetime = Qualifiers::OCL_ExplicitNone;
411*67e74705SXin Li       } else {
412*67e74705SXin Li         info.NeedsCopyDispose = true;
413*67e74705SXin Li         // used for mrr below.
414*67e74705SXin Li         lifetime = Qualifiers::OCL_Strong;
415*67e74705SXin Li       }
416*67e74705SXin Li 
417*67e74705SXin Li     // So do types that require non-trivial copy construction.
418*67e74705SXin Li     } else if (CI.hasCopyExpr()) {
419*67e74705SXin Li       info.NeedsCopyDispose = true;
420*67e74705SXin Li       info.HasCXXObject = true;
421*67e74705SXin Li 
422*67e74705SXin Li     // And so do types with destructors.
423*67e74705SXin Li     } else if (CGM.getLangOpts().CPlusPlus) {
424*67e74705SXin Li       if (const CXXRecordDecl *record =
425*67e74705SXin Li             variable->getType()->getAsCXXRecordDecl()) {
426*67e74705SXin Li         if (!record->hasTrivialDestructor()) {
427*67e74705SXin Li           info.HasCXXObject = true;
428*67e74705SXin Li           info.NeedsCopyDispose = true;
429*67e74705SXin Li         }
430*67e74705SXin Li       }
431*67e74705SXin Li     }
432*67e74705SXin Li 
433*67e74705SXin Li     QualType VT = variable->getType();
434*67e74705SXin Li     CharUnits size = C.getTypeSizeInChars(VT);
435*67e74705SXin Li     CharUnits align = C.getDeclAlign(variable);
436*67e74705SXin Li 
437*67e74705SXin Li     maxFieldAlign = std::max(maxFieldAlign, align);
438*67e74705SXin Li 
439*67e74705SXin Li     llvm::Type *llvmType =
440*67e74705SXin Li       CGM.getTypes().ConvertTypeForMem(VT);
441*67e74705SXin Li 
442*67e74705SXin Li     layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
443*67e74705SXin Li   }
444*67e74705SXin Li 
445*67e74705SXin Li   // If that was everything, we're done here.
446*67e74705SXin Li   if (layout.empty()) {
447*67e74705SXin Li     info.StructureType =
448*67e74705SXin Li       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
449*67e74705SXin Li     info.CanBeGlobal = true;
450*67e74705SXin Li     return;
451*67e74705SXin Li   }
452*67e74705SXin Li 
453*67e74705SXin Li   // Sort the layout by alignment.  We have to use a stable sort here
454*67e74705SXin Li   // to get reproducible results.  There should probably be an
455*67e74705SXin Li   // llvm::array_pod_stable_sort.
456*67e74705SXin Li   std::stable_sort(layout.begin(), layout.end());
457*67e74705SXin Li 
458*67e74705SXin Li   // Needed for blocks layout info.
459*67e74705SXin Li   info.BlockHeaderForcedGapOffset = info.BlockSize;
460*67e74705SXin Li   info.BlockHeaderForcedGapSize = CharUnits::Zero();
461*67e74705SXin Li 
462*67e74705SXin Li   CharUnits &blockSize = info.BlockSize;
463*67e74705SXin Li   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
464*67e74705SXin Li 
465*67e74705SXin Li   // Assuming that the first byte in the header is maximally aligned,
466*67e74705SXin Li   // get the alignment of the first byte following the header.
467*67e74705SXin Li   CharUnits endAlign = getLowBit(blockSize);
468*67e74705SXin Li 
469*67e74705SXin Li   // If the end of the header isn't satisfactorily aligned for the
470*67e74705SXin Li   // maximum thing, look for things that are okay with the header-end
471*67e74705SXin Li   // alignment, and keep appending them until we get something that's
472*67e74705SXin Li   // aligned right.  This algorithm is only guaranteed optimal if
473*67e74705SXin Li   // that condition is satisfied at some point; otherwise we can get
474*67e74705SXin Li   // things like:
475*67e74705SXin Li   //   header                 // next byte has alignment 4
476*67e74705SXin Li   //   something_with_size_5; // next byte has alignment 1
477*67e74705SXin Li   //   something_with_alignment_8;
478*67e74705SXin Li   // which has 7 bytes of padding, as opposed to the naive solution
479*67e74705SXin Li   // which might have less (?).
480*67e74705SXin Li   if (endAlign < maxFieldAlign) {
481*67e74705SXin Li     SmallVectorImpl<BlockLayoutChunk>::iterator
482*67e74705SXin Li       li = layout.begin() + 1, le = layout.end();
483*67e74705SXin Li 
484*67e74705SXin Li     // Look for something that the header end is already
485*67e74705SXin Li     // satisfactorily aligned for.
486*67e74705SXin Li     for (; li != le && endAlign < li->Alignment; ++li)
487*67e74705SXin Li       ;
488*67e74705SXin Li 
489*67e74705SXin Li     // If we found something that's naturally aligned for the end of
490*67e74705SXin Li     // the header, keep adding things...
491*67e74705SXin Li     if (li != le) {
492*67e74705SXin Li       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
493*67e74705SXin Li       for (; li != le; ++li) {
494*67e74705SXin Li         assert(endAlign >= li->Alignment);
495*67e74705SXin Li 
496*67e74705SXin Li         li->setIndex(info, elementTypes.size(), blockSize);
497*67e74705SXin Li         elementTypes.push_back(li->Type);
498*67e74705SXin Li         blockSize += li->Size;
499*67e74705SXin Li         endAlign = getLowBit(blockSize);
500*67e74705SXin Li 
501*67e74705SXin Li         // ...until we get to the alignment of the maximum field.
502*67e74705SXin Li         if (endAlign >= maxFieldAlign) {
503*67e74705SXin Li           break;
504*67e74705SXin Li         }
505*67e74705SXin Li       }
506*67e74705SXin Li       // Don't re-append everything we just appended.
507*67e74705SXin Li       layout.erase(first, li);
508*67e74705SXin Li     }
509*67e74705SXin Li   }
510*67e74705SXin Li 
511*67e74705SXin Li   assert(endAlign == getLowBit(blockSize));
512*67e74705SXin Li 
513*67e74705SXin Li   // At this point, we just have to add padding if the end align still
514*67e74705SXin Li   // isn't aligned right.
515*67e74705SXin Li   if (endAlign < maxFieldAlign) {
516*67e74705SXin Li     CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
517*67e74705SXin Li     CharUnits padding = newBlockSize - blockSize;
518*67e74705SXin Li 
519*67e74705SXin Li     // If we haven't yet added any fields, remember that there was an
520*67e74705SXin Li     // initial gap; this need to go into the block layout bit map.
521*67e74705SXin Li     if (blockSize == info.BlockHeaderForcedGapOffset) {
522*67e74705SXin Li       info.BlockHeaderForcedGapSize = padding;
523*67e74705SXin Li     }
524*67e74705SXin Li 
525*67e74705SXin Li     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
526*67e74705SXin Li                                                 padding.getQuantity()));
527*67e74705SXin Li     blockSize = newBlockSize;
528*67e74705SXin Li     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
529*67e74705SXin Li   }
530*67e74705SXin Li 
531*67e74705SXin Li   assert(endAlign >= maxFieldAlign);
532*67e74705SXin Li   assert(endAlign == getLowBit(blockSize));
533*67e74705SXin Li   // Slam everything else on now.  This works because they have
534*67e74705SXin Li   // strictly decreasing alignment and we expect that size is always a
535*67e74705SXin Li   // multiple of alignment.
536*67e74705SXin Li   for (SmallVectorImpl<BlockLayoutChunk>::iterator
537*67e74705SXin Li          li = layout.begin(), le = layout.end(); li != le; ++li) {
538*67e74705SXin Li     if (endAlign < li->Alignment) {
539*67e74705SXin Li       // size may not be multiple of alignment. This can only happen with
540*67e74705SXin Li       // an over-aligned variable. We will be adding a padding field to
541*67e74705SXin Li       // make the size be multiple of alignment.
542*67e74705SXin Li       CharUnits padding = li->Alignment - endAlign;
543*67e74705SXin Li       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
544*67e74705SXin Li                                                   padding.getQuantity()));
545*67e74705SXin Li       blockSize += padding;
546*67e74705SXin Li       endAlign = getLowBit(blockSize);
547*67e74705SXin Li     }
548*67e74705SXin Li     assert(endAlign >= li->Alignment);
549*67e74705SXin Li     li->setIndex(info, elementTypes.size(), blockSize);
550*67e74705SXin Li     elementTypes.push_back(li->Type);
551*67e74705SXin Li     blockSize += li->Size;
552*67e74705SXin Li     endAlign = getLowBit(blockSize);
553*67e74705SXin Li   }
554*67e74705SXin Li 
555*67e74705SXin Li   info.StructureType =
556*67e74705SXin Li     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
557*67e74705SXin Li }
558*67e74705SXin Li 
559*67e74705SXin Li /// Enter the scope of a block.  This should be run at the entrance to
560*67e74705SXin Li /// a full-expression so that the block's cleanups are pushed at the
561*67e74705SXin Li /// right place in the stack.
enterBlockScope(CodeGenFunction & CGF,BlockDecl * block)562*67e74705SXin Li static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
563*67e74705SXin Li   assert(CGF.HaveInsertPoint());
564*67e74705SXin Li 
565*67e74705SXin Li   // Allocate the block info and place it at the head of the list.
566*67e74705SXin Li   CGBlockInfo &blockInfo =
567*67e74705SXin Li     *new CGBlockInfo(block, CGF.CurFn->getName());
568*67e74705SXin Li   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
569*67e74705SXin Li   CGF.FirstBlockInfo = &blockInfo;
570*67e74705SXin Li 
571*67e74705SXin Li   // Compute information about the layout, etc., of this block,
572*67e74705SXin Li   // pushing cleanups as necessary.
573*67e74705SXin Li   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
574*67e74705SXin Li 
575*67e74705SXin Li   // Nothing else to do if it can be global.
576*67e74705SXin Li   if (blockInfo.CanBeGlobal) return;
577*67e74705SXin Li 
578*67e74705SXin Li   // Make the allocation for the block.
579*67e74705SXin Li   blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
580*67e74705SXin Li                                                 blockInfo.BlockAlign, "block");
581*67e74705SXin Li 
582*67e74705SXin Li   // If there are cleanups to emit, enter them (but inactive).
583*67e74705SXin Li   if (!blockInfo.NeedsCopyDispose) return;
584*67e74705SXin Li 
585*67e74705SXin Li   // Walk through the captures (in order) and find the ones not
586*67e74705SXin Li   // captured by constant.
587*67e74705SXin Li   for (const auto &CI : block->captures()) {
588*67e74705SXin Li     // Ignore __block captures; there's nothing special in the
589*67e74705SXin Li     // on-stack block that we need to do for them.
590*67e74705SXin Li     if (CI.isByRef()) continue;
591*67e74705SXin Li 
592*67e74705SXin Li     // Ignore variables that are constant-captured.
593*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
594*67e74705SXin Li     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
595*67e74705SXin Li     if (capture.isConstant()) continue;
596*67e74705SXin Li 
597*67e74705SXin Li     // Ignore objects that aren't destructed.
598*67e74705SXin Li     QualType::DestructionKind dtorKind =
599*67e74705SXin Li       variable->getType().isDestructedType();
600*67e74705SXin Li     if (dtorKind == QualType::DK_none) continue;
601*67e74705SXin Li 
602*67e74705SXin Li     CodeGenFunction::Destroyer *destroyer;
603*67e74705SXin Li 
604*67e74705SXin Li     // Block captures count as local values and have imprecise semantics.
605*67e74705SXin Li     // They also can't be arrays, so need to worry about that.
606*67e74705SXin Li     if (dtorKind == QualType::DK_objc_strong_lifetime) {
607*67e74705SXin Li       destroyer = CodeGenFunction::destroyARCStrongImprecise;
608*67e74705SXin Li     } else {
609*67e74705SXin Li       destroyer = CGF.getDestroyer(dtorKind);
610*67e74705SXin Li     }
611*67e74705SXin Li 
612*67e74705SXin Li     // GEP down to the address.
613*67e74705SXin Li     Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
614*67e74705SXin Li                                                capture.getIndex(),
615*67e74705SXin Li                                                capture.getOffset());
616*67e74705SXin Li 
617*67e74705SXin Li     // We can use that GEP as the dominating IP.
618*67e74705SXin Li     if (!blockInfo.DominatingIP)
619*67e74705SXin Li       blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
620*67e74705SXin Li 
621*67e74705SXin Li     CleanupKind cleanupKind = InactiveNormalCleanup;
622*67e74705SXin Li     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623*67e74705SXin Li     if (useArrayEHCleanup)
624*67e74705SXin Li       cleanupKind = InactiveNormalAndEHCleanup;
625*67e74705SXin Li 
626*67e74705SXin Li     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627*67e74705SXin Li                     destroyer, useArrayEHCleanup);
628*67e74705SXin Li 
629*67e74705SXin Li     // Remember where that cleanup was.
630*67e74705SXin Li     capture.setCleanup(CGF.EHStack.stable_begin());
631*67e74705SXin Li   }
632*67e74705SXin Li }
633*67e74705SXin Li 
634*67e74705SXin Li /// Enter a full-expression with a non-trivial number of objects to
635*67e74705SXin Li /// clean up.  This is in this file because, at the moment, the only
636*67e74705SXin Li /// kind of cleanup object is a BlockDecl*.
enterNonTrivialFullExpression(const ExprWithCleanups * E)637*67e74705SXin Li void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638*67e74705SXin Li   assert(E->getNumObjects() != 0);
639*67e74705SXin Li   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640*67e74705SXin Li   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641*67e74705SXin Li          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642*67e74705SXin Li     enterBlockScope(*this, *i);
643*67e74705SXin Li   }
644*67e74705SXin Li }
645*67e74705SXin Li 
646*67e74705SXin Li /// Find the layout for the given block in a linked list and remove it.
findAndRemoveBlockInfo(CGBlockInfo ** head,const BlockDecl * block)647*67e74705SXin Li static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648*67e74705SXin Li                                            const BlockDecl *block) {
649*67e74705SXin Li   while (true) {
650*67e74705SXin Li     assert(head && *head);
651*67e74705SXin Li     CGBlockInfo *cur = *head;
652*67e74705SXin Li 
653*67e74705SXin Li     // If this is the block we're looking for, splice it out of the list.
654*67e74705SXin Li     if (cur->getBlockDecl() == block) {
655*67e74705SXin Li       *head = cur->NextBlockInfo;
656*67e74705SXin Li       return cur;
657*67e74705SXin Li     }
658*67e74705SXin Li 
659*67e74705SXin Li     head = &cur->NextBlockInfo;
660*67e74705SXin Li   }
661*67e74705SXin Li }
662*67e74705SXin Li 
663*67e74705SXin Li /// Destroy a chain of block layouts.
destroyBlockInfos(CGBlockInfo * head)664*67e74705SXin Li void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665*67e74705SXin Li   assert(head && "destroying an empty chain");
666*67e74705SXin Li   do {
667*67e74705SXin Li     CGBlockInfo *cur = head;
668*67e74705SXin Li     head = cur->NextBlockInfo;
669*67e74705SXin Li     delete cur;
670*67e74705SXin Li   } while (head != nullptr);
671*67e74705SXin Li }
672*67e74705SXin Li 
673*67e74705SXin Li /// Emit a block literal expression in the current function.
EmitBlockLiteral(const BlockExpr * blockExpr)674*67e74705SXin Li llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
675*67e74705SXin Li   // If the block has no captures, we won't have a pre-computed
676*67e74705SXin Li   // layout for it.
677*67e74705SXin Li   if (!blockExpr->getBlockDecl()->hasCaptures()) {
678*67e74705SXin Li     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
679*67e74705SXin Li     computeBlockInfo(CGM, this, blockInfo);
680*67e74705SXin Li     blockInfo.BlockExpression = blockExpr;
681*67e74705SXin Li     return EmitBlockLiteral(blockInfo);
682*67e74705SXin Li   }
683*67e74705SXin Li 
684*67e74705SXin Li   // Find the block info for this block and take ownership of it.
685*67e74705SXin Li   std::unique_ptr<CGBlockInfo> blockInfo;
686*67e74705SXin Li   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687*67e74705SXin Li                                          blockExpr->getBlockDecl()));
688*67e74705SXin Li 
689*67e74705SXin Li   blockInfo->BlockExpression = blockExpr;
690*67e74705SXin Li   return EmitBlockLiteral(*blockInfo);
691*67e74705SXin Li }
692*67e74705SXin Li 
EmitBlockLiteral(const CGBlockInfo & blockInfo)693*67e74705SXin Li llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694*67e74705SXin Li   // Using the computed layout, generate the actual block function.
695*67e74705SXin Li   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
696*67e74705SXin Li   llvm::Constant *blockFn
697*67e74705SXin Li     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
698*67e74705SXin Li                                                        LocalDeclMap,
699*67e74705SXin Li                                                        isLambdaConv);
700*67e74705SXin Li   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
701*67e74705SXin Li 
702*67e74705SXin Li   // If there is nothing to capture, we can emit this as a global block.
703*67e74705SXin Li   if (blockInfo.CanBeGlobal)
704*67e74705SXin Li     return buildGlobalBlock(CGM, blockInfo, blockFn);
705*67e74705SXin Li 
706*67e74705SXin Li   // Otherwise, we have to emit this as a local block.
707*67e74705SXin Li 
708*67e74705SXin Li   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
709*67e74705SXin Li   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
710*67e74705SXin Li 
711*67e74705SXin Li   // Build the block descriptor.
712*67e74705SXin Li   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
713*67e74705SXin Li 
714*67e74705SXin Li   Address blockAddr = blockInfo.LocalAddress;
715*67e74705SXin Li   assert(blockAddr.isValid() && "block has no address!");
716*67e74705SXin Li 
717*67e74705SXin Li   // Compute the initial on-stack block flags.
718*67e74705SXin Li   BlockFlags flags = BLOCK_HAS_SIGNATURE;
719*67e74705SXin Li   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
720*67e74705SXin Li   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721*67e74705SXin Li   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
722*67e74705SXin Li   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
723*67e74705SXin Li 
724*67e74705SXin Li   auto projectField =
725*67e74705SXin Li     [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
726*67e74705SXin Li       return Builder.CreateStructGEP(blockAddr, index, offset, name);
727*67e74705SXin Li     };
728*67e74705SXin Li   auto storeField =
729*67e74705SXin Li     [&](llvm::Value *value, unsigned index, CharUnits offset,
730*67e74705SXin Li         const Twine &name) {
731*67e74705SXin Li       Builder.CreateStore(value, projectField(index, offset, name));
732*67e74705SXin Li     };
733*67e74705SXin Li 
734*67e74705SXin Li   // Initialize the block header.
735*67e74705SXin Li   {
736*67e74705SXin Li     // We assume all the header fields are densely packed.
737*67e74705SXin Li     unsigned index = 0;
738*67e74705SXin Li     CharUnits offset;
739*67e74705SXin Li     auto addHeaderField =
740*67e74705SXin Li       [&](llvm::Value *value, CharUnits size, const Twine &name) {
741*67e74705SXin Li         storeField(value, index, offset, name);
742*67e74705SXin Li         offset += size;
743*67e74705SXin Li         index++;
744*67e74705SXin Li       };
745*67e74705SXin Li 
746*67e74705SXin Li     addHeaderField(isa, getPointerSize(), "block.isa");
747*67e74705SXin Li     addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
748*67e74705SXin Li                    getIntSize(), "block.flags");
749*67e74705SXin Li     addHeaderField(llvm::ConstantInt::get(IntTy, 0),
750*67e74705SXin Li                    getIntSize(), "block.reserved");
751*67e74705SXin Li     addHeaderField(blockFn, getPointerSize(), "block.invoke");
752*67e74705SXin Li     addHeaderField(descriptor, getPointerSize(), "block.descriptor");
753*67e74705SXin Li   }
754*67e74705SXin Li 
755*67e74705SXin Li   // Finally, capture all the values into the block.
756*67e74705SXin Li   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
757*67e74705SXin Li 
758*67e74705SXin Li   // First, 'this'.
759*67e74705SXin Li   if (blockDecl->capturesCXXThis()) {
760*67e74705SXin Li     Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
761*67e74705SXin Li                                 "block.captured-this.addr");
762*67e74705SXin Li     Builder.CreateStore(LoadCXXThis(), addr);
763*67e74705SXin Li   }
764*67e74705SXin Li 
765*67e74705SXin Li   // Next, captured variables.
766*67e74705SXin Li   for (const auto &CI : blockDecl->captures()) {
767*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
768*67e74705SXin Li     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
769*67e74705SXin Li 
770*67e74705SXin Li     // Ignore constant captures.
771*67e74705SXin Li     if (capture.isConstant()) continue;
772*67e74705SXin Li 
773*67e74705SXin Li     QualType type = variable->getType();
774*67e74705SXin Li 
775*67e74705SXin Li     // This will be a [[type]]*, except that a byref entry will just be
776*67e74705SXin Li     // an i8**.
777*67e74705SXin Li     Address blockField =
778*67e74705SXin Li       projectField(capture.getIndex(), capture.getOffset(), "block.captured");
779*67e74705SXin Li 
780*67e74705SXin Li     // Compute the address of the thing we're going to move into the
781*67e74705SXin Li     // block literal.
782*67e74705SXin Li     Address src = Address::invalid();
783*67e74705SXin Li 
784*67e74705SXin Li     if (blockDecl->isConversionFromLambda()) {
785*67e74705SXin Li       // The lambda capture in a lambda's conversion-to-block-pointer is
786*67e74705SXin Li       // special; we'll simply emit it directly.
787*67e74705SXin Li       src = Address::invalid();
788*67e74705SXin Li     } else if (CI.isByRef()) {
789*67e74705SXin Li       if (BlockInfo && CI.isNested()) {
790*67e74705SXin Li         // We need to use the capture from the enclosing block.
791*67e74705SXin Li         const CGBlockInfo::Capture &enclosingCapture =
792*67e74705SXin Li             BlockInfo->getCapture(variable);
793*67e74705SXin Li 
794*67e74705SXin Li         // This is a [[type]]*, except that a byref entry wil just be an i8**.
795*67e74705SXin Li         src = Builder.CreateStructGEP(LoadBlockStruct(),
796*67e74705SXin Li                                       enclosingCapture.getIndex(),
797*67e74705SXin Li                                       enclosingCapture.getOffset(),
798*67e74705SXin Li                                       "block.capture.addr");
799*67e74705SXin Li       } else {
800*67e74705SXin Li         auto I = LocalDeclMap.find(variable);
801*67e74705SXin Li         assert(I != LocalDeclMap.end());
802*67e74705SXin Li         src = I->second;
803*67e74705SXin Li       }
804*67e74705SXin Li     } else {
805*67e74705SXin Li       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
806*67e74705SXin Li                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
807*67e74705SXin Li                           type.getNonReferenceType(), VK_LValue,
808*67e74705SXin Li                           SourceLocation());
809*67e74705SXin Li       src = EmitDeclRefLValue(&declRef).getAddress();
810*67e74705SXin Li     };
811*67e74705SXin Li 
812*67e74705SXin Li     // For byrefs, we just write the pointer to the byref struct into
813*67e74705SXin Li     // the block field.  There's no need to chase the forwarding
814*67e74705SXin Li     // pointer at this point, since we're building something that will
815*67e74705SXin Li     // live a shorter life than the stack byref anyway.
816*67e74705SXin Li     if (CI.isByRef()) {
817*67e74705SXin Li       // Get a void* that points to the byref struct.
818*67e74705SXin Li       llvm::Value *byrefPointer;
819*67e74705SXin Li       if (CI.isNested())
820*67e74705SXin Li         byrefPointer = Builder.CreateLoad(src, "byref.capture");
821*67e74705SXin Li       else
822*67e74705SXin Li         byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
823*67e74705SXin Li 
824*67e74705SXin Li       // Write that void* into the capture field.
825*67e74705SXin Li       Builder.CreateStore(byrefPointer, blockField);
826*67e74705SXin Li 
827*67e74705SXin Li     // If we have a copy constructor, evaluate that into the block field.
828*67e74705SXin Li     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
829*67e74705SXin Li       if (blockDecl->isConversionFromLambda()) {
830*67e74705SXin Li         // If we have a lambda conversion, emit the expression
831*67e74705SXin Li         // directly into the block instead.
832*67e74705SXin Li         AggValueSlot Slot =
833*67e74705SXin Li             AggValueSlot::forAddr(blockField, Qualifiers(),
834*67e74705SXin Li                                   AggValueSlot::IsDestructed,
835*67e74705SXin Li                                   AggValueSlot::DoesNotNeedGCBarriers,
836*67e74705SXin Li                                   AggValueSlot::IsNotAliased);
837*67e74705SXin Li         EmitAggExpr(copyExpr, Slot);
838*67e74705SXin Li       } else {
839*67e74705SXin Li         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
840*67e74705SXin Li       }
841*67e74705SXin Li 
842*67e74705SXin Li     // If it's a reference variable, copy the reference into the block field.
843*67e74705SXin Li     } else if (type->isReferenceType()) {
844*67e74705SXin Li       Builder.CreateStore(src.getPointer(), blockField);
845*67e74705SXin Li 
846*67e74705SXin Li     // If this is an ARC __strong block-pointer variable, don't do a
847*67e74705SXin Li     // block copy.
848*67e74705SXin Li     //
849*67e74705SXin Li     // TODO: this can be generalized into the normal initialization logic:
850*67e74705SXin Li     // we should never need to do a block-copy when initializing a local
851*67e74705SXin Li     // variable, because the local variable's lifetime should be strictly
852*67e74705SXin Li     // contained within the stack block's.
853*67e74705SXin Li     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
854*67e74705SXin Li                type->isBlockPointerType()) {
855*67e74705SXin Li       // Load the block and do a simple retain.
856*67e74705SXin Li       llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
857*67e74705SXin Li       value = EmitARCRetainNonBlock(value);
858*67e74705SXin Li 
859*67e74705SXin Li       // Do a primitive store to the block field.
860*67e74705SXin Li       Builder.CreateStore(value, blockField);
861*67e74705SXin Li 
862*67e74705SXin Li     // Otherwise, fake up a POD copy into the block field.
863*67e74705SXin Li     } else {
864*67e74705SXin Li       // Fake up a new variable so that EmitScalarInit doesn't think
865*67e74705SXin Li       // we're referring to the variable in its own initializer.
866*67e74705SXin Li       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
867*67e74705SXin Li                                             SourceLocation(), /*name*/ nullptr,
868*67e74705SXin Li                                             type);
869*67e74705SXin Li 
870*67e74705SXin Li       // We use one of these or the other depending on whether the
871*67e74705SXin Li       // reference is nested.
872*67e74705SXin Li       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
873*67e74705SXin Li                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
874*67e74705SXin Li                           type, VK_LValue, SourceLocation());
875*67e74705SXin Li 
876*67e74705SXin Li       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
877*67e74705SXin Li                            &declRef, VK_RValue);
878*67e74705SXin Li       // FIXME: Pass a specific location for the expr init so that the store is
879*67e74705SXin Li       // attributed to a reasonable location - otherwise it may be attributed to
880*67e74705SXin Li       // locations of subexpressions in the initialization.
881*67e74705SXin Li       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
882*67e74705SXin Li                      MakeAddrLValue(blockField, type, AlignmentSource::Decl),
883*67e74705SXin Li                      /*captured by init*/ false);
884*67e74705SXin Li     }
885*67e74705SXin Li 
886*67e74705SXin Li     // Activate the cleanup if layout pushed one.
887*67e74705SXin Li     if (!CI.isByRef()) {
888*67e74705SXin Li       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
889*67e74705SXin Li       if (cleanup.isValid())
890*67e74705SXin Li         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
891*67e74705SXin Li     }
892*67e74705SXin Li   }
893*67e74705SXin Li 
894*67e74705SXin Li   // Cast to the converted block-pointer type, which happens (somewhat
895*67e74705SXin Li   // unfortunately) to be a pointer to function type.
896*67e74705SXin Li   llvm::Value *result =
897*67e74705SXin Li     Builder.CreateBitCast(blockAddr.getPointer(),
898*67e74705SXin Li                           ConvertType(blockInfo.getBlockExpr()->getType()));
899*67e74705SXin Li 
900*67e74705SXin Li   return result;
901*67e74705SXin Li }
902*67e74705SXin Li 
903*67e74705SXin Li 
getBlockDescriptorType()904*67e74705SXin Li llvm::Type *CodeGenModule::getBlockDescriptorType() {
905*67e74705SXin Li   if (BlockDescriptorType)
906*67e74705SXin Li     return BlockDescriptorType;
907*67e74705SXin Li 
908*67e74705SXin Li   llvm::Type *UnsignedLongTy =
909*67e74705SXin Li     getTypes().ConvertType(getContext().UnsignedLongTy);
910*67e74705SXin Li 
911*67e74705SXin Li   // struct __block_descriptor {
912*67e74705SXin Li   //   unsigned long reserved;
913*67e74705SXin Li   //   unsigned long block_size;
914*67e74705SXin Li   //
915*67e74705SXin Li   //   // later, the following will be added
916*67e74705SXin Li   //
917*67e74705SXin Li   //   struct {
918*67e74705SXin Li   //     void (*copyHelper)();
919*67e74705SXin Li   //     void (*copyHelper)();
920*67e74705SXin Li   //   } helpers;                // !!! optional
921*67e74705SXin Li   //
922*67e74705SXin Li   //   const char *signature;   // the block signature
923*67e74705SXin Li   //   const char *layout;      // reserved
924*67e74705SXin Li   // };
925*67e74705SXin Li   BlockDescriptorType =
926*67e74705SXin Li     llvm::StructType::create("struct.__block_descriptor",
927*67e74705SXin Li                              UnsignedLongTy, UnsignedLongTy, nullptr);
928*67e74705SXin Li 
929*67e74705SXin Li   // Now form a pointer to that.
930*67e74705SXin Li   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
931*67e74705SXin Li   return BlockDescriptorType;
932*67e74705SXin Li }
933*67e74705SXin Li 
getGenericBlockLiteralType()934*67e74705SXin Li llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
935*67e74705SXin Li   if (GenericBlockLiteralType)
936*67e74705SXin Li     return GenericBlockLiteralType;
937*67e74705SXin Li 
938*67e74705SXin Li   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
939*67e74705SXin Li 
940*67e74705SXin Li   // struct __block_literal_generic {
941*67e74705SXin Li   //   void *__isa;
942*67e74705SXin Li   //   int __flags;
943*67e74705SXin Li   //   int __reserved;
944*67e74705SXin Li   //   void (*__invoke)(void *);
945*67e74705SXin Li   //   struct __block_descriptor *__descriptor;
946*67e74705SXin Li   // };
947*67e74705SXin Li   GenericBlockLiteralType =
948*67e74705SXin Li     llvm::StructType::create("struct.__block_literal_generic",
949*67e74705SXin Li                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
950*67e74705SXin Li                              BlockDescPtrTy, nullptr);
951*67e74705SXin Li 
952*67e74705SXin Li   return GenericBlockLiteralType;
953*67e74705SXin Li }
954*67e74705SXin Li 
EmitBlockCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)955*67e74705SXin Li RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
956*67e74705SXin Li                                           ReturnValueSlot ReturnValue) {
957*67e74705SXin Li   const BlockPointerType *BPT =
958*67e74705SXin Li     E->getCallee()->getType()->getAs<BlockPointerType>();
959*67e74705SXin Li 
960*67e74705SXin Li   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
961*67e74705SXin Li 
962*67e74705SXin Li   // Get a pointer to the generic block literal.
963*67e74705SXin Li   llvm::Type *BlockLiteralTy =
964*67e74705SXin Li     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
965*67e74705SXin Li 
966*67e74705SXin Li   // Bitcast the callee to a block literal.
967*67e74705SXin Li   llvm::Value *BlockLiteral =
968*67e74705SXin Li     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
969*67e74705SXin Li 
970*67e74705SXin Li   // Get the function pointer from the literal.
971*67e74705SXin Li   llvm::Value *FuncPtr =
972*67e74705SXin Li     Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
973*67e74705SXin Li 
974*67e74705SXin Li   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
975*67e74705SXin Li 
976*67e74705SXin Li   // Add the block literal.
977*67e74705SXin Li   CallArgList Args;
978*67e74705SXin Li   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
979*67e74705SXin Li 
980*67e74705SXin Li   QualType FnType = BPT->getPointeeType();
981*67e74705SXin Li 
982*67e74705SXin Li   // And the rest of the arguments.
983*67e74705SXin Li   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
984*67e74705SXin Li 
985*67e74705SXin Li   // Load the function.
986*67e74705SXin Li   llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
987*67e74705SXin Li 
988*67e74705SXin Li   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
989*67e74705SXin Li   const CGFunctionInfo &FnInfo =
990*67e74705SXin Li     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
991*67e74705SXin Li 
992*67e74705SXin Li   // Cast the function pointer to the right type.
993*67e74705SXin Li   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
994*67e74705SXin Li 
995*67e74705SXin Li   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
996*67e74705SXin Li   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
997*67e74705SXin Li 
998*67e74705SXin Li   // And call the block.
999*67e74705SXin Li   return EmitCall(FnInfo, Func, ReturnValue, Args);
1000*67e74705SXin Li }
1001*67e74705SXin Li 
GetAddrOfBlockDecl(const VarDecl * variable,bool isByRef)1002*67e74705SXin Li Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1003*67e74705SXin Li                                             bool isByRef) {
1004*67e74705SXin Li   assert(BlockInfo && "evaluating block ref without block information?");
1005*67e74705SXin Li   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1006*67e74705SXin Li 
1007*67e74705SXin Li   // Handle constant captures.
1008*67e74705SXin Li   if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1009*67e74705SXin Li 
1010*67e74705SXin Li   Address addr =
1011*67e74705SXin Li     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1012*67e74705SXin Li                             capture.getOffset(), "block.capture.addr");
1013*67e74705SXin Li 
1014*67e74705SXin Li   if (isByRef) {
1015*67e74705SXin Li     // addr should be a void** right now.  Load, then cast the result
1016*67e74705SXin Li     // to byref*.
1017*67e74705SXin Li 
1018*67e74705SXin Li     auto &byrefInfo = getBlockByrefInfo(variable);
1019*67e74705SXin Li     addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1020*67e74705SXin Li 
1021*67e74705SXin Li     auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1022*67e74705SXin Li     addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1023*67e74705SXin Li 
1024*67e74705SXin Li     addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1025*67e74705SXin Li                                  variable->getName());
1026*67e74705SXin Li   }
1027*67e74705SXin Li 
1028*67e74705SXin Li   if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1029*67e74705SXin Li     addr = EmitLoadOfReference(addr, refType);
1030*67e74705SXin Li   }
1031*67e74705SXin Li 
1032*67e74705SXin Li   return addr;
1033*67e74705SXin Li }
1034*67e74705SXin Li 
1035*67e74705SXin Li llvm::Constant *
GetAddrOfGlobalBlock(const BlockExpr * blockExpr,const char * name)1036*67e74705SXin Li CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1037*67e74705SXin Li                                     const char *name) {
1038*67e74705SXin Li   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1039*67e74705SXin Li   blockInfo.BlockExpression = blockExpr;
1040*67e74705SXin Li 
1041*67e74705SXin Li   // Compute information about the layout, etc., of this block.
1042*67e74705SXin Li   computeBlockInfo(*this, nullptr, blockInfo);
1043*67e74705SXin Li 
1044*67e74705SXin Li   // Using that metadata, generate the actual block function.
1045*67e74705SXin Li   llvm::Constant *blockFn;
1046*67e74705SXin Li   {
1047*67e74705SXin Li     CodeGenFunction::DeclMapTy LocalDeclMap;
1048*67e74705SXin Li     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1049*67e74705SXin Li                                                            blockInfo,
1050*67e74705SXin Li                                                            LocalDeclMap,
1051*67e74705SXin Li                                                            false);
1052*67e74705SXin Li   }
1053*67e74705SXin Li   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1054*67e74705SXin Li 
1055*67e74705SXin Li   return buildGlobalBlock(*this, blockInfo, blockFn);
1056*67e74705SXin Li }
1057*67e74705SXin Li 
buildGlobalBlock(CodeGenModule & CGM,const CGBlockInfo & blockInfo,llvm::Constant * blockFn)1058*67e74705SXin Li static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1059*67e74705SXin Li                                         const CGBlockInfo &blockInfo,
1060*67e74705SXin Li                                         llvm::Constant *blockFn) {
1061*67e74705SXin Li   assert(blockInfo.CanBeGlobal);
1062*67e74705SXin Li 
1063*67e74705SXin Li   // Generate the constants for the block literal initializer.
1064*67e74705SXin Li   llvm::Constant *fields[BlockHeaderSize];
1065*67e74705SXin Li 
1066*67e74705SXin Li   // isa
1067*67e74705SXin Li   fields[0] = CGM.getNSConcreteGlobalBlock();
1068*67e74705SXin Li 
1069*67e74705SXin Li   // __flags
1070*67e74705SXin Li   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1071*67e74705SXin Li   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1072*67e74705SXin Li 
1073*67e74705SXin Li   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1074*67e74705SXin Li 
1075*67e74705SXin Li   // Reserved
1076*67e74705SXin Li   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1077*67e74705SXin Li 
1078*67e74705SXin Li   // Function
1079*67e74705SXin Li   fields[3] = blockFn;
1080*67e74705SXin Li 
1081*67e74705SXin Li   // Descriptor
1082*67e74705SXin Li   fields[4] = buildBlockDescriptor(CGM, blockInfo);
1083*67e74705SXin Li 
1084*67e74705SXin Li   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1085*67e74705SXin Li 
1086*67e74705SXin Li   llvm::GlobalVariable *literal =
1087*67e74705SXin Li     new llvm::GlobalVariable(CGM.getModule(),
1088*67e74705SXin Li                              init->getType(),
1089*67e74705SXin Li                              /*constant*/ true,
1090*67e74705SXin Li                              llvm::GlobalVariable::InternalLinkage,
1091*67e74705SXin Li                              init,
1092*67e74705SXin Li                              "__block_literal_global");
1093*67e74705SXin Li   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1094*67e74705SXin Li 
1095*67e74705SXin Li   // Return a constant of the appropriately-casted type.
1096*67e74705SXin Li   llvm::Type *requiredType =
1097*67e74705SXin Li     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1098*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(literal, requiredType);
1099*67e74705SXin Li }
1100*67e74705SXin Li 
setBlockContextParameter(const ImplicitParamDecl * D,unsigned argNum,llvm::Value * arg)1101*67e74705SXin Li void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1102*67e74705SXin Li                                                unsigned argNum,
1103*67e74705SXin Li                                                llvm::Value *arg) {
1104*67e74705SXin Li   assert(BlockInfo && "not emitting prologue of block invocation function?!");
1105*67e74705SXin Li 
1106*67e74705SXin Li   llvm::Value *localAddr = nullptr;
1107*67e74705SXin Li   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1108*67e74705SXin Li     // Allocate a stack slot to let the debug info survive the RA.
1109*67e74705SXin Li     Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1110*67e74705SXin Li     Builder.CreateStore(arg, alloc);
1111*67e74705SXin Li     localAddr = Builder.CreateLoad(alloc);
1112*67e74705SXin Li   }
1113*67e74705SXin Li 
1114*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo()) {
1115*67e74705SXin Li     if (CGM.getCodeGenOpts().getDebugInfo() >=
1116*67e74705SXin Li         codegenoptions::LimitedDebugInfo) {
1117*67e74705SXin Li       DI->setLocation(D->getLocation());
1118*67e74705SXin Li       DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1119*67e74705SXin Li                                                localAddr, Builder);
1120*67e74705SXin Li     }
1121*67e74705SXin Li   }
1122*67e74705SXin Li 
1123*67e74705SXin Li   SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1124*67e74705SXin Li   ApplyDebugLocation Scope(*this, StartLoc);
1125*67e74705SXin Li 
1126*67e74705SXin Li   // Instead of messing around with LocalDeclMap, just set the value
1127*67e74705SXin Li   // directly as BlockPointer.
1128*67e74705SXin Li   BlockPointer = Builder.CreateBitCast(arg,
1129*67e74705SXin Li                                        BlockInfo->StructureType->getPointerTo(),
1130*67e74705SXin Li                                        "block");
1131*67e74705SXin Li }
1132*67e74705SXin Li 
LoadBlockStruct()1133*67e74705SXin Li Address CodeGenFunction::LoadBlockStruct() {
1134*67e74705SXin Li   assert(BlockInfo && "not in a block invocation function!");
1135*67e74705SXin Li   assert(BlockPointer && "no block pointer set!");
1136*67e74705SXin Li   return Address(BlockPointer, BlockInfo->BlockAlign);
1137*67e74705SXin Li }
1138*67e74705SXin Li 
1139*67e74705SXin Li llvm::Function *
GenerateBlockFunction(GlobalDecl GD,const CGBlockInfo & blockInfo,const DeclMapTy & ldm,bool IsLambdaConversionToBlock)1140*67e74705SXin Li CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1141*67e74705SXin Li                                        const CGBlockInfo &blockInfo,
1142*67e74705SXin Li                                        const DeclMapTy &ldm,
1143*67e74705SXin Li                                        bool IsLambdaConversionToBlock) {
1144*67e74705SXin Li   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1145*67e74705SXin Li 
1146*67e74705SXin Li   CurGD = GD;
1147*67e74705SXin Li 
1148*67e74705SXin Li   CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1149*67e74705SXin Li 
1150*67e74705SXin Li   BlockInfo = &blockInfo;
1151*67e74705SXin Li 
1152*67e74705SXin Li   // Arrange for local static and local extern declarations to appear
1153*67e74705SXin Li   // to be local to this function as well, in case they're directly
1154*67e74705SXin Li   // referenced in a block.
1155*67e74705SXin Li   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1156*67e74705SXin Li     const auto *var = dyn_cast<VarDecl>(i->first);
1157*67e74705SXin Li     if (var && !var->hasLocalStorage())
1158*67e74705SXin Li       setAddrOfLocalVar(var, i->second);
1159*67e74705SXin Li   }
1160*67e74705SXin Li 
1161*67e74705SXin Li   // Begin building the function declaration.
1162*67e74705SXin Li 
1163*67e74705SXin Li   // Build the argument list.
1164*67e74705SXin Li   FunctionArgList args;
1165*67e74705SXin Li 
1166*67e74705SXin Li   // The first argument is the block pointer.  Just take it as a void*
1167*67e74705SXin Li   // and cast it later.
1168*67e74705SXin Li   QualType selfTy = getContext().VoidPtrTy;
1169*67e74705SXin Li   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1170*67e74705SXin Li 
1171*67e74705SXin Li   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1172*67e74705SXin Li                              SourceLocation(), II, selfTy);
1173*67e74705SXin Li   args.push_back(&selfDecl);
1174*67e74705SXin Li 
1175*67e74705SXin Li   // Now add the rest of the parameters.
1176*67e74705SXin Li   args.append(blockDecl->param_begin(), blockDecl->param_end());
1177*67e74705SXin Li 
1178*67e74705SXin Li   // Create the function declaration.
1179*67e74705SXin Li   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1180*67e74705SXin Li   const CGFunctionInfo &fnInfo =
1181*67e74705SXin Li     CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1182*67e74705SXin Li   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1183*67e74705SXin Li     blockInfo.UsesStret = true;
1184*67e74705SXin Li 
1185*67e74705SXin Li   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1186*67e74705SXin Li 
1187*67e74705SXin Li   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1188*67e74705SXin Li   llvm::Function *fn = llvm::Function::Create(
1189*67e74705SXin Li       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1190*67e74705SXin Li   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1191*67e74705SXin Li 
1192*67e74705SXin Li   // Begin generating the function.
1193*67e74705SXin Li   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1194*67e74705SXin Li                 blockDecl->getLocation(),
1195*67e74705SXin Li                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1196*67e74705SXin Li 
1197*67e74705SXin Li   // Okay.  Undo some of what StartFunction did.
1198*67e74705SXin Li 
1199*67e74705SXin Li   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1200*67e74705SXin Li   // won't delete the dbg.declare intrinsics for captured variables.
1201*67e74705SXin Li   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1202*67e74705SXin Li   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1203*67e74705SXin Li     // Allocate a stack slot for it, so we can point the debugger to it
1204*67e74705SXin Li     Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1205*67e74705SXin Li                                       getPointerAlign(),
1206*67e74705SXin Li                                       "block.addr");
1207*67e74705SXin Li     // Set the DebugLocation to empty, so the store is recognized as a
1208*67e74705SXin Li     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1209*67e74705SXin Li     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1210*67e74705SXin Li     Builder.CreateStore(BlockPointer, Alloca);
1211*67e74705SXin Li     BlockPointerDbgLoc = Alloca.getPointer();
1212*67e74705SXin Li   }
1213*67e74705SXin Li 
1214*67e74705SXin Li   // If we have a C++ 'this' reference, go ahead and force it into
1215*67e74705SXin Li   // existence now.
1216*67e74705SXin Li   if (blockDecl->capturesCXXThis()) {
1217*67e74705SXin Li     Address addr =
1218*67e74705SXin Li       Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1219*67e74705SXin Li                               blockInfo.CXXThisOffset, "block.captured-this");
1220*67e74705SXin Li     CXXThisValue = Builder.CreateLoad(addr, "this");
1221*67e74705SXin Li   }
1222*67e74705SXin Li 
1223*67e74705SXin Li   // Also force all the constant captures.
1224*67e74705SXin Li   for (const auto &CI : blockDecl->captures()) {
1225*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
1226*67e74705SXin Li     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1227*67e74705SXin Li     if (!capture.isConstant()) continue;
1228*67e74705SXin Li 
1229*67e74705SXin Li     CharUnits align = getContext().getDeclAlign(variable);
1230*67e74705SXin Li     Address alloca =
1231*67e74705SXin Li       CreateMemTemp(variable->getType(), align, "block.captured-const");
1232*67e74705SXin Li 
1233*67e74705SXin Li     Builder.CreateStore(capture.getConstant(), alloca);
1234*67e74705SXin Li 
1235*67e74705SXin Li     setAddrOfLocalVar(variable, alloca);
1236*67e74705SXin Li   }
1237*67e74705SXin Li 
1238*67e74705SXin Li   // Save a spot to insert the debug information for all the DeclRefExprs.
1239*67e74705SXin Li   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1240*67e74705SXin Li   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1241*67e74705SXin Li   --entry_ptr;
1242*67e74705SXin Li 
1243*67e74705SXin Li   if (IsLambdaConversionToBlock)
1244*67e74705SXin Li     EmitLambdaBlockInvokeBody();
1245*67e74705SXin Li   else {
1246*67e74705SXin Li     PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1247*67e74705SXin Li     incrementProfileCounter(blockDecl->getBody());
1248*67e74705SXin Li     EmitStmt(blockDecl->getBody());
1249*67e74705SXin Li   }
1250*67e74705SXin Li 
1251*67e74705SXin Li   // Remember where we were...
1252*67e74705SXin Li   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1253*67e74705SXin Li 
1254*67e74705SXin Li   // Go back to the entry.
1255*67e74705SXin Li   ++entry_ptr;
1256*67e74705SXin Li   Builder.SetInsertPoint(entry, entry_ptr);
1257*67e74705SXin Li 
1258*67e74705SXin Li   // Emit debug information for all the DeclRefExprs.
1259*67e74705SXin Li   // FIXME: also for 'this'
1260*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo()) {
1261*67e74705SXin Li     for (const auto &CI : blockDecl->captures()) {
1262*67e74705SXin Li       const VarDecl *variable = CI.getVariable();
1263*67e74705SXin Li       DI->EmitLocation(Builder, variable->getLocation());
1264*67e74705SXin Li 
1265*67e74705SXin Li       if (CGM.getCodeGenOpts().getDebugInfo() >=
1266*67e74705SXin Li           codegenoptions::LimitedDebugInfo) {
1267*67e74705SXin Li         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1268*67e74705SXin Li         if (capture.isConstant()) {
1269*67e74705SXin Li           auto addr = LocalDeclMap.find(variable)->second;
1270*67e74705SXin Li           DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1271*67e74705SXin Li                                         Builder);
1272*67e74705SXin Li           continue;
1273*67e74705SXin Li         }
1274*67e74705SXin Li 
1275*67e74705SXin Li         DI->EmitDeclareOfBlockDeclRefVariable(
1276*67e74705SXin Li             variable, BlockPointerDbgLoc, Builder, blockInfo,
1277*67e74705SXin Li             entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1278*67e74705SXin Li       }
1279*67e74705SXin Li     }
1280*67e74705SXin Li     // Recover location if it was changed in the above loop.
1281*67e74705SXin Li     DI->EmitLocation(Builder,
1282*67e74705SXin Li                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1283*67e74705SXin Li   }
1284*67e74705SXin Li 
1285*67e74705SXin Li   // And resume where we left off.
1286*67e74705SXin Li   if (resume == nullptr)
1287*67e74705SXin Li     Builder.ClearInsertionPoint();
1288*67e74705SXin Li   else
1289*67e74705SXin Li     Builder.SetInsertPoint(resume);
1290*67e74705SXin Li 
1291*67e74705SXin Li   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1292*67e74705SXin Li 
1293*67e74705SXin Li   return fn;
1294*67e74705SXin Li }
1295*67e74705SXin Li 
1296*67e74705SXin Li /*
1297*67e74705SXin Li     notes.push_back(HelperInfo());
1298*67e74705SXin Li     HelperInfo &note = notes.back();
1299*67e74705SXin Li     note.index = capture.getIndex();
1300*67e74705SXin Li     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1301*67e74705SXin Li     note.cxxbar_import = ci->getCopyExpr();
1302*67e74705SXin Li 
1303*67e74705SXin Li     if (ci->isByRef()) {
1304*67e74705SXin Li       note.flag = BLOCK_FIELD_IS_BYREF;
1305*67e74705SXin Li       if (type.isObjCGCWeak())
1306*67e74705SXin Li         note.flag |= BLOCK_FIELD_IS_WEAK;
1307*67e74705SXin Li     } else if (type->isBlockPointerType()) {
1308*67e74705SXin Li       note.flag = BLOCK_FIELD_IS_BLOCK;
1309*67e74705SXin Li     } else {
1310*67e74705SXin Li       note.flag = BLOCK_FIELD_IS_OBJECT;
1311*67e74705SXin Li     }
1312*67e74705SXin Li  */
1313*67e74705SXin Li 
1314*67e74705SXin Li /// Generate the copy-helper function for a block closure object:
1315*67e74705SXin Li ///   static void block_copy_helper(block_t *dst, block_t *src);
1316*67e74705SXin Li /// The runtime will have previously initialized 'dst' by doing a
1317*67e74705SXin Li /// bit-copy of 'src'.
1318*67e74705SXin Li ///
1319*67e74705SXin Li /// Note that this copies an entire block closure object to the heap;
1320*67e74705SXin Li /// it should not be confused with a 'byref copy helper', which moves
1321*67e74705SXin Li /// the contents of an individual __block variable to the heap.
1322*67e74705SXin Li llvm::Constant *
GenerateCopyHelperFunction(const CGBlockInfo & blockInfo)1323*67e74705SXin Li CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1324*67e74705SXin Li   ASTContext &C = getContext();
1325*67e74705SXin Li 
1326*67e74705SXin Li   FunctionArgList args;
1327*67e74705SXin Li   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1328*67e74705SXin Li                             C.VoidPtrTy);
1329*67e74705SXin Li   args.push_back(&dstDecl);
1330*67e74705SXin Li   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1331*67e74705SXin Li                             C.VoidPtrTy);
1332*67e74705SXin Li   args.push_back(&srcDecl);
1333*67e74705SXin Li 
1334*67e74705SXin Li   const CGFunctionInfo &FI =
1335*67e74705SXin Li     CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1336*67e74705SXin Li 
1337*67e74705SXin Li   // FIXME: it would be nice if these were mergeable with things with
1338*67e74705SXin Li   // identical semantics.
1339*67e74705SXin Li   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1340*67e74705SXin Li 
1341*67e74705SXin Li   llvm::Function *Fn =
1342*67e74705SXin Li     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1343*67e74705SXin Li                            "__copy_helper_block_", &CGM.getModule());
1344*67e74705SXin Li 
1345*67e74705SXin Li   IdentifierInfo *II
1346*67e74705SXin Li     = &CGM.getContext().Idents.get("__copy_helper_block_");
1347*67e74705SXin Li 
1348*67e74705SXin Li   FunctionDecl *FD = FunctionDecl::Create(C,
1349*67e74705SXin Li                                           C.getTranslationUnitDecl(),
1350*67e74705SXin Li                                           SourceLocation(),
1351*67e74705SXin Li                                           SourceLocation(), II, C.VoidTy,
1352*67e74705SXin Li                                           nullptr, SC_Static,
1353*67e74705SXin Li                                           false,
1354*67e74705SXin Li                                           false);
1355*67e74705SXin Li 
1356*67e74705SXin Li   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1357*67e74705SXin Li 
1358*67e74705SXin Li   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1359*67e74705SXin Li   StartFunction(FD, C.VoidTy, Fn, FI, args);
1360*67e74705SXin Li   // Create a scope with an artificial location for the body of this function.
1361*67e74705SXin Li   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1362*67e74705SXin Li   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1363*67e74705SXin Li 
1364*67e74705SXin Li   Address src = GetAddrOfLocalVar(&srcDecl);
1365*67e74705SXin Li   src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1366*67e74705SXin Li   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1367*67e74705SXin Li 
1368*67e74705SXin Li   Address dst = GetAddrOfLocalVar(&dstDecl);
1369*67e74705SXin Li   dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1370*67e74705SXin Li   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1371*67e74705SXin Li 
1372*67e74705SXin Li   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1373*67e74705SXin Li 
1374*67e74705SXin Li   for (const auto &CI : blockDecl->captures()) {
1375*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
1376*67e74705SXin Li     QualType type = variable->getType();
1377*67e74705SXin Li 
1378*67e74705SXin Li     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1379*67e74705SXin Li     if (capture.isConstant()) continue;
1380*67e74705SXin Li 
1381*67e74705SXin Li     const Expr *copyExpr = CI.getCopyExpr();
1382*67e74705SXin Li     BlockFieldFlags flags;
1383*67e74705SXin Li 
1384*67e74705SXin Li     bool useARCWeakCopy = false;
1385*67e74705SXin Li     bool useARCStrongCopy = false;
1386*67e74705SXin Li 
1387*67e74705SXin Li     if (copyExpr) {
1388*67e74705SXin Li       assert(!CI.isByRef());
1389*67e74705SXin Li       // don't bother computing flags
1390*67e74705SXin Li 
1391*67e74705SXin Li     } else if (CI.isByRef()) {
1392*67e74705SXin Li       flags = BLOCK_FIELD_IS_BYREF;
1393*67e74705SXin Li       if (type.isObjCGCWeak())
1394*67e74705SXin Li         flags |= BLOCK_FIELD_IS_WEAK;
1395*67e74705SXin Li 
1396*67e74705SXin Li     } else if (type->isObjCRetainableType()) {
1397*67e74705SXin Li       flags = BLOCK_FIELD_IS_OBJECT;
1398*67e74705SXin Li       bool isBlockPointer = type->isBlockPointerType();
1399*67e74705SXin Li       if (isBlockPointer)
1400*67e74705SXin Li         flags = BLOCK_FIELD_IS_BLOCK;
1401*67e74705SXin Li 
1402*67e74705SXin Li       // Special rules for ARC captures:
1403*67e74705SXin Li       Qualifiers qs = type.getQualifiers();
1404*67e74705SXin Li 
1405*67e74705SXin Li       // We need to register __weak direct captures with the runtime.
1406*67e74705SXin Li       if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1407*67e74705SXin Li         useARCWeakCopy = true;
1408*67e74705SXin Li 
1409*67e74705SXin Li       // We need to retain the copied value for __strong direct captures.
1410*67e74705SXin Li       } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1411*67e74705SXin Li         // If it's a block pointer, we have to copy the block and
1412*67e74705SXin Li         // assign that to the destination pointer, so we might as
1413*67e74705SXin Li         // well use _Block_object_assign.  Otherwise we can avoid that.
1414*67e74705SXin Li         if (!isBlockPointer)
1415*67e74705SXin Li           useARCStrongCopy = true;
1416*67e74705SXin Li 
1417*67e74705SXin Li       // Non-ARC captures of retainable pointers are strong and
1418*67e74705SXin Li       // therefore require a call to _Block_object_assign.
1419*67e74705SXin Li       } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1420*67e74705SXin Li         // fall through
1421*67e74705SXin Li 
1422*67e74705SXin Li       // Otherwise the memcpy is fine.
1423*67e74705SXin Li       } else {
1424*67e74705SXin Li         continue;
1425*67e74705SXin Li       }
1426*67e74705SXin Li 
1427*67e74705SXin Li     // For all other types, the memcpy is fine.
1428*67e74705SXin Li     } else {
1429*67e74705SXin Li       continue;
1430*67e74705SXin Li     }
1431*67e74705SXin Li 
1432*67e74705SXin Li     unsigned index = capture.getIndex();
1433*67e74705SXin Li     Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1434*67e74705SXin Li     Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1435*67e74705SXin Li 
1436*67e74705SXin Li     // If there's an explicit copy expression, we do that.
1437*67e74705SXin Li     if (copyExpr) {
1438*67e74705SXin Li       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1439*67e74705SXin Li     } else if (useARCWeakCopy) {
1440*67e74705SXin Li       EmitARCCopyWeak(dstField, srcField);
1441*67e74705SXin Li     } else {
1442*67e74705SXin Li       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1443*67e74705SXin Li       if (useARCStrongCopy) {
1444*67e74705SXin Li         // At -O0, store null into the destination field (so that the
1445*67e74705SXin Li         // storeStrong doesn't over-release) and then call storeStrong.
1446*67e74705SXin Li         // This is a workaround to not having an initStrong call.
1447*67e74705SXin Li         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1448*67e74705SXin Li           auto *ty = cast<llvm::PointerType>(srcValue->getType());
1449*67e74705SXin Li           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1450*67e74705SXin Li           Builder.CreateStore(null, dstField);
1451*67e74705SXin Li           EmitARCStoreStrongCall(dstField, srcValue, true);
1452*67e74705SXin Li 
1453*67e74705SXin Li         // With optimization enabled, take advantage of the fact that
1454*67e74705SXin Li         // the blocks runtime guarantees a memcpy of the block data, and
1455*67e74705SXin Li         // just emit a retain of the src field.
1456*67e74705SXin Li         } else {
1457*67e74705SXin Li           EmitARCRetainNonBlock(srcValue);
1458*67e74705SXin Li 
1459*67e74705SXin Li           // We don't need this anymore, so kill it.  It's not quite
1460*67e74705SXin Li           // worth the annoyance to avoid creating it in the first place.
1461*67e74705SXin Li           cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1462*67e74705SXin Li         }
1463*67e74705SXin Li       } else {
1464*67e74705SXin Li         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1465*67e74705SXin Li         llvm::Value *dstAddr =
1466*67e74705SXin Li           Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1467*67e74705SXin Li         llvm::Value *args[] = {
1468*67e74705SXin Li           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1469*67e74705SXin Li         };
1470*67e74705SXin Li 
1471*67e74705SXin Li         bool copyCanThrow = false;
1472*67e74705SXin Li         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1473*67e74705SXin Li           const Expr *copyExpr =
1474*67e74705SXin Li             CGM.getContext().getBlockVarCopyInits(variable);
1475*67e74705SXin Li           if (copyExpr) {
1476*67e74705SXin Li             copyCanThrow = true; // FIXME: reuse the noexcept logic
1477*67e74705SXin Li           }
1478*67e74705SXin Li         }
1479*67e74705SXin Li 
1480*67e74705SXin Li         if (copyCanThrow) {
1481*67e74705SXin Li           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1482*67e74705SXin Li         } else {
1483*67e74705SXin Li           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1484*67e74705SXin Li         }
1485*67e74705SXin Li       }
1486*67e74705SXin Li     }
1487*67e74705SXin Li   }
1488*67e74705SXin Li 
1489*67e74705SXin Li   FinishFunction();
1490*67e74705SXin Li 
1491*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1492*67e74705SXin Li }
1493*67e74705SXin Li 
1494*67e74705SXin Li /// Generate the destroy-helper function for a block closure object:
1495*67e74705SXin Li ///   static void block_destroy_helper(block_t *theBlock);
1496*67e74705SXin Li ///
1497*67e74705SXin Li /// Note that this destroys a heap-allocated block closure object;
1498*67e74705SXin Li /// it should not be confused with a 'byref destroy helper', which
1499*67e74705SXin Li /// destroys the heap-allocated contents of an individual __block
1500*67e74705SXin Li /// variable.
1501*67e74705SXin Li llvm::Constant *
GenerateDestroyHelperFunction(const CGBlockInfo & blockInfo)1502*67e74705SXin Li CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1503*67e74705SXin Li   ASTContext &C = getContext();
1504*67e74705SXin Li 
1505*67e74705SXin Li   FunctionArgList args;
1506*67e74705SXin Li   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1507*67e74705SXin Li                             C.VoidPtrTy);
1508*67e74705SXin Li   args.push_back(&srcDecl);
1509*67e74705SXin Li 
1510*67e74705SXin Li   const CGFunctionInfo &FI =
1511*67e74705SXin Li     CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1512*67e74705SXin Li 
1513*67e74705SXin Li   // FIXME: We'd like to put these into a mergable by content, with
1514*67e74705SXin Li   // internal linkage.
1515*67e74705SXin Li   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1516*67e74705SXin Li 
1517*67e74705SXin Li   llvm::Function *Fn =
1518*67e74705SXin Li     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1519*67e74705SXin Li                            "__destroy_helper_block_", &CGM.getModule());
1520*67e74705SXin Li 
1521*67e74705SXin Li   IdentifierInfo *II
1522*67e74705SXin Li     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1523*67e74705SXin Li 
1524*67e74705SXin Li   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1525*67e74705SXin Li                                           SourceLocation(),
1526*67e74705SXin Li                                           SourceLocation(), II, C.VoidTy,
1527*67e74705SXin Li                                           nullptr, SC_Static,
1528*67e74705SXin Li                                           false, false);
1529*67e74705SXin Li 
1530*67e74705SXin Li   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1531*67e74705SXin Li 
1532*67e74705SXin Li   // Create a scope with an artificial location for the body of this function.
1533*67e74705SXin Li   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1534*67e74705SXin Li   StartFunction(FD, C.VoidTy, Fn, FI, args);
1535*67e74705SXin Li   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1536*67e74705SXin Li 
1537*67e74705SXin Li   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1538*67e74705SXin Li 
1539*67e74705SXin Li   Address src = GetAddrOfLocalVar(&srcDecl);
1540*67e74705SXin Li   src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1541*67e74705SXin Li   src = Builder.CreateBitCast(src, structPtrTy, "block");
1542*67e74705SXin Li 
1543*67e74705SXin Li   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1544*67e74705SXin Li 
1545*67e74705SXin Li   CodeGenFunction::RunCleanupsScope cleanups(*this);
1546*67e74705SXin Li 
1547*67e74705SXin Li   for (const auto &CI : blockDecl->captures()) {
1548*67e74705SXin Li     const VarDecl *variable = CI.getVariable();
1549*67e74705SXin Li     QualType type = variable->getType();
1550*67e74705SXin Li 
1551*67e74705SXin Li     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1552*67e74705SXin Li     if (capture.isConstant()) continue;
1553*67e74705SXin Li 
1554*67e74705SXin Li     BlockFieldFlags flags;
1555*67e74705SXin Li     const CXXDestructorDecl *dtor = nullptr;
1556*67e74705SXin Li 
1557*67e74705SXin Li     bool useARCWeakDestroy = false;
1558*67e74705SXin Li     bool useARCStrongDestroy = false;
1559*67e74705SXin Li 
1560*67e74705SXin Li     if (CI.isByRef()) {
1561*67e74705SXin Li       flags = BLOCK_FIELD_IS_BYREF;
1562*67e74705SXin Li       if (type.isObjCGCWeak())
1563*67e74705SXin Li         flags |= BLOCK_FIELD_IS_WEAK;
1564*67e74705SXin Li     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1565*67e74705SXin Li       if (record->hasTrivialDestructor())
1566*67e74705SXin Li         continue;
1567*67e74705SXin Li       dtor = record->getDestructor();
1568*67e74705SXin Li     } else if (type->isObjCRetainableType()) {
1569*67e74705SXin Li       flags = BLOCK_FIELD_IS_OBJECT;
1570*67e74705SXin Li       if (type->isBlockPointerType())
1571*67e74705SXin Li         flags = BLOCK_FIELD_IS_BLOCK;
1572*67e74705SXin Li 
1573*67e74705SXin Li       // Special rules for ARC captures.
1574*67e74705SXin Li       Qualifiers qs = type.getQualifiers();
1575*67e74705SXin Li 
1576*67e74705SXin Li       // Use objc_storeStrong for __strong direct captures; the
1577*67e74705SXin Li       // dynamic tools really like it when we do this.
1578*67e74705SXin Li       if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1579*67e74705SXin Li         useARCStrongDestroy = true;
1580*67e74705SXin Li 
1581*67e74705SXin Li       // Support __weak direct captures.
1582*67e74705SXin Li       } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1583*67e74705SXin Li         useARCWeakDestroy = true;
1584*67e74705SXin Li 
1585*67e74705SXin Li       // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1586*67e74705SXin Li       } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1587*67e74705SXin Li         // fall through
1588*67e74705SXin Li 
1589*67e74705SXin Li       // Otherwise, we have nothing to do.
1590*67e74705SXin Li       } else {
1591*67e74705SXin Li         continue;
1592*67e74705SXin Li       }
1593*67e74705SXin Li     } else {
1594*67e74705SXin Li       continue;
1595*67e74705SXin Li     }
1596*67e74705SXin Li 
1597*67e74705SXin Li     Address srcField =
1598*67e74705SXin Li       Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1599*67e74705SXin Li 
1600*67e74705SXin Li     // If there's an explicit copy expression, we do that.
1601*67e74705SXin Li     if (dtor) {
1602*67e74705SXin Li       PushDestructorCleanup(dtor, srcField);
1603*67e74705SXin Li 
1604*67e74705SXin Li     // If this is a __weak capture, emit the release directly.
1605*67e74705SXin Li     } else if (useARCWeakDestroy) {
1606*67e74705SXin Li       EmitARCDestroyWeak(srcField);
1607*67e74705SXin Li 
1608*67e74705SXin Li     // Destroy strong objects with a call if requested.
1609*67e74705SXin Li     } else if (useARCStrongDestroy) {
1610*67e74705SXin Li       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1611*67e74705SXin Li 
1612*67e74705SXin Li     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1613*67e74705SXin Li     // hard to just emit this as a cleanup if we wanted to make sure
1614*67e74705SXin Li     // that things were done in reverse.
1615*67e74705SXin Li     } else {
1616*67e74705SXin Li       llvm::Value *value = Builder.CreateLoad(srcField);
1617*67e74705SXin Li       value = Builder.CreateBitCast(value, VoidPtrTy);
1618*67e74705SXin Li       BuildBlockRelease(value, flags);
1619*67e74705SXin Li     }
1620*67e74705SXin Li   }
1621*67e74705SXin Li 
1622*67e74705SXin Li   cleanups.ForceCleanup();
1623*67e74705SXin Li 
1624*67e74705SXin Li   FinishFunction();
1625*67e74705SXin Li 
1626*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1627*67e74705SXin Li }
1628*67e74705SXin Li 
1629*67e74705SXin Li namespace {
1630*67e74705SXin Li 
1631*67e74705SXin Li /// Emits the copy/dispose helper functions for a __block object of id type.
1632*67e74705SXin Li class ObjectByrefHelpers final : public BlockByrefHelpers {
1633*67e74705SXin Li   BlockFieldFlags Flags;
1634*67e74705SXin Li 
1635*67e74705SXin Li public:
ObjectByrefHelpers(CharUnits alignment,BlockFieldFlags flags)1636*67e74705SXin Li   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1637*67e74705SXin Li     : BlockByrefHelpers(alignment), Flags(flags) {}
1638*67e74705SXin Li 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)1639*67e74705SXin Li   void emitCopy(CodeGenFunction &CGF, Address destField,
1640*67e74705SXin Li                 Address srcField) override {
1641*67e74705SXin Li     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1642*67e74705SXin Li 
1643*67e74705SXin Li     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1644*67e74705SXin Li     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1645*67e74705SXin Li 
1646*67e74705SXin Li     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1647*67e74705SXin Li 
1648*67e74705SXin Li     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1649*67e74705SXin Li     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1650*67e74705SXin Li 
1651*67e74705SXin Li     llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1652*67e74705SXin Li     CGF.EmitNounwindRuntimeCall(fn, args);
1653*67e74705SXin Li   }
1654*67e74705SXin Li 
emitDispose(CodeGenFunction & CGF,Address field)1655*67e74705SXin Li   void emitDispose(CodeGenFunction &CGF, Address field) override {
1656*67e74705SXin Li     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1657*67e74705SXin Li     llvm::Value *value = CGF.Builder.CreateLoad(field);
1658*67e74705SXin Li 
1659*67e74705SXin Li     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1660*67e74705SXin Li   }
1661*67e74705SXin Li 
profileImpl(llvm::FoldingSetNodeID & id) const1662*67e74705SXin Li   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1663*67e74705SXin Li     id.AddInteger(Flags.getBitMask());
1664*67e74705SXin Li   }
1665*67e74705SXin Li };
1666*67e74705SXin Li 
1667*67e74705SXin Li /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1668*67e74705SXin Li class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1669*67e74705SXin Li public:
ARCWeakByrefHelpers(CharUnits alignment)1670*67e74705SXin Li   ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1671*67e74705SXin Li 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)1672*67e74705SXin Li   void emitCopy(CodeGenFunction &CGF, Address destField,
1673*67e74705SXin Li                 Address srcField) override {
1674*67e74705SXin Li     CGF.EmitARCMoveWeak(destField, srcField);
1675*67e74705SXin Li   }
1676*67e74705SXin Li 
emitDispose(CodeGenFunction & CGF,Address field)1677*67e74705SXin Li   void emitDispose(CodeGenFunction &CGF, Address field) override {
1678*67e74705SXin Li     CGF.EmitARCDestroyWeak(field);
1679*67e74705SXin Li   }
1680*67e74705SXin Li 
profileImpl(llvm::FoldingSetNodeID & id) const1681*67e74705SXin Li   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1682*67e74705SXin Li     // 0 is distinguishable from all pointers and byref flags
1683*67e74705SXin Li     id.AddInteger(0);
1684*67e74705SXin Li   }
1685*67e74705SXin Li };
1686*67e74705SXin Li 
1687*67e74705SXin Li /// Emits the copy/dispose helpers for an ARC __block __strong variable
1688*67e74705SXin Li /// that's not of block-pointer type.
1689*67e74705SXin Li class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1690*67e74705SXin Li public:
ARCStrongByrefHelpers(CharUnits alignment)1691*67e74705SXin Li   ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1692*67e74705SXin Li 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)1693*67e74705SXin Li   void emitCopy(CodeGenFunction &CGF, Address destField,
1694*67e74705SXin Li                 Address srcField) override {
1695*67e74705SXin Li     // Do a "move" by copying the value and then zeroing out the old
1696*67e74705SXin Li     // variable.
1697*67e74705SXin Li 
1698*67e74705SXin Li     llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1699*67e74705SXin Li 
1700*67e74705SXin Li     llvm::Value *null =
1701*67e74705SXin Li       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1702*67e74705SXin Li 
1703*67e74705SXin Li     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1704*67e74705SXin Li       CGF.Builder.CreateStore(null, destField);
1705*67e74705SXin Li       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1706*67e74705SXin Li       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1707*67e74705SXin Li       return;
1708*67e74705SXin Li     }
1709*67e74705SXin Li     CGF.Builder.CreateStore(value, destField);
1710*67e74705SXin Li     CGF.Builder.CreateStore(null, srcField);
1711*67e74705SXin Li   }
1712*67e74705SXin Li 
emitDispose(CodeGenFunction & CGF,Address field)1713*67e74705SXin Li   void emitDispose(CodeGenFunction &CGF, Address field) override {
1714*67e74705SXin Li     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1715*67e74705SXin Li   }
1716*67e74705SXin Li 
profileImpl(llvm::FoldingSetNodeID & id) const1717*67e74705SXin Li   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1718*67e74705SXin Li     // 1 is distinguishable from all pointers and byref flags
1719*67e74705SXin Li     id.AddInteger(1);
1720*67e74705SXin Li   }
1721*67e74705SXin Li };
1722*67e74705SXin Li 
1723*67e74705SXin Li /// Emits the copy/dispose helpers for an ARC __block __strong
1724*67e74705SXin Li /// variable that's of block-pointer type.
1725*67e74705SXin Li class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1726*67e74705SXin Li public:
ARCStrongBlockByrefHelpers(CharUnits alignment)1727*67e74705SXin Li   ARCStrongBlockByrefHelpers(CharUnits alignment)
1728*67e74705SXin Li     : BlockByrefHelpers(alignment) {}
1729*67e74705SXin Li 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)1730*67e74705SXin Li   void emitCopy(CodeGenFunction &CGF, Address destField,
1731*67e74705SXin Li                 Address srcField) override {
1732*67e74705SXin Li     // Do the copy with objc_retainBlock; that's all that
1733*67e74705SXin Li     // _Block_object_assign would do anyway, and we'd have to pass the
1734*67e74705SXin Li     // right arguments to make sure it doesn't get no-op'ed.
1735*67e74705SXin Li     llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1736*67e74705SXin Li     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1737*67e74705SXin Li     CGF.Builder.CreateStore(copy, destField);
1738*67e74705SXin Li   }
1739*67e74705SXin Li 
emitDispose(CodeGenFunction & CGF,Address field)1740*67e74705SXin Li   void emitDispose(CodeGenFunction &CGF, Address field) override {
1741*67e74705SXin Li     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1742*67e74705SXin Li   }
1743*67e74705SXin Li 
profileImpl(llvm::FoldingSetNodeID & id) const1744*67e74705SXin Li   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1745*67e74705SXin Li     // 2 is distinguishable from all pointers and byref flags
1746*67e74705SXin Li     id.AddInteger(2);
1747*67e74705SXin Li   }
1748*67e74705SXin Li };
1749*67e74705SXin Li 
1750*67e74705SXin Li /// Emits the copy/dispose helpers for a __block variable with a
1751*67e74705SXin Li /// nontrivial copy constructor or destructor.
1752*67e74705SXin Li class CXXByrefHelpers final : public BlockByrefHelpers {
1753*67e74705SXin Li   QualType VarType;
1754*67e74705SXin Li   const Expr *CopyExpr;
1755*67e74705SXin Li 
1756*67e74705SXin Li public:
CXXByrefHelpers(CharUnits alignment,QualType type,const Expr * copyExpr)1757*67e74705SXin Li   CXXByrefHelpers(CharUnits alignment, QualType type,
1758*67e74705SXin Li                   const Expr *copyExpr)
1759*67e74705SXin Li     : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1760*67e74705SXin Li 
needsCopy() const1761*67e74705SXin Li   bool needsCopy() const override { return CopyExpr != nullptr; }
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)1762*67e74705SXin Li   void emitCopy(CodeGenFunction &CGF, Address destField,
1763*67e74705SXin Li                 Address srcField) override {
1764*67e74705SXin Li     if (!CopyExpr) return;
1765*67e74705SXin Li     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1766*67e74705SXin Li   }
1767*67e74705SXin Li 
emitDispose(CodeGenFunction & CGF,Address field)1768*67e74705SXin Li   void emitDispose(CodeGenFunction &CGF, Address field) override {
1769*67e74705SXin Li     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1770*67e74705SXin Li     CGF.PushDestructorCleanup(VarType, field);
1771*67e74705SXin Li     CGF.PopCleanupBlocks(cleanupDepth);
1772*67e74705SXin Li   }
1773*67e74705SXin Li 
profileImpl(llvm::FoldingSetNodeID & id) const1774*67e74705SXin Li   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1775*67e74705SXin Li     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1776*67e74705SXin Li   }
1777*67e74705SXin Li };
1778*67e74705SXin Li } // end anonymous namespace
1779*67e74705SXin Li 
1780*67e74705SXin Li static llvm::Constant *
generateByrefCopyHelper(CodeGenFunction & CGF,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)1781*67e74705SXin Li generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1782*67e74705SXin Li                         BlockByrefHelpers &generator) {
1783*67e74705SXin Li   ASTContext &Context = CGF.getContext();
1784*67e74705SXin Li 
1785*67e74705SXin Li   QualType R = Context.VoidTy;
1786*67e74705SXin Li 
1787*67e74705SXin Li   FunctionArgList args;
1788*67e74705SXin Li   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1789*67e74705SXin Li                         Context.VoidPtrTy);
1790*67e74705SXin Li   args.push_back(&dst);
1791*67e74705SXin Li 
1792*67e74705SXin Li   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1793*67e74705SXin Li                         Context.VoidPtrTy);
1794*67e74705SXin Li   args.push_back(&src);
1795*67e74705SXin Li 
1796*67e74705SXin Li   const CGFunctionInfo &FI =
1797*67e74705SXin Li     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1798*67e74705SXin Li 
1799*67e74705SXin Li   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1800*67e74705SXin Li 
1801*67e74705SXin Li   // FIXME: We'd like to put these into a mergable by content, with
1802*67e74705SXin Li   // internal linkage.
1803*67e74705SXin Li   llvm::Function *Fn =
1804*67e74705SXin Li     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1805*67e74705SXin Li                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1806*67e74705SXin Li 
1807*67e74705SXin Li   IdentifierInfo *II
1808*67e74705SXin Li     = &Context.Idents.get("__Block_byref_object_copy_");
1809*67e74705SXin Li 
1810*67e74705SXin Li   FunctionDecl *FD = FunctionDecl::Create(Context,
1811*67e74705SXin Li                                           Context.getTranslationUnitDecl(),
1812*67e74705SXin Li                                           SourceLocation(),
1813*67e74705SXin Li                                           SourceLocation(), II, R, nullptr,
1814*67e74705SXin Li                                           SC_Static,
1815*67e74705SXin Li                                           false, false);
1816*67e74705SXin Li 
1817*67e74705SXin Li   CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1818*67e74705SXin Li 
1819*67e74705SXin Li   CGF.StartFunction(FD, R, Fn, FI, args);
1820*67e74705SXin Li 
1821*67e74705SXin Li   if (generator.needsCopy()) {
1822*67e74705SXin Li     llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1823*67e74705SXin Li 
1824*67e74705SXin Li     // dst->x
1825*67e74705SXin Li     Address destField = CGF.GetAddrOfLocalVar(&dst);
1826*67e74705SXin Li     destField = Address(CGF.Builder.CreateLoad(destField),
1827*67e74705SXin Li                         byrefInfo.ByrefAlignment);
1828*67e74705SXin Li     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1829*67e74705SXin Li     destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1830*67e74705SXin Li                                           "dest-object");
1831*67e74705SXin Li 
1832*67e74705SXin Li     // src->x
1833*67e74705SXin Li     Address srcField = CGF.GetAddrOfLocalVar(&src);
1834*67e74705SXin Li     srcField = Address(CGF.Builder.CreateLoad(srcField),
1835*67e74705SXin Li                        byrefInfo.ByrefAlignment);
1836*67e74705SXin Li     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1837*67e74705SXin Li     srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1838*67e74705SXin Li                                          "src-object");
1839*67e74705SXin Li 
1840*67e74705SXin Li     generator.emitCopy(CGF, destField, srcField);
1841*67e74705SXin Li   }
1842*67e74705SXin Li 
1843*67e74705SXin Li   CGF.FinishFunction();
1844*67e74705SXin Li 
1845*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1846*67e74705SXin Li }
1847*67e74705SXin Li 
1848*67e74705SXin Li /// Build the copy helper for a __block variable.
buildByrefCopyHelper(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)1849*67e74705SXin Li static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1850*67e74705SXin Li                                             const BlockByrefInfo &byrefInfo,
1851*67e74705SXin Li                                             BlockByrefHelpers &generator) {
1852*67e74705SXin Li   CodeGenFunction CGF(CGM);
1853*67e74705SXin Li   return generateByrefCopyHelper(CGF, byrefInfo, generator);
1854*67e74705SXin Li }
1855*67e74705SXin Li 
1856*67e74705SXin Li /// Generate code for a __block variable's dispose helper.
1857*67e74705SXin Li static llvm::Constant *
generateByrefDisposeHelper(CodeGenFunction & CGF,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)1858*67e74705SXin Li generateByrefDisposeHelper(CodeGenFunction &CGF,
1859*67e74705SXin Li                            const BlockByrefInfo &byrefInfo,
1860*67e74705SXin Li                            BlockByrefHelpers &generator) {
1861*67e74705SXin Li   ASTContext &Context = CGF.getContext();
1862*67e74705SXin Li   QualType R = Context.VoidTy;
1863*67e74705SXin Li 
1864*67e74705SXin Li   FunctionArgList args;
1865*67e74705SXin Li   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1866*67e74705SXin Li                         Context.VoidPtrTy);
1867*67e74705SXin Li   args.push_back(&src);
1868*67e74705SXin Li 
1869*67e74705SXin Li   const CGFunctionInfo &FI =
1870*67e74705SXin Li     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1871*67e74705SXin Li 
1872*67e74705SXin Li   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1873*67e74705SXin Li 
1874*67e74705SXin Li   // FIXME: We'd like to put these into a mergable by content, with
1875*67e74705SXin Li   // internal linkage.
1876*67e74705SXin Li   llvm::Function *Fn =
1877*67e74705SXin Li     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1878*67e74705SXin Li                            "__Block_byref_object_dispose_",
1879*67e74705SXin Li                            &CGF.CGM.getModule());
1880*67e74705SXin Li 
1881*67e74705SXin Li   IdentifierInfo *II
1882*67e74705SXin Li     = &Context.Idents.get("__Block_byref_object_dispose_");
1883*67e74705SXin Li 
1884*67e74705SXin Li   FunctionDecl *FD = FunctionDecl::Create(Context,
1885*67e74705SXin Li                                           Context.getTranslationUnitDecl(),
1886*67e74705SXin Li                                           SourceLocation(),
1887*67e74705SXin Li                                           SourceLocation(), II, R, nullptr,
1888*67e74705SXin Li                                           SC_Static,
1889*67e74705SXin Li                                           false, false);
1890*67e74705SXin Li 
1891*67e74705SXin Li   CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1892*67e74705SXin Li 
1893*67e74705SXin Li   CGF.StartFunction(FD, R, Fn, FI, args);
1894*67e74705SXin Li 
1895*67e74705SXin Li   if (generator.needsDispose()) {
1896*67e74705SXin Li     Address addr = CGF.GetAddrOfLocalVar(&src);
1897*67e74705SXin Li     addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1898*67e74705SXin Li     auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1899*67e74705SXin Li     addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1900*67e74705SXin Li     addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1901*67e74705SXin Li 
1902*67e74705SXin Li     generator.emitDispose(CGF, addr);
1903*67e74705SXin Li   }
1904*67e74705SXin Li 
1905*67e74705SXin Li   CGF.FinishFunction();
1906*67e74705SXin Li 
1907*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1908*67e74705SXin Li }
1909*67e74705SXin Li 
1910*67e74705SXin Li /// Build the dispose helper for a __block variable.
buildByrefDisposeHelper(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)1911*67e74705SXin Li static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1912*67e74705SXin Li                                                const BlockByrefInfo &byrefInfo,
1913*67e74705SXin Li                                                BlockByrefHelpers &generator) {
1914*67e74705SXin Li   CodeGenFunction CGF(CGM);
1915*67e74705SXin Li   return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1916*67e74705SXin Li }
1917*67e74705SXin Li 
1918*67e74705SXin Li /// Lazily build the copy and dispose helpers for a __block variable
1919*67e74705SXin Li /// with the given information.
1920*67e74705SXin Li template <class T>
buildByrefHelpers(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,T && generator)1921*67e74705SXin Li static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1922*67e74705SXin Li                             T &&generator) {
1923*67e74705SXin Li   llvm::FoldingSetNodeID id;
1924*67e74705SXin Li   generator.Profile(id);
1925*67e74705SXin Li 
1926*67e74705SXin Li   void *insertPos;
1927*67e74705SXin Li   BlockByrefHelpers *node
1928*67e74705SXin Li     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1929*67e74705SXin Li   if (node) return static_cast<T*>(node);
1930*67e74705SXin Li 
1931*67e74705SXin Li   generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1932*67e74705SXin Li   generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1933*67e74705SXin Li 
1934*67e74705SXin Li   T *copy = new (CGM.getContext()) T(std::move(generator));
1935*67e74705SXin Li   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1936*67e74705SXin Li   return copy;
1937*67e74705SXin Li }
1938*67e74705SXin Li 
1939*67e74705SXin Li /// Build the copy and dispose helpers for the given __block variable
1940*67e74705SXin Li /// emission.  Places the helpers in the global cache.  Returns null
1941*67e74705SXin Li /// if no helpers are required.
1942*67e74705SXin Li BlockByrefHelpers *
buildByrefHelpers(llvm::StructType & byrefType,const AutoVarEmission & emission)1943*67e74705SXin Li CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1944*67e74705SXin Li                                    const AutoVarEmission &emission) {
1945*67e74705SXin Li   const VarDecl &var = *emission.Variable;
1946*67e74705SXin Li   QualType type = var.getType();
1947*67e74705SXin Li 
1948*67e74705SXin Li   auto &byrefInfo = getBlockByrefInfo(&var);
1949*67e74705SXin Li 
1950*67e74705SXin Li   // The alignment we care about for the purposes of uniquing byref
1951*67e74705SXin Li   // helpers is the alignment of the actual byref value field.
1952*67e74705SXin Li   CharUnits valueAlignment =
1953*67e74705SXin Li     byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1954*67e74705SXin Li 
1955*67e74705SXin Li   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1956*67e74705SXin Li     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1957*67e74705SXin Li     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1958*67e74705SXin Li 
1959*67e74705SXin Li     return ::buildByrefHelpers(
1960*67e74705SXin Li         CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1961*67e74705SXin Li   }
1962*67e74705SXin Li 
1963*67e74705SXin Li   // Otherwise, if we don't have a retainable type, there's nothing to do.
1964*67e74705SXin Li   // that the runtime does extra copies.
1965*67e74705SXin Li   if (!type->isObjCRetainableType()) return nullptr;
1966*67e74705SXin Li 
1967*67e74705SXin Li   Qualifiers qs = type.getQualifiers();
1968*67e74705SXin Li 
1969*67e74705SXin Li   // If we have lifetime, that dominates.
1970*67e74705SXin Li   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1971*67e74705SXin Li     switch (lifetime) {
1972*67e74705SXin Li     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1973*67e74705SXin Li 
1974*67e74705SXin Li     // These are just bits as far as the runtime is concerned.
1975*67e74705SXin Li     case Qualifiers::OCL_ExplicitNone:
1976*67e74705SXin Li     case Qualifiers::OCL_Autoreleasing:
1977*67e74705SXin Li       return nullptr;
1978*67e74705SXin Li 
1979*67e74705SXin Li     // Tell the runtime that this is ARC __weak, called by the
1980*67e74705SXin Li     // byref routines.
1981*67e74705SXin Li     case Qualifiers::OCL_Weak:
1982*67e74705SXin Li       return ::buildByrefHelpers(CGM, byrefInfo,
1983*67e74705SXin Li                                  ARCWeakByrefHelpers(valueAlignment));
1984*67e74705SXin Li 
1985*67e74705SXin Li     // ARC __strong __block variables need to be retained.
1986*67e74705SXin Li     case Qualifiers::OCL_Strong:
1987*67e74705SXin Li       // Block pointers need to be copied, and there's no direct
1988*67e74705SXin Li       // transfer possible.
1989*67e74705SXin Li       if (type->isBlockPointerType()) {
1990*67e74705SXin Li         return ::buildByrefHelpers(CGM, byrefInfo,
1991*67e74705SXin Li                                    ARCStrongBlockByrefHelpers(valueAlignment));
1992*67e74705SXin Li 
1993*67e74705SXin Li       // Otherwise, we transfer ownership of the retain from the stack
1994*67e74705SXin Li       // to the heap.
1995*67e74705SXin Li       } else {
1996*67e74705SXin Li         return ::buildByrefHelpers(CGM, byrefInfo,
1997*67e74705SXin Li                                    ARCStrongByrefHelpers(valueAlignment));
1998*67e74705SXin Li       }
1999*67e74705SXin Li     }
2000*67e74705SXin Li     llvm_unreachable("fell out of lifetime switch!");
2001*67e74705SXin Li   }
2002*67e74705SXin Li 
2003*67e74705SXin Li   BlockFieldFlags flags;
2004*67e74705SXin Li   if (type->isBlockPointerType()) {
2005*67e74705SXin Li     flags |= BLOCK_FIELD_IS_BLOCK;
2006*67e74705SXin Li   } else if (CGM.getContext().isObjCNSObjectType(type) ||
2007*67e74705SXin Li              type->isObjCObjectPointerType()) {
2008*67e74705SXin Li     flags |= BLOCK_FIELD_IS_OBJECT;
2009*67e74705SXin Li   } else {
2010*67e74705SXin Li     return nullptr;
2011*67e74705SXin Li   }
2012*67e74705SXin Li 
2013*67e74705SXin Li   if (type.isObjCGCWeak())
2014*67e74705SXin Li     flags |= BLOCK_FIELD_IS_WEAK;
2015*67e74705SXin Li 
2016*67e74705SXin Li   return ::buildByrefHelpers(CGM, byrefInfo,
2017*67e74705SXin Li                              ObjectByrefHelpers(valueAlignment, flags));
2018*67e74705SXin Li }
2019*67e74705SXin Li 
emitBlockByrefAddress(Address baseAddr,const VarDecl * var,bool followForward)2020*67e74705SXin Li Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2021*67e74705SXin Li                                                const VarDecl *var,
2022*67e74705SXin Li                                                bool followForward) {
2023*67e74705SXin Li   auto &info = getBlockByrefInfo(var);
2024*67e74705SXin Li   return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2025*67e74705SXin Li }
2026*67e74705SXin Li 
emitBlockByrefAddress(Address baseAddr,const BlockByrefInfo & info,bool followForward,const llvm::Twine & name)2027*67e74705SXin Li Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2028*67e74705SXin Li                                                const BlockByrefInfo &info,
2029*67e74705SXin Li                                                bool followForward,
2030*67e74705SXin Li                                                const llvm::Twine &name) {
2031*67e74705SXin Li   // Chase the forwarding address if requested.
2032*67e74705SXin Li   if (followForward) {
2033*67e74705SXin Li     Address forwardingAddr =
2034*67e74705SXin Li       Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2035*67e74705SXin Li     baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2036*67e74705SXin Li   }
2037*67e74705SXin Li 
2038*67e74705SXin Li   return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2039*67e74705SXin Li                                  info.FieldOffset, name);
2040*67e74705SXin Li }
2041*67e74705SXin Li 
2042*67e74705SXin Li /// BuildByrefInfo - This routine changes a __block variable declared as T x
2043*67e74705SXin Li ///   into:
2044*67e74705SXin Li ///
2045*67e74705SXin Li ///      struct {
2046*67e74705SXin Li ///        void *__isa;
2047*67e74705SXin Li ///        void *__forwarding;
2048*67e74705SXin Li ///        int32_t __flags;
2049*67e74705SXin Li ///        int32_t __size;
2050*67e74705SXin Li ///        void *__copy_helper;       // only if needed
2051*67e74705SXin Li ///        void *__destroy_helper;    // only if needed
2052*67e74705SXin Li ///        void *__byref_variable_layout;// only if needed
2053*67e74705SXin Li ///        char padding[X];           // only if needed
2054*67e74705SXin Li ///        T x;
2055*67e74705SXin Li ///      } x
2056*67e74705SXin Li ///
getBlockByrefInfo(const VarDecl * D)2057*67e74705SXin Li const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2058*67e74705SXin Li   auto it = BlockByrefInfos.find(D);
2059*67e74705SXin Li   if (it != BlockByrefInfos.end())
2060*67e74705SXin Li     return it->second;
2061*67e74705SXin Li 
2062*67e74705SXin Li   llvm::StructType *byrefType =
2063*67e74705SXin Li     llvm::StructType::create(getLLVMContext(),
2064*67e74705SXin Li                              "struct.__block_byref_" + D->getNameAsString());
2065*67e74705SXin Li 
2066*67e74705SXin Li   QualType Ty = D->getType();
2067*67e74705SXin Li 
2068*67e74705SXin Li   CharUnits size;
2069*67e74705SXin Li   SmallVector<llvm::Type *, 8> types;
2070*67e74705SXin Li 
2071*67e74705SXin Li   // void *__isa;
2072*67e74705SXin Li   types.push_back(Int8PtrTy);
2073*67e74705SXin Li   size += getPointerSize();
2074*67e74705SXin Li 
2075*67e74705SXin Li   // void *__forwarding;
2076*67e74705SXin Li   types.push_back(llvm::PointerType::getUnqual(byrefType));
2077*67e74705SXin Li   size += getPointerSize();
2078*67e74705SXin Li 
2079*67e74705SXin Li   // int32_t __flags;
2080*67e74705SXin Li   types.push_back(Int32Ty);
2081*67e74705SXin Li   size += CharUnits::fromQuantity(4);
2082*67e74705SXin Li 
2083*67e74705SXin Li   // int32_t __size;
2084*67e74705SXin Li   types.push_back(Int32Ty);
2085*67e74705SXin Li   size += CharUnits::fromQuantity(4);
2086*67e74705SXin Li 
2087*67e74705SXin Li   // Note that this must match *exactly* the logic in buildByrefHelpers.
2088*67e74705SXin Li   bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2089*67e74705SXin Li   if (hasCopyAndDispose) {
2090*67e74705SXin Li     /// void *__copy_helper;
2091*67e74705SXin Li     types.push_back(Int8PtrTy);
2092*67e74705SXin Li     size += getPointerSize();
2093*67e74705SXin Li 
2094*67e74705SXin Li     /// void *__destroy_helper;
2095*67e74705SXin Li     types.push_back(Int8PtrTy);
2096*67e74705SXin Li     size += getPointerSize();
2097*67e74705SXin Li   }
2098*67e74705SXin Li 
2099*67e74705SXin Li   bool HasByrefExtendedLayout = false;
2100*67e74705SXin Li   Qualifiers::ObjCLifetime Lifetime;
2101*67e74705SXin Li   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2102*67e74705SXin Li       HasByrefExtendedLayout) {
2103*67e74705SXin Li     /// void *__byref_variable_layout;
2104*67e74705SXin Li     types.push_back(Int8PtrTy);
2105*67e74705SXin Li     size += CharUnits::fromQuantity(PointerSizeInBytes);
2106*67e74705SXin Li   }
2107*67e74705SXin Li 
2108*67e74705SXin Li   // T x;
2109*67e74705SXin Li   llvm::Type *varTy = ConvertTypeForMem(Ty);
2110*67e74705SXin Li 
2111*67e74705SXin Li   bool packed = false;
2112*67e74705SXin Li   CharUnits varAlign = getContext().getDeclAlign(D);
2113*67e74705SXin Li   CharUnits varOffset = size.alignTo(varAlign);
2114*67e74705SXin Li 
2115*67e74705SXin Li   // We may have to insert padding.
2116*67e74705SXin Li   if (varOffset != size) {
2117*67e74705SXin Li     llvm::Type *paddingTy =
2118*67e74705SXin Li       llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2119*67e74705SXin Li 
2120*67e74705SXin Li     types.push_back(paddingTy);
2121*67e74705SXin Li     size = varOffset;
2122*67e74705SXin Li 
2123*67e74705SXin Li   // Conversely, we might have to prevent LLVM from inserting padding.
2124*67e74705SXin Li   } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2125*67e74705SXin Li                > varAlign.getQuantity()) {
2126*67e74705SXin Li     packed = true;
2127*67e74705SXin Li   }
2128*67e74705SXin Li   types.push_back(varTy);
2129*67e74705SXin Li 
2130*67e74705SXin Li   byrefType->setBody(types, packed);
2131*67e74705SXin Li 
2132*67e74705SXin Li   BlockByrefInfo info;
2133*67e74705SXin Li   info.Type = byrefType;
2134*67e74705SXin Li   info.FieldIndex = types.size() - 1;
2135*67e74705SXin Li   info.FieldOffset = varOffset;
2136*67e74705SXin Li   info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2137*67e74705SXin Li 
2138*67e74705SXin Li   auto pair = BlockByrefInfos.insert({D, info});
2139*67e74705SXin Li   assert(pair.second && "info was inserted recursively?");
2140*67e74705SXin Li   return pair.first->second;
2141*67e74705SXin Li }
2142*67e74705SXin Li 
2143*67e74705SXin Li /// Initialize the structural components of a __block variable, i.e.
2144*67e74705SXin Li /// everything but the actual object.
emitByrefStructureInit(const AutoVarEmission & emission)2145*67e74705SXin Li void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2146*67e74705SXin Li   // Find the address of the local.
2147*67e74705SXin Li   Address addr = emission.Addr;
2148*67e74705SXin Li 
2149*67e74705SXin Li   // That's an alloca of the byref structure type.
2150*67e74705SXin Li   llvm::StructType *byrefType = cast<llvm::StructType>(
2151*67e74705SXin Li     cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2152*67e74705SXin Li 
2153*67e74705SXin Li   unsigned nextHeaderIndex = 0;
2154*67e74705SXin Li   CharUnits nextHeaderOffset;
2155*67e74705SXin Li   auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2156*67e74705SXin Li                               const Twine &name) {
2157*67e74705SXin Li     auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2158*67e74705SXin Li                                              nextHeaderOffset, name);
2159*67e74705SXin Li     Builder.CreateStore(value, fieldAddr);
2160*67e74705SXin Li 
2161*67e74705SXin Li     nextHeaderIndex++;
2162*67e74705SXin Li     nextHeaderOffset += fieldSize;
2163*67e74705SXin Li   };
2164*67e74705SXin Li 
2165*67e74705SXin Li   // Build the byref helpers if necessary.  This is null if we don't need any.
2166*67e74705SXin Li   BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2167*67e74705SXin Li 
2168*67e74705SXin Li   const VarDecl &D = *emission.Variable;
2169*67e74705SXin Li   QualType type = D.getType();
2170*67e74705SXin Li 
2171*67e74705SXin Li   bool HasByrefExtendedLayout;
2172*67e74705SXin Li   Qualifiers::ObjCLifetime ByrefLifetime;
2173*67e74705SXin Li   bool ByRefHasLifetime =
2174*67e74705SXin Li     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2175*67e74705SXin Li 
2176*67e74705SXin Li   llvm::Value *V;
2177*67e74705SXin Li 
2178*67e74705SXin Li   // Initialize the 'isa', which is just 0 or 1.
2179*67e74705SXin Li   int isa = 0;
2180*67e74705SXin Li   if (type.isObjCGCWeak())
2181*67e74705SXin Li     isa = 1;
2182*67e74705SXin Li   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2183*67e74705SXin Li   storeHeaderField(V, getPointerSize(), "byref.isa");
2184*67e74705SXin Li 
2185*67e74705SXin Li   // Store the address of the variable into its own forwarding pointer.
2186*67e74705SXin Li   storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2187*67e74705SXin Li 
2188*67e74705SXin Li   // Blocks ABI:
2189*67e74705SXin Li   //   c) the flags field is set to either 0 if no helper functions are
2190*67e74705SXin Li   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2191*67e74705SXin Li   BlockFlags flags;
2192*67e74705SXin Li   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2193*67e74705SXin Li   if (ByRefHasLifetime) {
2194*67e74705SXin Li     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2195*67e74705SXin Li       else switch (ByrefLifetime) {
2196*67e74705SXin Li         case Qualifiers::OCL_Strong:
2197*67e74705SXin Li           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2198*67e74705SXin Li           break;
2199*67e74705SXin Li         case Qualifiers::OCL_Weak:
2200*67e74705SXin Li           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2201*67e74705SXin Li           break;
2202*67e74705SXin Li         case Qualifiers::OCL_ExplicitNone:
2203*67e74705SXin Li           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2204*67e74705SXin Li           break;
2205*67e74705SXin Li         case Qualifiers::OCL_None:
2206*67e74705SXin Li           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2207*67e74705SXin Li             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2208*67e74705SXin Li           break;
2209*67e74705SXin Li         default:
2210*67e74705SXin Li           break;
2211*67e74705SXin Li       }
2212*67e74705SXin Li     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2213*67e74705SXin Li       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2214*67e74705SXin Li       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2215*67e74705SXin Li         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2216*67e74705SXin Li       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2217*67e74705SXin Li         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2218*67e74705SXin Li         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2219*67e74705SXin Li           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2220*67e74705SXin Li         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2221*67e74705SXin Li           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2222*67e74705SXin Li         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2223*67e74705SXin Li           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2224*67e74705SXin Li         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2225*67e74705SXin Li           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2226*67e74705SXin Li         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2227*67e74705SXin Li           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2228*67e74705SXin Li       }
2229*67e74705SXin Li       printf("\n");
2230*67e74705SXin Li     }
2231*67e74705SXin Li   }
2232*67e74705SXin Li   storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2233*67e74705SXin Li                    getIntSize(), "byref.flags");
2234*67e74705SXin Li 
2235*67e74705SXin Li   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2236*67e74705SXin Li   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2237*67e74705SXin Li   storeHeaderField(V, getIntSize(), "byref.size");
2238*67e74705SXin Li 
2239*67e74705SXin Li   if (helpers) {
2240*67e74705SXin Li     storeHeaderField(helpers->CopyHelper, getPointerSize(),
2241*67e74705SXin Li                      "byref.copyHelper");
2242*67e74705SXin Li     storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2243*67e74705SXin Li                      "byref.disposeHelper");
2244*67e74705SXin Li   }
2245*67e74705SXin Li 
2246*67e74705SXin Li   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2247*67e74705SXin Li     auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2248*67e74705SXin Li     storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2249*67e74705SXin Li   }
2250*67e74705SXin Li }
2251*67e74705SXin Li 
BuildBlockRelease(llvm::Value * V,BlockFieldFlags flags)2252*67e74705SXin Li void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2253*67e74705SXin Li   llvm::Value *F = CGM.getBlockObjectDispose();
2254*67e74705SXin Li   llvm::Value *args[] = {
2255*67e74705SXin Li     Builder.CreateBitCast(V, Int8PtrTy),
2256*67e74705SXin Li     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2257*67e74705SXin Li   };
2258*67e74705SXin Li   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2259*67e74705SXin Li }
2260*67e74705SXin Li 
2261*67e74705SXin Li namespace {
2262*67e74705SXin Li   /// Release a __block variable.
2263*67e74705SXin Li   struct CallBlockRelease final : EHScopeStack::Cleanup {
2264*67e74705SXin Li     llvm::Value *Addr;
CallBlockRelease__anonf4e099be0811::CallBlockRelease2265*67e74705SXin Li     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2266*67e74705SXin Li 
Emit__anonf4e099be0811::CallBlockRelease2267*67e74705SXin Li     void Emit(CodeGenFunction &CGF, Flags flags) override {
2268*67e74705SXin Li       // Should we be passing FIELD_IS_WEAK here?
2269*67e74705SXin Li       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2270*67e74705SXin Li     }
2271*67e74705SXin Li   };
2272*67e74705SXin Li } // end anonymous namespace
2273*67e74705SXin Li 
2274*67e74705SXin Li /// Enter a cleanup to destroy a __block variable.  Note that this
2275*67e74705SXin Li /// cleanup should be a no-op if the variable hasn't left the stack
2276*67e74705SXin Li /// yet; if a cleanup is required for the variable itself, that needs
2277*67e74705SXin Li /// to be done externally.
enterByrefCleanup(const AutoVarEmission & emission)2278*67e74705SXin Li void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2279*67e74705SXin Li   // We don't enter this cleanup if we're in pure-GC mode.
2280*67e74705SXin Li   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2281*67e74705SXin Li     return;
2282*67e74705SXin Li 
2283*67e74705SXin Li   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2284*67e74705SXin Li                                         emission.Addr.getPointer());
2285*67e74705SXin Li }
2286*67e74705SXin Li 
2287*67e74705SXin Li /// Adjust the declaration of something from the blocks API.
configureBlocksRuntimeObject(CodeGenModule & CGM,llvm::Constant * C)2288*67e74705SXin Li static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2289*67e74705SXin Li                                          llvm::Constant *C) {
2290*67e74705SXin Li   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2291*67e74705SXin Li 
2292*67e74705SXin Li   if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2293*67e74705SXin Li     IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2294*67e74705SXin Li     TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2295*67e74705SXin Li     DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2296*67e74705SXin Li 
2297*67e74705SXin Li     assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2298*67e74705SXin Li             isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2299*67e74705SXin Li            "expected Function or GlobalVariable");
2300*67e74705SXin Li 
2301*67e74705SXin Li     const NamedDecl *ND = nullptr;
2302*67e74705SXin Li     for (const auto &Result : DC->lookup(&II))
2303*67e74705SXin Li       if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2304*67e74705SXin Li           (ND = dyn_cast<VarDecl>(Result)))
2305*67e74705SXin Li         break;
2306*67e74705SXin Li 
2307*67e74705SXin Li     // TODO: support static blocks runtime
2308*67e74705SXin Li     if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2309*67e74705SXin Li       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2310*67e74705SXin Li       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2311*67e74705SXin Li     } else {
2312*67e74705SXin Li       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2313*67e74705SXin Li       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2314*67e74705SXin Li     }
2315*67e74705SXin Li   }
2316*67e74705SXin Li 
2317*67e74705SXin Li   if (!CGM.getLangOpts().BlocksRuntimeOptional)
2318*67e74705SXin Li     return;
2319*67e74705SXin Li 
2320*67e74705SXin Li   if (GV->isDeclaration() && GV->hasExternalLinkage())
2321*67e74705SXin Li     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2322*67e74705SXin Li }
2323*67e74705SXin Li 
getBlockObjectDispose()2324*67e74705SXin Li llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2325*67e74705SXin Li   if (BlockObjectDispose)
2326*67e74705SXin Li     return BlockObjectDispose;
2327*67e74705SXin Li 
2328*67e74705SXin Li   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2329*67e74705SXin Li   llvm::FunctionType *fty
2330*67e74705SXin Li     = llvm::FunctionType::get(VoidTy, args, false);
2331*67e74705SXin Li   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2332*67e74705SXin Li   configureBlocksRuntimeObject(*this, BlockObjectDispose);
2333*67e74705SXin Li   return BlockObjectDispose;
2334*67e74705SXin Li }
2335*67e74705SXin Li 
getBlockObjectAssign()2336*67e74705SXin Li llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2337*67e74705SXin Li   if (BlockObjectAssign)
2338*67e74705SXin Li     return BlockObjectAssign;
2339*67e74705SXin Li 
2340*67e74705SXin Li   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2341*67e74705SXin Li   llvm::FunctionType *fty
2342*67e74705SXin Li     = llvm::FunctionType::get(VoidTy, args, false);
2343*67e74705SXin Li   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2344*67e74705SXin Li   configureBlocksRuntimeObject(*this, BlockObjectAssign);
2345*67e74705SXin Li   return BlockObjectAssign;
2346*67e74705SXin Li }
2347*67e74705SXin Li 
getNSConcreteGlobalBlock()2348*67e74705SXin Li llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2349*67e74705SXin Li   if (NSConcreteGlobalBlock)
2350*67e74705SXin Li     return NSConcreteGlobalBlock;
2351*67e74705SXin Li 
2352*67e74705SXin Li   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2353*67e74705SXin Li                                                 Int8PtrTy->getPointerTo(),
2354*67e74705SXin Li                                                 nullptr);
2355*67e74705SXin Li   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2356*67e74705SXin Li   return NSConcreteGlobalBlock;
2357*67e74705SXin Li }
2358*67e74705SXin Li 
getNSConcreteStackBlock()2359*67e74705SXin Li llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2360*67e74705SXin Li   if (NSConcreteStackBlock)
2361*67e74705SXin Li     return NSConcreteStackBlock;
2362*67e74705SXin Li 
2363*67e74705SXin Li   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2364*67e74705SXin Li                                                Int8PtrTy->getPointerTo(),
2365*67e74705SXin Li                                                nullptr);
2366*67e74705SXin Li   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2367*67e74705SXin Li   return NSConcreteStackBlock;
2368*67e74705SXin Li }
2369