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