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