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