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