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