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(
625         blockInfo.StructureType, blockInfo.Address, 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::Type *blockTy = blockInfo.StructureType;
725   llvm::AllocaInst *blockAddr = blockInfo.Address;
726   assert(blockAddr && "block has no address!");
727 
728   // Compute the initial on-stack block flags.
729   BlockFlags flags = BLOCK_HAS_SIGNATURE;
730   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
731   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
732   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
733   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
734 
735   // Initialize the block literal.
736   Builder.CreateStore(
737       isa, Builder.CreateStructGEP(blockTy, blockAddr, 0, "block.isa"));
738   Builder.CreateStore(
739       llvm::ConstantInt::get(IntTy, flags.getBitMask()),
740       Builder.CreateStructGEP(blockTy, blockAddr, 1, "block.flags"));
741   Builder.CreateStore(
742       llvm::ConstantInt::get(IntTy, 0),
743       Builder.CreateStructGEP(blockTy, blockAddr, 2, "block.reserved"));
744   Builder.CreateStore(
745       blockFn, Builder.CreateStructGEP(blockTy, blockAddr, 3, "block.invoke"));
746   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockTy, blockAddr, 4,
747                                                           "block.descriptor"));
748 
749   // Finally, capture all the values into the block.
750   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
751 
752   // First, 'this'.
753   if (blockDecl->capturesCXXThis()) {
754     llvm::Value *addr = Builder.CreateStructGEP(
755         blockTy, blockAddr, blockInfo.CXXThisIndex, "block.captured-this.addr");
756     Builder.CreateStore(LoadCXXThis(), addr);
757   }
758 
759   // Next, captured variables.
760   for (const auto &CI : blockDecl->captures()) {
761     const VarDecl *variable = CI.getVariable();
762     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
763 
764     // Ignore constant captures.
765     if (capture.isConstant()) continue;
766 
767     QualType type = variable->getType();
768     CharUnits align = getContext().getDeclAlign(variable);
769 
770     // This will be a [[type]]*, except that a byref entry will just be
771     // an i8**.
772     llvm::Value *blockField = Builder.CreateStructGEP(
773         blockTy, blockAddr, capture.getIndex(), "block.captured");
774 
775     // Compute the address of the thing we're going to move into the
776     // block literal.
777     llvm::Value *src;
778     if (BlockInfo && CI.isNested()) {
779       // We need to use the capture from the enclosing block.
780       const CGBlockInfo::Capture &enclosingCapture =
781         BlockInfo->getCapture(variable);
782 
783       // This is a [[type]]*, except that a byref entry wil just be an i8**.
784       src = Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
785                                     enclosingCapture.getIndex(),
786                                     "block.capture.addr");
787     } else if (blockDecl->isConversionFromLambda()) {
788       // The lambda capture in a lambda's conversion-to-block-pointer is
789       // special; we'll simply emit it directly.
790       src = nullptr;
791     } else {
792       // Just look it up in the locals map, which will give us back a
793       // [[type]]*.  If that doesn't work, do the more elaborate DRE
794       // emission.
795       src = LocalDeclMap.lookup(variable);
796       if (!src) {
797         DeclRefExpr declRef(
798             const_cast<VarDecl *>(variable),
799             /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
800             VK_LValue, SourceLocation());
801         src = EmitDeclRefLValue(&declRef).getAddress();
802       }
803     }
804 
805     // For byrefs, we just write the pointer to the byref struct into
806     // the block field.  There's no need to chase the forwarding
807     // pointer at this point, since we're building something that will
808     // live a shorter life than the stack byref anyway.
809     if (CI.isByRef()) {
810       // Get a void* that points to the byref struct.
811       if (CI.isNested())
812         src = Builder.CreateAlignedLoad(src, align.getQuantity(),
813                                         "byref.capture");
814       else
815         src = Builder.CreateBitCast(src, VoidPtrTy);
816 
817       // Write that void* into the capture field.
818       Builder.CreateAlignedStore(src, blockField, align.getQuantity());
819 
820     // If we have a copy constructor, evaluate that into the block field.
821     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
822       if (blockDecl->isConversionFromLambda()) {
823         // If we have a lambda conversion, emit the expression
824         // directly into the block instead.
825         AggValueSlot Slot =
826             AggValueSlot::forAddr(blockField, align, Qualifiers(),
827                                   AggValueSlot::IsDestructed,
828                                   AggValueSlot::DoesNotNeedGCBarriers,
829                                   AggValueSlot::IsNotAliased);
830         EmitAggExpr(copyExpr, Slot);
831       } else {
832         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
833       }
834 
835     // If it's a reference variable, copy the reference into the block field.
836     } else if (type->isReferenceType()) {
837       llvm::Value *ref =
838         Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
839       Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
840 
841     // If this is an ARC __strong block-pointer variable, don't do a
842     // block copy.
843     //
844     // TODO: this can be generalized into the normal initialization logic:
845     // we should never need to do a block-copy when initializing a local
846     // variable, because the local variable's lifetime should be strictly
847     // contained within the stack block's.
848     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
849                type->isBlockPointerType()) {
850       // Load the block and do a simple retain.
851       LValue srcLV = MakeAddrLValue(src, type, align);
852       llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
853       value = EmitARCRetainNonBlock(value);
854 
855       // Do a primitive store to the block field.
856       LValue destLV = MakeAddrLValue(blockField, type, align);
857       EmitStoreOfScalar(value, destLV, /*init*/ true);
858 
859     // Otherwise, fake up a POD copy into the block field.
860     } else {
861       // Fake up a new variable so that EmitScalarInit doesn't think
862       // we're referring to the variable in its own initializer.
863       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
864                                             SourceLocation(), /*name*/ nullptr,
865                                             type);
866 
867       // We use one of these or the other depending on whether the
868       // reference is nested.
869       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
870                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
871                           type, VK_LValue, SourceLocation());
872 
873       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
874                            &declRef, VK_RValue);
875       // FIXME: Pass a specific location for the expr init so that the store is
876       // attributed to a reasonable location - otherwise it may be attributed to
877       // locations of subexpressions in the initialization.
878       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
879                      MakeAddrLValue(blockField, type, align),
880                      /*captured by init*/ false);
881     }
882 
883     // Activate the cleanup if layout pushed one.
884     if (!CI.isByRef()) {
885       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
886       if (cleanup.isValid())
887         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
888     }
889   }
890 
891   // Cast to the converted block-pointer type, which happens (somewhat
892   // unfortunately) to be a pointer to function type.
893   llvm::Value *result =
894     Builder.CreateBitCast(blockAddr,
895                           ConvertType(blockInfo.getBlockExpr()->getType()));
896 
897   return result;
898 }
899 
900 
901 llvm::Type *CodeGenModule::getBlockDescriptorType() {
902   if (BlockDescriptorType)
903     return BlockDescriptorType;
904 
905   llvm::Type *UnsignedLongTy =
906     getTypes().ConvertType(getContext().UnsignedLongTy);
907 
908   // struct __block_descriptor {
909   //   unsigned long reserved;
910   //   unsigned long block_size;
911   //
912   //   // later, the following will be added
913   //
914   //   struct {
915   //     void (*copyHelper)();
916   //     void (*copyHelper)();
917   //   } helpers;                // !!! optional
918   //
919   //   const char *signature;   // the block signature
920   //   const char *layout;      // reserved
921   // };
922   BlockDescriptorType =
923     llvm::StructType::create("struct.__block_descriptor",
924                              UnsignedLongTy, UnsignedLongTy, nullptr);
925 
926   // Now form a pointer to that.
927   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
928   return BlockDescriptorType;
929 }
930 
931 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
932   if (GenericBlockLiteralType)
933     return GenericBlockLiteralType;
934 
935   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
936 
937   // struct __block_literal_generic {
938   //   void *__isa;
939   //   int __flags;
940   //   int __reserved;
941   //   void (*__invoke)(void *);
942   //   struct __block_descriptor *__descriptor;
943   // };
944   GenericBlockLiteralType =
945     llvm::StructType::create("struct.__block_literal_generic",
946                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
947                              BlockDescPtrTy, nullptr);
948 
949   return GenericBlockLiteralType;
950 }
951 
952 
953 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
954                                           ReturnValueSlot ReturnValue) {
955   const BlockPointerType *BPT =
956     E->getCallee()->getType()->getAs<BlockPointerType>();
957 
958   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
959 
960   // Get a pointer to the generic block literal.
961   llvm::Type *BlockLiteralTy =
962     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
963 
964   // Bitcast the callee to a block literal.
965   llvm::Value *BlockLiteral =
966     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
967 
968   // Get the function pointer from the literal.
969   llvm::Value *FuncPtr = Builder.CreateStructGEP(
970       CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
971 
972   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
973 
974   // Add the block literal.
975   CallArgList Args;
976   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
977 
978   QualType FnType = BPT->getPointeeType();
979 
980   // And the rest of the arguments.
981   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
982 
983   // Load the function.
984   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
985 
986   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
987   const CGFunctionInfo &FnInfo =
988     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
989 
990   // Cast the function pointer to the right type.
991   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
992 
993   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
994   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
995 
996   // And call the block.
997   return EmitCall(FnInfo, Func, ReturnValue, Args);
998 }
999 
1000 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1001                                                  bool isByRef) {
1002   assert(BlockInfo && "evaluating block ref without block information?");
1003   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1004 
1005   // Handle constant captures.
1006   if (capture.isConstant()) return LocalDeclMap[variable];
1007 
1008   llvm::Value *addr =
1009       Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
1010                               capture.getIndex(), "block.capture.addr");
1011 
1012   if (isByRef) {
1013     // addr should be a void** right now.  Load, then cast the result
1014     // to byref*.
1015 
1016     addr = Builder.CreateLoad(addr);
1017     auto *byrefType = BuildByRefType(variable);
1018     llvm::PointerType *byrefPointerType = llvm::PointerType::get(byrefType, 0);
1019     addr = Builder.CreateBitCast(addr, byrefPointerType,
1020                                  "byref.addr");
1021 
1022     // Follow the forwarding pointer.
1023     addr = Builder.CreateStructGEP(byrefType, addr, 1, "byref.forwarding");
1024     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
1025 
1026     // Cast back to byref* and GEP over to the actual object.
1027     addr = Builder.CreateBitCast(addr, byrefPointerType);
1028     addr = Builder.CreateStructGEP(byrefType, addr,
1029                                    getByRefValueLLVMField(variable).second,
1030                                    variable->getNameAsString());
1031   }
1032 
1033   if (variable->getType()->isReferenceType())
1034     addr = Builder.CreateLoad(addr, "ref.tmp");
1035 
1036   return addr;
1037 }
1038 
1039 llvm::Constant *
1040 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1041                                     const char *name) {
1042   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1043   blockInfo.BlockExpression = blockExpr;
1044 
1045   // Compute information about the layout, etc., of this block.
1046   computeBlockInfo(*this, nullptr, blockInfo);
1047 
1048   // Using that metadata, generate the actual block function.
1049   llvm::Constant *blockFn;
1050   {
1051     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1052     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1053                                                            blockInfo,
1054                                                            LocalDeclMap,
1055                                                            false);
1056   }
1057   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1058 
1059   return buildGlobalBlock(*this, blockInfo, blockFn);
1060 }
1061 
1062 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1063                                         const CGBlockInfo &blockInfo,
1064                                         llvm::Constant *blockFn) {
1065   assert(blockInfo.CanBeGlobal);
1066 
1067   // Generate the constants for the block literal initializer.
1068   llvm::Constant *fields[BlockHeaderSize];
1069 
1070   // isa
1071   fields[0] = CGM.getNSConcreteGlobalBlock();
1072 
1073   // __flags
1074   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1075   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1076 
1077   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1078 
1079   // Reserved
1080   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1081 
1082   // Function
1083   fields[3] = blockFn;
1084 
1085   // Descriptor
1086   fields[4] = buildBlockDescriptor(CGM, blockInfo);
1087 
1088   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1089 
1090   llvm::GlobalVariable *literal =
1091     new llvm::GlobalVariable(CGM.getModule(),
1092                              init->getType(),
1093                              /*constant*/ true,
1094                              llvm::GlobalVariable::InternalLinkage,
1095                              init,
1096                              "__block_literal_global");
1097   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1098 
1099   // Return a constant of the appropriately-casted type.
1100   llvm::Type *requiredType =
1101     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1102   return llvm::ConstantExpr::getBitCast(literal, requiredType);
1103 }
1104 
1105 llvm::Function *
1106 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1107                                        const CGBlockInfo &blockInfo,
1108                                        const DeclMapTy &ldm,
1109                                        bool IsLambdaConversionToBlock) {
1110   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1111 
1112   CurGD = GD;
1113 
1114   CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1115 
1116   BlockInfo = &blockInfo;
1117 
1118   // Arrange for local static and local extern declarations to appear
1119   // to be local to this function as well, in case they're directly
1120   // referenced in a block.
1121   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1122     const auto *var = dyn_cast<VarDecl>(i->first);
1123     if (var && !var->hasLocalStorage())
1124       LocalDeclMap[var] = i->second;
1125   }
1126 
1127   // Begin building the function declaration.
1128 
1129   // Build the argument list.
1130   FunctionArgList args;
1131 
1132   // The first argument is the block pointer.  Just take it as a void*
1133   // and cast it later.
1134   QualType selfTy = getContext().VoidPtrTy;
1135   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1136 
1137   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1138                              SourceLocation(), II, selfTy);
1139   args.push_back(&selfDecl);
1140 
1141   // Now add the rest of the parameters.
1142   args.append(blockDecl->param_begin(), blockDecl->param_end());
1143 
1144   // Create the function declaration.
1145   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1146   const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1147       fnType->getReturnType(), args, fnType->getExtInfo(),
1148       fnType->isVariadic());
1149   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1150     blockInfo.UsesStret = true;
1151 
1152   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1153 
1154   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1155   llvm::Function *fn = llvm::Function::Create(
1156       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1157   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1158 
1159   // Begin generating the function.
1160   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1161                 blockDecl->getLocation(),
1162                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1163 
1164   // Okay.  Undo some of what StartFunction did.
1165 
1166   // Pull the 'self' reference out of the local decl map.
1167   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1168   LocalDeclMap.erase(&selfDecl);
1169   BlockPointer = Builder.CreateBitCast(blockAddr,
1170                                        blockInfo.StructureType->getPointerTo(),
1171                                        "block");
1172   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1173   // won't delete the dbg.declare intrinsics for captured variables.
1174   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1175   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1176     // Allocate a stack slot for it, so we can point the debugger to it
1177     llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1178                                                 "block.addr");
1179     unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1180     Alloca->setAlignment(Align);
1181     // Set the DebugLocation to empty, so the store is recognized as a
1182     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1183     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1184     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1185     BlockPointerDbgLoc = Alloca;
1186   }
1187 
1188   // If we have a C++ 'this' reference, go ahead and force it into
1189   // existence now.
1190   if (blockDecl->capturesCXXThis()) {
1191     llvm::Value *addr =
1192         Builder.CreateStructGEP(blockInfo.StructureType, BlockPointer,
1193                                 blockInfo.CXXThisIndex, "block.captured-this");
1194     CXXThisValue = Builder.CreateLoad(addr, "this");
1195   }
1196 
1197   // Also force all the constant captures.
1198   for (const auto &CI : blockDecl->captures()) {
1199     const VarDecl *variable = CI.getVariable();
1200     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1201     if (!capture.isConstant()) continue;
1202 
1203     unsigned align = getContext().getDeclAlign(variable).getQuantity();
1204 
1205     llvm::AllocaInst *alloca =
1206       CreateMemTemp(variable->getType(), "block.captured-const");
1207     alloca->setAlignment(align);
1208 
1209     Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1210 
1211     LocalDeclMap[variable] = alloca;
1212   }
1213 
1214   // Save a spot to insert the debug information for all the DeclRefExprs.
1215   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1216   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1217   --entry_ptr;
1218 
1219   if (IsLambdaConversionToBlock)
1220     EmitLambdaBlockInvokeBody();
1221   else {
1222     PGO.assignRegionCounters(blockDecl, fn);
1223     incrementProfileCounter(blockDecl->getBody());
1224     EmitStmt(blockDecl->getBody());
1225   }
1226 
1227   // Remember where we were...
1228   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1229 
1230   // Go back to the entry.
1231   ++entry_ptr;
1232   Builder.SetInsertPoint(entry, entry_ptr);
1233 
1234   // Emit debug information for all the DeclRefExprs.
1235   // FIXME: also for 'this'
1236   if (CGDebugInfo *DI = getDebugInfo()) {
1237     for (const auto &CI : blockDecl->captures()) {
1238       const VarDecl *variable = CI.getVariable();
1239       DI->EmitLocation(Builder, variable->getLocation());
1240 
1241       if (CGM.getCodeGenOpts().getDebugInfo()
1242             >= CodeGenOptions::LimitedDebugInfo) {
1243         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1244         if (capture.isConstant()) {
1245           DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1246                                         Builder);
1247           continue;
1248         }
1249 
1250         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
1251                                               Builder, blockInfo,
1252                                               entry_ptr == entry->end()
1253                                               ? nullptr : entry_ptr);
1254       }
1255     }
1256     // Recover location if it was changed in the above loop.
1257     DI->EmitLocation(Builder,
1258                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1259   }
1260 
1261   // And resume where we left off.
1262   if (resume == nullptr)
1263     Builder.ClearInsertionPoint();
1264   else
1265     Builder.SetInsertPoint(resume);
1266 
1267   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1268 
1269   return fn;
1270 }
1271 
1272 /*
1273     notes.push_back(HelperInfo());
1274     HelperInfo &note = notes.back();
1275     note.index = capture.getIndex();
1276     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1277     note.cxxbar_import = ci->getCopyExpr();
1278 
1279     if (ci->isByRef()) {
1280       note.flag = BLOCK_FIELD_IS_BYREF;
1281       if (type.isObjCGCWeak())
1282         note.flag |= BLOCK_FIELD_IS_WEAK;
1283     } else if (type->isBlockPointerType()) {
1284       note.flag = BLOCK_FIELD_IS_BLOCK;
1285     } else {
1286       note.flag = BLOCK_FIELD_IS_OBJECT;
1287     }
1288  */
1289 
1290 
1291 /// Generate the copy-helper function for a block closure object:
1292 ///   static void block_copy_helper(block_t *dst, block_t *src);
1293 /// The runtime will have previously initialized 'dst' by doing a
1294 /// bit-copy of 'src'.
1295 ///
1296 /// Note that this copies an entire block closure object to the heap;
1297 /// it should not be confused with a 'byref copy helper', which moves
1298 /// the contents of an individual __block variable to the heap.
1299 llvm::Constant *
1300 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1301   ASTContext &C = getContext();
1302 
1303   FunctionArgList args;
1304   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1305                             C.VoidPtrTy);
1306   args.push_back(&dstDecl);
1307   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1308                             C.VoidPtrTy);
1309   args.push_back(&srcDecl);
1310 
1311   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1312       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1313 
1314   // FIXME: it would be nice if these were mergeable with things with
1315   // identical semantics.
1316   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1317 
1318   llvm::Function *Fn =
1319     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1320                            "__copy_helper_block_", &CGM.getModule());
1321 
1322   IdentifierInfo *II
1323     = &CGM.getContext().Idents.get("__copy_helper_block_");
1324 
1325   FunctionDecl *FD = FunctionDecl::Create(C,
1326                                           C.getTranslationUnitDecl(),
1327                                           SourceLocation(),
1328                                           SourceLocation(), II, C.VoidTy,
1329                                           nullptr, SC_Static,
1330                                           false,
1331                                           false);
1332   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1333   StartFunction(FD, C.VoidTy, Fn, FI, args);
1334   // Create a scope with an artificial location for the body of this function.
1335   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1336   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1337 
1338   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1339   src = Builder.CreateLoad(src);
1340   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1341 
1342   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1343   dst = Builder.CreateLoad(dst);
1344   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1345 
1346   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1347 
1348   for (const auto &CI : blockDecl->captures()) {
1349     const VarDecl *variable = CI.getVariable();
1350     QualType type = variable->getType();
1351 
1352     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1353     if (capture.isConstant()) continue;
1354 
1355     const Expr *copyExpr = CI.getCopyExpr();
1356     BlockFieldFlags flags;
1357 
1358     bool useARCWeakCopy = false;
1359     bool useARCStrongCopy = false;
1360 
1361     if (copyExpr) {
1362       assert(!CI.isByRef());
1363       // don't bother computing flags
1364 
1365     } else if (CI.isByRef()) {
1366       flags = BLOCK_FIELD_IS_BYREF;
1367       if (type.isObjCGCWeak())
1368         flags |= BLOCK_FIELD_IS_WEAK;
1369 
1370     } else if (type->isObjCRetainableType()) {
1371       flags = BLOCK_FIELD_IS_OBJECT;
1372       bool isBlockPointer = type->isBlockPointerType();
1373       if (isBlockPointer)
1374         flags = BLOCK_FIELD_IS_BLOCK;
1375 
1376       // Special rules for ARC captures:
1377       if (getLangOpts().ObjCAutoRefCount) {
1378         Qualifiers qs = type.getQualifiers();
1379 
1380         // We need to register __weak direct captures with the runtime.
1381         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1382           useARCWeakCopy = true;
1383 
1384         // We need to retain the copied value for __strong direct captures.
1385         } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1386           // If it's a block pointer, we have to copy the block and
1387           // assign that to the destination pointer, so we might as
1388           // well use _Block_object_assign.  Otherwise we can avoid that.
1389           if (!isBlockPointer)
1390             useARCStrongCopy = true;
1391 
1392         // Otherwise the memcpy is fine.
1393         } else {
1394           continue;
1395         }
1396 
1397       // Non-ARC captures of retainable pointers are strong and
1398       // therefore require a call to _Block_object_assign.
1399       } else {
1400         // fall through
1401       }
1402     } else {
1403       continue;
1404     }
1405 
1406     unsigned index = capture.getIndex();
1407     llvm::Value *srcField =
1408         Builder.CreateStructGEP(blockInfo.StructureType, src, index);
1409     llvm::Value *dstField =
1410         Builder.CreateStructGEP(blockInfo.StructureType, dst, index);
1411 
1412     // If there's an explicit copy expression, we do that.
1413     if (copyExpr) {
1414       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1415     } else if (useARCWeakCopy) {
1416       EmitARCCopyWeak(dstField, srcField);
1417     } else {
1418       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1419       if (useARCStrongCopy) {
1420         // At -O0, store null into the destination field (so that the
1421         // storeStrong doesn't over-release) and then call storeStrong.
1422         // This is a workaround to not having an initStrong call.
1423         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1424           auto *ty = cast<llvm::PointerType>(srcValue->getType());
1425           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1426           Builder.CreateStore(null, dstField);
1427           EmitARCStoreStrongCall(dstField, srcValue, true);
1428 
1429         // With optimization enabled, take advantage of the fact that
1430         // the blocks runtime guarantees a memcpy of the block data, and
1431         // just emit a retain of the src field.
1432         } else {
1433           EmitARCRetainNonBlock(srcValue);
1434 
1435           // We don't need this anymore, so kill it.  It's not quite
1436           // worth the annoyance to avoid creating it in the first place.
1437           cast<llvm::Instruction>(dstField)->eraseFromParent();
1438         }
1439       } else {
1440         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1441         llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1442         llvm::Value *args[] = {
1443           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1444         };
1445 
1446         bool copyCanThrow = false;
1447         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1448           const Expr *copyExpr =
1449             CGM.getContext().getBlockVarCopyInits(variable);
1450           if (copyExpr) {
1451             copyCanThrow = true; // FIXME: reuse the noexcept logic
1452           }
1453         }
1454 
1455         if (copyCanThrow) {
1456           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1457         } else {
1458           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1459         }
1460       }
1461     }
1462   }
1463 
1464   FinishFunction();
1465 
1466   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1467 }
1468 
1469 /// Generate the destroy-helper function for a block closure object:
1470 ///   static void block_destroy_helper(block_t *theBlock);
1471 ///
1472 /// Note that this destroys a heap-allocated block closure object;
1473 /// it should not be confused with a 'byref destroy helper', which
1474 /// destroys the heap-allocated contents of an individual __block
1475 /// variable.
1476 llvm::Constant *
1477 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1478   ASTContext &C = getContext();
1479 
1480   FunctionArgList args;
1481   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1482                             C.VoidPtrTy);
1483   args.push_back(&srcDecl);
1484 
1485   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1486       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1487 
1488   // FIXME: We'd like to put these into a mergable by content, with
1489   // internal linkage.
1490   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1491 
1492   llvm::Function *Fn =
1493     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1494                            "__destroy_helper_block_", &CGM.getModule());
1495 
1496   IdentifierInfo *II
1497     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1498 
1499   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1500                                           SourceLocation(),
1501                                           SourceLocation(), II, C.VoidTy,
1502                                           nullptr, SC_Static,
1503                                           false, false);
1504   // Create a scope with an artificial location for the body of this function.
1505   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1506   StartFunction(FD, C.VoidTy, Fn, FI, args);
1507   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1508 
1509   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1510 
1511   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1512   src = Builder.CreateLoad(src);
1513   src = Builder.CreateBitCast(src, structPtrTy, "block");
1514 
1515   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1516 
1517   CodeGenFunction::RunCleanupsScope cleanups(*this);
1518 
1519   for (const auto &CI : blockDecl->captures()) {
1520     const VarDecl *variable = CI.getVariable();
1521     QualType type = variable->getType();
1522 
1523     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1524     if (capture.isConstant()) continue;
1525 
1526     BlockFieldFlags flags;
1527     const CXXDestructorDecl *dtor = nullptr;
1528 
1529     bool useARCWeakDestroy = false;
1530     bool useARCStrongDestroy = false;
1531 
1532     if (CI.isByRef()) {
1533       flags = BLOCK_FIELD_IS_BYREF;
1534       if (type.isObjCGCWeak())
1535         flags |= BLOCK_FIELD_IS_WEAK;
1536     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1537       if (record->hasTrivialDestructor())
1538         continue;
1539       dtor = record->getDestructor();
1540     } else if (type->isObjCRetainableType()) {
1541       flags = BLOCK_FIELD_IS_OBJECT;
1542       if (type->isBlockPointerType())
1543         flags = BLOCK_FIELD_IS_BLOCK;
1544 
1545       // Special rules for ARC captures.
1546       if (getLangOpts().ObjCAutoRefCount) {
1547         Qualifiers qs = type.getQualifiers();
1548 
1549         // Don't generate special dispose logic for a captured object
1550         // unless it's __strong or __weak.
1551         if (!qs.hasStrongOrWeakObjCLifetime())
1552           continue;
1553 
1554         // Support __weak direct captures.
1555         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1556           useARCWeakDestroy = true;
1557 
1558         // Tools really want us to use objc_storeStrong here.
1559         else
1560           useARCStrongDestroy = true;
1561       }
1562     } else {
1563       continue;
1564     }
1565 
1566     unsigned index = capture.getIndex();
1567     llvm::Value *srcField =
1568         Builder.CreateStructGEP(blockInfo.StructureType, src, index);
1569 
1570     // If there's an explicit copy expression, we do that.
1571     if (dtor) {
1572       PushDestructorCleanup(dtor, srcField);
1573 
1574     // If this is a __weak capture, emit the release directly.
1575     } else if (useARCWeakDestroy) {
1576       EmitARCDestroyWeak(srcField);
1577 
1578     // Destroy strong objects with a call if requested.
1579     } else if (useARCStrongDestroy) {
1580       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1581 
1582     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1583     // hard to just emit this as a cleanup if we wanted to make sure
1584     // that things were done in reverse.
1585     } else {
1586       llvm::Value *value = Builder.CreateLoad(srcField);
1587       value = Builder.CreateBitCast(value, VoidPtrTy);
1588       BuildBlockRelease(value, flags);
1589     }
1590   }
1591 
1592   cleanups.ForceCleanup();
1593 
1594   FinishFunction();
1595 
1596   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1597 }
1598 
1599 namespace {
1600 
1601 /// Emits the copy/dispose helper functions for a __block object of id type.
1602 class ObjectByrefHelpers final : public CodeGenModule::ByrefHelpers {
1603   BlockFieldFlags Flags;
1604 
1605 public:
1606   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1607     : ByrefHelpers(alignment), Flags(flags) {}
1608 
1609   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1610                 llvm::Value *srcField) override {
1611     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1612 
1613     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1614     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1615 
1616     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1617 
1618     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1619     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1620 
1621     llvm::Value *args[] = { destField, srcValue, flagsVal };
1622     CGF.EmitNounwindRuntimeCall(fn, args);
1623   }
1624 
1625   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1626     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1627     llvm::Value *value = CGF.Builder.CreateLoad(field);
1628 
1629     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1630   }
1631 
1632   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1633     id.AddInteger(Flags.getBitMask());
1634   }
1635 };
1636 
1637 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1638 class ARCWeakByrefHelpers final : public CodeGenModule::ByrefHelpers {
1639 public:
1640   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1641 
1642   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1643                 llvm::Value *srcField) override {
1644     CGF.EmitARCMoveWeak(destField, srcField);
1645   }
1646 
1647   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1648     CGF.EmitARCDestroyWeak(field);
1649   }
1650 
1651   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1652     // 0 is distinguishable from all pointers and byref flags
1653     id.AddInteger(0);
1654   }
1655 };
1656 
1657 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1658 /// that's not of block-pointer type.
1659 class ARCStrongByrefHelpers final : public CodeGenModule::ByrefHelpers {
1660 public:
1661   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1662 
1663   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1664                 llvm::Value *srcField) override {
1665     // Do a "move" by copying the value and then zeroing out the old
1666     // variable.
1667 
1668     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1669     value->setAlignment(Alignment.getQuantity());
1670 
1671     llvm::Value *null =
1672       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1673 
1674     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1675       llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1676       store->setAlignment(Alignment.getQuantity());
1677       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1678       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1679       return;
1680     }
1681     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1682     store->setAlignment(Alignment.getQuantity());
1683 
1684     store = CGF.Builder.CreateStore(null, srcField);
1685     store->setAlignment(Alignment.getQuantity());
1686   }
1687 
1688   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1689     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1690   }
1691 
1692   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1693     // 1 is distinguishable from all pointers and byref flags
1694     id.AddInteger(1);
1695   }
1696 };
1697 
1698 /// Emits the copy/dispose helpers for an ARC __block __strong
1699 /// variable that's of block-pointer type.
1700 class ARCStrongBlockByrefHelpers final : public CodeGenModule::ByrefHelpers {
1701 public:
1702   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1703 
1704   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1705                 llvm::Value *srcField) override {
1706     // Do the copy with objc_retainBlock; that's all that
1707     // _Block_object_assign would do anyway, and we'd have to pass the
1708     // right arguments to make sure it doesn't get no-op'ed.
1709     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1710     oldValue->setAlignment(Alignment.getQuantity());
1711 
1712     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1713 
1714     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1715     store->setAlignment(Alignment.getQuantity());
1716   }
1717 
1718   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1719     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1720   }
1721 
1722   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1723     // 2 is distinguishable from all pointers and byref flags
1724     id.AddInteger(2);
1725   }
1726 };
1727 
1728 /// Emits the copy/dispose helpers for a __block variable with a
1729 /// nontrivial copy constructor or destructor.
1730 class CXXByrefHelpers final : public CodeGenModule::ByrefHelpers {
1731   QualType VarType;
1732   const Expr *CopyExpr;
1733 
1734 public:
1735   CXXByrefHelpers(CharUnits alignment, QualType type,
1736                   const Expr *copyExpr)
1737     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1738 
1739   bool needsCopy() const override { return CopyExpr != nullptr; }
1740   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1741                 llvm::Value *srcField) override {
1742     if (!CopyExpr) return;
1743     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1744   }
1745 
1746   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1747     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1748     CGF.PushDestructorCleanup(VarType, field);
1749     CGF.PopCleanupBlocks(cleanupDepth);
1750   }
1751 
1752   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1753     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1754   }
1755 };
1756 } // end anonymous namespace
1757 
1758 static llvm::Constant *
1759 generateByrefCopyHelper(CodeGenFunction &CGF,
1760                         llvm::StructType &byrefType,
1761                         unsigned valueFieldIndex,
1762                         CodeGenModule::ByrefHelpers &byrefInfo) {
1763   ASTContext &Context = CGF.getContext();
1764 
1765   QualType R = Context.VoidTy;
1766 
1767   FunctionArgList args;
1768   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1769                         Context.VoidPtrTy);
1770   args.push_back(&dst);
1771 
1772   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1773                         Context.VoidPtrTy);
1774   args.push_back(&src);
1775 
1776   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1777       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1778 
1779   CodeGenTypes &Types = CGF.CGM.getTypes();
1780   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1781 
1782   // FIXME: We'd like to put these into a mergable by content, with
1783   // internal linkage.
1784   llvm::Function *Fn =
1785     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1786                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1787 
1788   IdentifierInfo *II
1789     = &Context.Idents.get("__Block_byref_object_copy_");
1790 
1791   FunctionDecl *FD = FunctionDecl::Create(Context,
1792                                           Context.getTranslationUnitDecl(),
1793                                           SourceLocation(),
1794                                           SourceLocation(), II, R, nullptr,
1795                                           SC_Static,
1796                                           false, false);
1797 
1798   CGF.StartFunction(FD, R, Fn, FI, args);
1799 
1800   if (byrefInfo.needsCopy()) {
1801     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1802 
1803     // dst->x
1804     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1805     destField = CGF.Builder.CreateLoad(destField);
1806     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1807     destField = CGF.Builder.CreateStructGEP(&byrefType, destField,
1808                                             valueFieldIndex, "x");
1809 
1810     // src->x
1811     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1812     srcField = CGF.Builder.CreateLoad(srcField);
1813     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1814     srcField =
1815         CGF.Builder.CreateStructGEP(&byrefType, srcField, valueFieldIndex, "x");
1816 
1817     byrefInfo.emitCopy(CGF, destField, srcField);
1818   }
1819 
1820   CGF.FinishFunction();
1821 
1822   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1823 }
1824 
1825 /// Build the copy helper for a __block variable.
1826 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1827                                             llvm::StructType &byrefType,
1828                                             unsigned byrefValueIndex,
1829                                             CodeGenModule::ByrefHelpers &info) {
1830   CodeGenFunction CGF(CGM);
1831   return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1832 }
1833 
1834 /// Generate code for a __block variable's dispose helper.
1835 static llvm::Constant *
1836 generateByrefDisposeHelper(CodeGenFunction &CGF,
1837                            llvm::StructType &byrefType,
1838                            unsigned byrefValueIndex,
1839                            CodeGenModule::ByrefHelpers &byrefInfo) {
1840   ASTContext &Context = CGF.getContext();
1841   QualType R = Context.VoidTy;
1842 
1843   FunctionArgList args;
1844   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1845                         Context.VoidPtrTy);
1846   args.push_back(&src);
1847 
1848   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1849       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1850 
1851   CodeGenTypes &Types = CGF.CGM.getTypes();
1852   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1853 
1854   // FIXME: We'd like to put these into a mergable by content, with
1855   // internal linkage.
1856   llvm::Function *Fn =
1857     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1858                            "__Block_byref_object_dispose_",
1859                            &CGF.CGM.getModule());
1860 
1861   IdentifierInfo *II
1862     = &Context.Idents.get("__Block_byref_object_dispose_");
1863 
1864   FunctionDecl *FD = FunctionDecl::Create(Context,
1865                                           Context.getTranslationUnitDecl(),
1866                                           SourceLocation(),
1867                                           SourceLocation(), II, R, nullptr,
1868                                           SC_Static,
1869                                           false, false);
1870   CGF.StartFunction(FD, R, Fn, FI, args);
1871 
1872   if (byrefInfo.needsDispose()) {
1873     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1874     V = CGF.Builder.CreateLoad(V);
1875     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1876     V = CGF.Builder.CreateStructGEP(&byrefType, V, byrefValueIndex, "x");
1877 
1878     byrefInfo.emitDispose(CGF, V);
1879   }
1880 
1881   CGF.FinishFunction();
1882 
1883   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1884 }
1885 
1886 /// Build the dispose helper for a __block variable.
1887 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1888                                               llvm::StructType &byrefType,
1889                                                unsigned byrefValueIndex,
1890                                             CodeGenModule::ByrefHelpers &info) {
1891   CodeGenFunction CGF(CGM);
1892   return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
1893 }
1894 
1895 /// Lazily build the copy and dispose helpers for a __block variable
1896 /// with the given information.
1897 template <class T>
1898 static T *buildByrefHelpers(CodeGenModule &CGM, llvm::StructType &byrefTy,
1899                             unsigned byrefValueIndex, T byrefInfo) {
1900   // Increase the field's alignment to be at least pointer alignment,
1901   // since the layout of the byref struct will guarantee at least that.
1902   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1903                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1904 
1905   llvm::FoldingSetNodeID id;
1906   byrefInfo.Profile(id);
1907 
1908   void *insertPos;
1909   CodeGenModule::ByrefHelpers *node
1910     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1911   if (node) return static_cast<T*>(node);
1912 
1913   byrefInfo.CopyHelper =
1914     buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1915   byrefInfo.DisposeHelper =
1916     buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1917 
1918   T *copy = new (CGM.getContext()) T(std::move(byrefInfo));
1919   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1920   return copy;
1921 }
1922 
1923 /// Build the copy and dispose helpers for the given __block variable
1924 /// emission.  Places the helpers in the global cache.  Returns null
1925 /// if no helpers are required.
1926 CodeGenModule::ByrefHelpers *
1927 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1928                                    const AutoVarEmission &emission) {
1929   const VarDecl &var = *emission.Variable;
1930   QualType type = var.getType();
1931 
1932   unsigned byrefValueIndex = getByRefValueLLVMField(&var).second;
1933 
1934   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1935     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1936     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1937 
1938     return ::buildByrefHelpers(
1939         CGM, byrefType, byrefValueIndex,
1940         CXXByrefHelpers(emission.Alignment, type, copyExpr));
1941   }
1942 
1943   // Otherwise, if we don't have a retainable type, there's nothing to do.
1944   // that the runtime does extra copies.
1945   if (!type->isObjCRetainableType()) return nullptr;
1946 
1947   Qualifiers qs = type.getQualifiers();
1948 
1949   // If we have lifetime, that dominates.
1950   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1951     assert(getLangOpts().ObjCAutoRefCount);
1952 
1953     switch (lifetime) {
1954     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1955 
1956     // These are just bits as far as the runtime is concerned.
1957     case Qualifiers::OCL_ExplicitNone:
1958     case Qualifiers::OCL_Autoreleasing:
1959       return nullptr;
1960 
1961     // Tell the runtime that this is ARC __weak, called by the
1962     // byref routines.
1963     case Qualifiers::OCL_Weak:
1964       return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
1965                                  ARCWeakByrefHelpers(emission.Alignment));
1966 
1967     // ARC __strong __block variables need to be retained.
1968     case Qualifiers::OCL_Strong:
1969       // Block pointers need to be copied, and there's no direct
1970       // transfer possible.
1971       if (type->isBlockPointerType()) {
1972         return ::buildByrefHelpers(
1973             CGM, byrefType, byrefValueIndex,
1974             ARCStrongBlockByrefHelpers(emission.Alignment));
1975 
1976       // Otherwise, we transfer ownership of the retain from the stack
1977       // to the heap.
1978       } else {
1979         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
1980                                    ARCStrongByrefHelpers(emission.Alignment));
1981       }
1982     }
1983     llvm_unreachable("fell out of lifetime switch!");
1984   }
1985 
1986   BlockFieldFlags flags;
1987   if (type->isBlockPointerType()) {
1988     flags |= BLOCK_FIELD_IS_BLOCK;
1989   } else if (CGM.getContext().isObjCNSObjectType(type) ||
1990              type->isObjCObjectPointerType()) {
1991     flags |= BLOCK_FIELD_IS_OBJECT;
1992   } else {
1993     return nullptr;
1994   }
1995 
1996   if (type.isObjCGCWeak())
1997     flags |= BLOCK_FIELD_IS_WEAK;
1998 
1999   return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
2000                              ObjectByrefHelpers(emission.Alignment, flags));
2001 }
2002 
2003 std::pair<llvm::Type *, unsigned>
2004 CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
2005   assert(ByRefValueInfo.count(VD) && "Did not find value!");
2006 
2007   return ByRefValueInfo.find(VD)->second;
2008 }
2009 
2010 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2011                                                      const VarDecl *V) {
2012   auto P = getByRefValueLLVMField(V);
2013   llvm::Value *Loc =
2014       Builder.CreateStructGEP(P.first, BaseAddr, 1, "forwarding");
2015   Loc = Builder.CreateLoad(Loc);
2016   Loc = Builder.CreateStructGEP(P.first, Loc, P.second, V->getNameAsString());
2017   return Loc;
2018 }
2019 
2020 /// BuildByRefType - This routine changes a __block variable declared as T x
2021 ///   into:
2022 ///
2023 ///      struct {
2024 ///        void *__isa;
2025 ///        void *__forwarding;
2026 ///        int32_t __flags;
2027 ///        int32_t __size;
2028 ///        void *__copy_helper;       // only if needed
2029 ///        void *__destroy_helper;    // only if needed
2030 ///        void *__byref_variable_layout;// only if needed
2031 ///        char padding[X];           // only if needed
2032 ///        T x;
2033 ///      } x
2034 ///
2035 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2036   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
2037   if (Info.first)
2038     return Info.first;
2039 
2040   QualType Ty = D->getType();
2041 
2042   SmallVector<llvm::Type *, 8> types;
2043 
2044   llvm::StructType *ByRefType =
2045     llvm::StructType::create(getLLVMContext(),
2046                              "struct.__block_byref_" + D->getNameAsString());
2047 
2048   // void *__isa;
2049   types.push_back(Int8PtrTy);
2050 
2051   // void *__forwarding;
2052   types.push_back(llvm::PointerType::getUnqual(ByRefType));
2053 
2054   // int32_t __flags;
2055   types.push_back(Int32Ty);
2056 
2057   // int32_t __size;
2058   types.push_back(Int32Ty);
2059   // Note that this must match *exactly* the logic in buildByrefHelpers.
2060   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2061   if (HasCopyAndDispose) {
2062     /// void *__copy_helper;
2063     types.push_back(Int8PtrTy);
2064 
2065     /// void *__destroy_helper;
2066     types.push_back(Int8PtrTy);
2067   }
2068   bool HasByrefExtendedLayout = false;
2069   Qualifiers::ObjCLifetime Lifetime;
2070   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2071       HasByrefExtendedLayout)
2072     /// void *__byref_variable_layout;
2073     types.push_back(Int8PtrTy);
2074 
2075   bool Packed = false;
2076   CharUnits Align = getContext().getDeclAlign(D);
2077   if (Align >
2078       getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
2079     // We have to insert padding.
2080 
2081     // The struct above has 2 32-bit integers.
2082     unsigned CurrentOffsetInBytes = 4 * 2;
2083 
2084     // And either 2, 3, 4 or 5 pointers.
2085     unsigned noPointers = 2;
2086     if (HasCopyAndDispose)
2087       noPointers += 2;
2088     if (HasByrefExtendedLayout)
2089       noPointers += 1;
2090 
2091     CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
2092 
2093     // Align the offset.
2094     unsigned AlignedOffsetInBytes =
2095       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2096 
2097     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2098     if (NumPaddingBytes > 0) {
2099       llvm::Type *Ty = Int8Ty;
2100       // FIXME: We need a sema error for alignment larger than the minimum of
2101       // the maximal stack alignment and the alignment of malloc on the system.
2102       if (NumPaddingBytes > 1)
2103         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2104 
2105       types.push_back(Ty);
2106 
2107       // We want a packed struct.
2108       Packed = true;
2109     }
2110   }
2111 
2112   // T x;
2113   types.push_back(ConvertTypeForMem(Ty));
2114 
2115   ByRefType->setBody(types, Packed);
2116 
2117   Info.first = ByRefType;
2118 
2119   Info.second = types.size() - 1;
2120 
2121   return Info.first;
2122 }
2123 
2124 /// Initialize the structural components of a __block variable, i.e.
2125 /// everything but the actual object.
2126 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2127   // Find the address of the local.
2128   llvm::Value *addr = emission.Address;
2129 
2130   // That's an alloca of the byref structure type.
2131   llvm::StructType *byrefType = cast<llvm::StructType>(
2132                  cast<llvm::PointerType>(addr->getType())->getElementType());
2133 
2134   // Build the byref helpers if necessary.  This is null if we don't need any.
2135   CodeGenModule::ByrefHelpers *helpers =
2136     buildByrefHelpers(*byrefType, emission);
2137 
2138   const VarDecl &D = *emission.Variable;
2139   QualType type = D.getType();
2140 
2141   bool HasByrefExtendedLayout;
2142   Qualifiers::ObjCLifetime ByrefLifetime;
2143   bool ByRefHasLifetime =
2144     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2145 
2146   llvm::Value *V;
2147 
2148   // Initialize the 'isa', which is just 0 or 1.
2149   int isa = 0;
2150   if (type.isObjCGCWeak())
2151     isa = 1;
2152   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2153   Builder.CreateStore(V,
2154                       Builder.CreateStructGEP(nullptr, addr, 0, "byref.isa"));
2155 
2156   // Store the address of the variable into its own forwarding pointer.
2157   Builder.CreateStore(
2158       addr, Builder.CreateStructGEP(nullptr, addr, 1, "byref.forwarding"));
2159 
2160   // Blocks ABI:
2161   //   c) the flags field is set to either 0 if no helper functions are
2162   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2163   BlockFlags flags;
2164   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2165   if (ByRefHasLifetime) {
2166     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2167       else switch (ByrefLifetime) {
2168         case Qualifiers::OCL_Strong:
2169           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2170           break;
2171         case Qualifiers::OCL_Weak:
2172           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2173           break;
2174         case Qualifiers::OCL_ExplicitNone:
2175           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2176           break;
2177         case Qualifiers::OCL_None:
2178           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2179             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2180           break;
2181         default:
2182           break;
2183       }
2184     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2185       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2186       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2187         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2188       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2189         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2190         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2191           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2192         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2193           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2194         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2195           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2196         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2197           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2198         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2199           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2200       }
2201       printf("\n");
2202     }
2203   }
2204 
2205   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2206                       Builder.CreateStructGEP(nullptr, addr, 2, "byref.flags"));
2207 
2208   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2209   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2210   Builder.CreateStore(V,
2211                       Builder.CreateStructGEP(nullptr, addr, 3, "byref.size"));
2212 
2213   if (helpers) {
2214     llvm::Value *copy_helper = Builder.CreateStructGEP(nullptr, addr, 4);
2215     Builder.CreateStore(helpers->CopyHelper, copy_helper);
2216 
2217     llvm::Value *destroy_helper = Builder.CreateStructGEP(nullptr, addr, 5);
2218     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2219   }
2220   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2221     llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2222     llvm::Value *ByrefInfoAddr =
2223         Builder.CreateStructGEP(nullptr, addr, helpers ? 6 : 4, "byref.layout");
2224     // cast destination to pointer to source type.
2225     llvm::Type *DesTy = ByrefLayoutInfo->getType();
2226     DesTy = DesTy->getPointerTo();
2227     llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2228     Builder.CreateStore(ByrefLayoutInfo, BC);
2229   }
2230 }
2231 
2232 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2233   llvm::Value *F = CGM.getBlockObjectDispose();
2234   llvm::Value *args[] = {
2235     Builder.CreateBitCast(V, Int8PtrTy),
2236     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2237   };
2238   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2239 }
2240 
2241 namespace {
2242   struct CallBlockRelease : EHScopeStack::Cleanup {
2243     llvm::Value *Addr;
2244     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2245 
2246     void Emit(CodeGenFunction &CGF, Flags flags) override {
2247       // Should we be passing FIELD_IS_WEAK here?
2248       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2249     }
2250   };
2251 }
2252 
2253 /// Enter a cleanup to destroy a __block variable.  Note that this
2254 /// cleanup should be a no-op if the variable hasn't left the stack
2255 /// yet; if a cleanup is required for the variable itself, that needs
2256 /// to be done externally.
2257 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2258   // We don't enter this cleanup if we're in pure-GC mode.
2259   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2260     return;
2261 
2262   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2263 }
2264 
2265 /// Adjust the declaration of something from the blocks API.
2266 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2267                                          llvm::Constant *C) {
2268   if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2269 
2270   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2271   if (GV->isDeclaration() && GV->hasExternalLinkage())
2272     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2273 }
2274 
2275 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2276   if (BlockObjectDispose)
2277     return BlockObjectDispose;
2278 
2279   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2280   llvm::FunctionType *fty
2281     = llvm::FunctionType::get(VoidTy, args, false);
2282   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2283   configureBlocksRuntimeObject(*this, BlockObjectDispose);
2284   return BlockObjectDispose;
2285 }
2286 
2287 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2288   if (BlockObjectAssign)
2289     return BlockObjectAssign;
2290 
2291   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2292   llvm::FunctionType *fty
2293     = llvm::FunctionType::get(VoidTy, args, false);
2294   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2295   configureBlocksRuntimeObject(*this, BlockObjectAssign);
2296   return BlockObjectAssign;
2297 }
2298 
2299 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2300   if (NSConcreteGlobalBlock)
2301     return NSConcreteGlobalBlock;
2302 
2303   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2304                                                 Int8PtrTy->getPointerTo(),
2305                                                 nullptr);
2306   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2307   return NSConcreteGlobalBlock;
2308 }
2309 
2310 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2311   if (NSConcreteStackBlock)
2312     return NSConcreteStackBlock;
2313 
2314   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2315                                                Int8PtrTy->getPointerTo(),
2316                                                nullptr);
2317   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2318   return NSConcreteStackBlock;
2319 }
2320