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