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