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