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                                                 .getQuantity()),
750                      /*captured by init*/ false);
751     }
752 
753     // Activate the cleanup if layout pushed one.
754     if (!ci->isByRef()) {
755       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
756       if (cleanup.isValid())
757         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
758     }
759   }
760 
761   // Cast to the converted block-pointer type, which happens (somewhat
762   // unfortunately) to be a pointer to function type.
763   llvm::Value *result =
764     Builder.CreateBitCast(blockAddr,
765                           ConvertType(blockInfo.getBlockExpr()->getType()));
766 
767   return result;
768 }
769 
770 
771 llvm::Type *CodeGenModule::getBlockDescriptorType() {
772   if (BlockDescriptorType)
773     return BlockDescriptorType;
774 
775   llvm::Type *UnsignedLongTy =
776     getTypes().ConvertType(getContext().UnsignedLongTy);
777 
778   // struct __block_descriptor {
779   //   unsigned long reserved;
780   //   unsigned long block_size;
781   //
782   //   // later, the following will be added
783   //
784   //   struct {
785   //     void (*copyHelper)();
786   //     void (*copyHelper)();
787   //   } helpers;                // !!! optional
788   //
789   //   const char *signature;   // the block signature
790   //   const char *layout;      // reserved
791   // };
792   BlockDescriptorType =
793     llvm::StructType::create("struct.__block_descriptor",
794                              UnsignedLongTy, UnsignedLongTy, NULL);
795 
796   // Now form a pointer to that.
797   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
798   return BlockDescriptorType;
799 }
800 
801 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
802   if (GenericBlockLiteralType)
803     return GenericBlockLiteralType;
804 
805   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
806 
807   // struct __block_literal_generic {
808   //   void *__isa;
809   //   int __flags;
810   //   int __reserved;
811   //   void (*__invoke)(void *);
812   //   struct __block_descriptor *__descriptor;
813   // };
814   GenericBlockLiteralType =
815     llvm::StructType::create("struct.__block_literal_generic",
816                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
817                              BlockDescPtrTy, NULL);
818 
819   return GenericBlockLiteralType;
820 }
821 
822 
823 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
824                                           ReturnValueSlot ReturnValue) {
825   const BlockPointerType *BPT =
826     E->getCallee()->getType()->getAs<BlockPointerType>();
827 
828   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
829 
830   // Get a pointer to the generic block literal.
831   llvm::Type *BlockLiteralTy =
832     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
833 
834   // Bitcast the callee to a block literal.
835   llvm::Value *BlockLiteral =
836     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
837 
838   // Get the function pointer from the literal.
839   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
840 
841   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
842 
843   // Add the block literal.
844   CallArgList Args;
845   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
846 
847   QualType FnType = BPT->getPointeeType();
848 
849   // And the rest of the arguments.
850   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
851                E->arg_begin(), E->arg_end());
852 
853   // Load the function.
854   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
855 
856   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
857   const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
858 
859   // Cast the function pointer to the right type.
860   llvm::Type *BlockFTy =
861     CGM.getTypes().GetFunctionType(FnInfo, false);
862 
863   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
864   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
865 
866   // And call the block.
867   return EmitCall(FnInfo, Func, ReturnValue, Args);
868 }
869 
870 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
871                                                  bool isByRef) {
872   assert(BlockInfo && "evaluating block ref without block information?");
873   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
874 
875   // Handle constant captures.
876   if (capture.isConstant()) return LocalDeclMap[variable];
877 
878   llvm::Value *addr =
879     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
880                             "block.capture.addr");
881 
882   if (isByRef) {
883     // addr should be a void** right now.  Load, then cast the result
884     // to byref*.
885 
886     addr = Builder.CreateLoad(addr);
887     llvm::PointerType *byrefPointerType
888       = llvm::PointerType::get(BuildByRefType(variable), 0);
889     addr = Builder.CreateBitCast(addr, byrefPointerType,
890                                  "byref.addr");
891 
892     // Follow the forwarding pointer.
893     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
894     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
895 
896     // Cast back to byref* and GEP over to the actual object.
897     addr = Builder.CreateBitCast(addr, byrefPointerType);
898     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
899                                    variable->getNameAsString());
900   }
901 
902   if (variable->getType()->isReferenceType())
903     addr = Builder.CreateLoad(addr, "ref.tmp");
904 
905   return addr;
906 }
907 
908 llvm::Constant *
909 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
910                                     const char *name) {
911   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
912   blockInfo.BlockExpression = blockExpr;
913 
914   // Compute information about the layout, etc., of this block.
915   computeBlockInfo(*this, blockInfo);
916 
917   // Using that metadata, generate the actual block function.
918   llvm::Constant *blockFn;
919   {
920     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
921     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
922                                                            blockInfo,
923                                                            0, LocalDeclMap);
924   }
925   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
926 
927   return buildGlobalBlock(*this, blockInfo, blockFn);
928 }
929 
930 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
931                                         const CGBlockInfo &blockInfo,
932                                         llvm::Constant *blockFn) {
933   assert(blockInfo.CanBeGlobal);
934 
935   // Generate the constants for the block literal initializer.
936   llvm::Constant *fields[BlockHeaderSize];
937 
938   // isa
939   fields[0] = CGM.getNSConcreteGlobalBlock();
940 
941   // __flags
942   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
943   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
944 
945   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
946 
947   // Reserved
948   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
949 
950   // Function
951   fields[3] = blockFn;
952 
953   // Descriptor
954   fields[4] = buildBlockDescriptor(CGM, blockInfo);
955 
956   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
957 
958   llvm::GlobalVariable *literal =
959     new llvm::GlobalVariable(CGM.getModule(),
960                              init->getType(),
961                              /*constant*/ true,
962                              llvm::GlobalVariable::InternalLinkage,
963                              init,
964                              "__block_literal_global");
965   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
966 
967   // Return a constant of the appropriately-casted type.
968   llvm::Type *requiredType =
969     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
970   return llvm::ConstantExpr::getBitCast(literal, requiredType);
971 }
972 
973 llvm::Function *
974 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
975                                        const CGBlockInfo &blockInfo,
976                                        const Decl *outerFnDecl,
977                                        const DeclMapTy &ldm) {
978   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
979 
980   // Check if we should generate debug info for this block function.
981   if (CGM.getModuleDebugInfo())
982     DebugInfo = CGM.getModuleDebugInfo();
983 
984   BlockInfo = &blockInfo;
985 
986   // Arrange for local static and local extern declarations to appear
987   // to be local to this function as well, in case they're directly
988   // referenced in a block.
989   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
990     const VarDecl *var = dyn_cast<VarDecl>(i->first);
991     if (var && !var->hasLocalStorage())
992       LocalDeclMap[var] = i->second;
993   }
994 
995   // Begin building the function declaration.
996 
997   // Build the argument list.
998   FunctionArgList args;
999 
1000   // The first argument is the block pointer.  Just take it as a void*
1001   // and cast it later.
1002   QualType selfTy = getContext().VoidPtrTy;
1003   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1004 
1005   ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1006                              SourceLocation(), II, selfTy);
1007   args.push_back(&selfDecl);
1008 
1009   // Now add the rest of the parameters.
1010   for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1011        e = blockDecl->param_end(); i != e; ++i)
1012     args.push_back(*i);
1013 
1014   // Create the function declaration.
1015   const FunctionProtoType *fnType =
1016     cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
1017   const CGFunctionInfo &fnInfo =
1018     CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
1019                                    fnType->getExtInfo());
1020   if (CGM.ReturnTypeUsesSRet(fnInfo))
1021     blockInfo.UsesStret = true;
1022 
1023   llvm::FunctionType *fnLLVMType =
1024     CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
1025 
1026   MangleBuffer name;
1027   CGM.getBlockMangledName(GD, name, blockDecl);
1028   llvm::Function *fn =
1029     llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1030                            name.getString(), &CGM.getModule());
1031   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1032 
1033   // Begin generating the function.
1034   StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
1035                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1036   CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
1037 
1038   // Okay.  Undo some of what StartFunction did.
1039 
1040   // Pull the 'self' reference out of the local decl map.
1041   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1042   LocalDeclMap.erase(&selfDecl);
1043   BlockPointer = Builder.CreateBitCast(blockAddr,
1044                                        blockInfo.StructureType->getPointerTo(),
1045                                        "block");
1046 
1047   // If we have a C++ 'this' reference, go ahead and force it into
1048   // existence now.
1049   if (blockDecl->capturesCXXThis()) {
1050     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1051                                                 blockInfo.CXXThisIndex,
1052                                                 "block.captured-this");
1053     CXXThisValue = Builder.CreateLoad(addr, "this");
1054   }
1055 
1056   // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1057   // appease it.
1058   if (const ObjCMethodDecl *method
1059         = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1060     const VarDecl *self = method->getSelfDecl();
1061 
1062     // There might not be a capture for 'self', but if there is...
1063     if (blockInfo.Captures.count(self)) {
1064       const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1065       llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1066                                                       capture.getIndex(),
1067                                                       "block.captured-self");
1068       LocalDeclMap[self] = selfAddr;
1069     }
1070   }
1071 
1072   // Also force all the constant captures.
1073   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1074          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1075     const VarDecl *variable = ci->getVariable();
1076     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1077     if (!capture.isConstant()) continue;
1078 
1079     unsigned align = getContext().getDeclAlign(variable).getQuantity();
1080 
1081     llvm::AllocaInst *alloca =
1082       CreateMemTemp(variable->getType(), "block.captured-const");
1083     alloca->setAlignment(align);
1084 
1085     Builder.CreateStore(capture.getConstant(), alloca, align);
1086 
1087     LocalDeclMap[variable] = alloca;
1088   }
1089 
1090   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1091   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1092   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1093   --entry_ptr;
1094 
1095   EmitStmt(blockDecl->getBody());
1096 
1097   // Remember where we were...
1098   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1099 
1100   // Go back to the entry.
1101   ++entry_ptr;
1102   Builder.SetInsertPoint(entry, entry_ptr);
1103 
1104   // Emit debug information for all the BlockDeclRefDecls.
1105   // FIXME: also for 'this'
1106   if (CGDebugInfo *DI = getDebugInfo()) {
1107     for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1108            ce = blockDecl->capture_end(); ci != ce; ++ci) {
1109       const VarDecl *variable = ci->getVariable();
1110       DI->EmitLocation(Builder, variable->getLocation());
1111 
1112       const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1113       if (capture.isConstant()) {
1114         DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1115                                       Builder);
1116         continue;
1117       }
1118 
1119       DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1120                                             Builder, blockInfo);
1121     }
1122   }
1123 
1124   // And resume where we left off.
1125   if (resume == 0)
1126     Builder.ClearInsertionPoint();
1127   else
1128     Builder.SetInsertPoint(resume);
1129 
1130   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1131 
1132   return fn;
1133 }
1134 
1135 /*
1136     notes.push_back(HelperInfo());
1137     HelperInfo &note = notes.back();
1138     note.index = capture.getIndex();
1139     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1140     note.cxxbar_import = ci->getCopyExpr();
1141 
1142     if (ci->isByRef()) {
1143       note.flag = BLOCK_FIELD_IS_BYREF;
1144       if (type.isObjCGCWeak())
1145         note.flag |= BLOCK_FIELD_IS_WEAK;
1146     } else if (type->isBlockPointerType()) {
1147       note.flag = BLOCK_FIELD_IS_BLOCK;
1148     } else {
1149       note.flag = BLOCK_FIELD_IS_OBJECT;
1150     }
1151  */
1152 
1153 
1154 
1155 llvm::Constant *
1156 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1157   ASTContext &C = getContext();
1158 
1159   FunctionArgList args;
1160   ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1161   args.push_back(&dstDecl);
1162   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1163   args.push_back(&srcDecl);
1164 
1165   const CGFunctionInfo &FI =
1166       CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
1167 
1168   // FIXME: it would be nice if these were mergeable with things with
1169   // identical semantics.
1170   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
1171 
1172   llvm::Function *Fn =
1173     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1174                            "__copy_helper_block_", &CGM.getModule());
1175 
1176   IdentifierInfo *II
1177     = &CGM.getContext().Idents.get("__copy_helper_block_");
1178 
1179   // Check if we should generate debug info for this block helper function.
1180   if (CGM.getModuleDebugInfo())
1181     DebugInfo = CGM.getModuleDebugInfo();
1182 
1183   FunctionDecl *FD = FunctionDecl::Create(C,
1184                                           C.getTranslationUnitDecl(),
1185                                           SourceLocation(),
1186                                           SourceLocation(), II, C.VoidTy, 0,
1187                                           SC_Static,
1188                                           SC_None,
1189                                           false,
1190                                           true);
1191   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1192 
1193   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1194 
1195   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1196   src = Builder.CreateLoad(src);
1197   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1198 
1199   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1200   dst = Builder.CreateLoad(dst);
1201   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1202 
1203   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1204 
1205   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1206          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1207     const VarDecl *variable = ci->getVariable();
1208     QualType type = variable->getType();
1209 
1210     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1211     if (capture.isConstant()) continue;
1212 
1213     const Expr *copyExpr = ci->getCopyExpr();
1214     BlockFieldFlags flags;
1215 
1216     bool isARCWeakCapture = false;
1217 
1218     if (copyExpr) {
1219       assert(!ci->isByRef());
1220       // don't bother computing flags
1221 
1222     } else if (ci->isByRef()) {
1223       flags = BLOCK_FIELD_IS_BYREF;
1224       if (type.isObjCGCWeak())
1225         flags |= BLOCK_FIELD_IS_WEAK;
1226 
1227     } else if (type->isObjCRetainableType()) {
1228       flags = BLOCK_FIELD_IS_OBJECT;
1229       if (type->isBlockPointerType())
1230         flags = BLOCK_FIELD_IS_BLOCK;
1231 
1232       // Special rules for ARC captures:
1233       if (getLangOptions().ObjCAutoRefCount) {
1234         Qualifiers qs = type.getQualifiers();
1235 
1236         // Don't generate special copy logic for a captured object
1237         // unless it's __strong or __weak.
1238         if (!qs.hasStrongOrWeakObjCLifetime())
1239           continue;
1240 
1241         // Support __weak direct captures.
1242         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1243           isARCWeakCapture = true;
1244       }
1245     } else {
1246       continue;
1247     }
1248 
1249     unsigned index = capture.getIndex();
1250     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1251     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1252 
1253     // If there's an explicit copy expression, we do that.
1254     if (copyExpr) {
1255       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1256     } else if (isARCWeakCapture) {
1257       EmitARCCopyWeak(dstField, srcField);
1258     } else {
1259       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1260       srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1261       llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1262       Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1263                           llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1264     }
1265   }
1266 
1267   FinishFunction();
1268 
1269   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1270 }
1271 
1272 llvm::Constant *
1273 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1274   ASTContext &C = getContext();
1275 
1276   FunctionArgList args;
1277   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1278   args.push_back(&srcDecl);
1279 
1280   const CGFunctionInfo &FI =
1281       CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
1282 
1283   // FIXME: We'd like to put these into a mergable by content, with
1284   // internal linkage.
1285   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
1286 
1287   llvm::Function *Fn =
1288     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1289                            "__destroy_helper_block_", &CGM.getModule());
1290 
1291   // Check if we should generate debug info for this block destroy function.
1292   if (CGM.getModuleDebugInfo())
1293     DebugInfo = CGM.getModuleDebugInfo();
1294 
1295   IdentifierInfo *II
1296     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1297 
1298   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1299                                           SourceLocation(),
1300                                           SourceLocation(), II, C.VoidTy, 0,
1301                                           SC_Static,
1302                                           SC_None,
1303                                           false, true);
1304   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1305 
1306   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1307 
1308   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1309   src = Builder.CreateLoad(src);
1310   src = Builder.CreateBitCast(src, structPtrTy, "block");
1311 
1312   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1313 
1314   CodeGenFunction::RunCleanupsScope cleanups(*this);
1315 
1316   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1317          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1318     const VarDecl *variable = ci->getVariable();
1319     QualType type = variable->getType();
1320 
1321     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1322     if (capture.isConstant()) continue;
1323 
1324     BlockFieldFlags flags;
1325     const CXXDestructorDecl *dtor = 0;
1326 
1327     bool isARCWeakCapture = false;
1328 
1329     if (ci->isByRef()) {
1330       flags = BLOCK_FIELD_IS_BYREF;
1331       if (type.isObjCGCWeak())
1332         flags |= BLOCK_FIELD_IS_WEAK;
1333     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1334       if (record->hasTrivialDestructor())
1335         continue;
1336       dtor = record->getDestructor();
1337     } else if (type->isObjCRetainableType()) {
1338       flags = BLOCK_FIELD_IS_OBJECT;
1339       if (type->isBlockPointerType())
1340         flags = BLOCK_FIELD_IS_BLOCK;
1341 
1342       // Special rules for ARC captures.
1343       if (getLangOptions().ObjCAutoRefCount) {
1344         Qualifiers qs = type.getQualifiers();
1345 
1346         // Don't generate special dispose logic for a captured object
1347         // unless it's __strong or __weak.
1348         if (!qs.hasStrongOrWeakObjCLifetime())
1349           continue;
1350 
1351         // Support __weak direct captures.
1352         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1353           isARCWeakCapture = true;
1354       }
1355     } else {
1356       continue;
1357     }
1358 
1359     unsigned index = capture.getIndex();
1360     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1361 
1362     // If there's an explicit copy expression, we do that.
1363     if (dtor) {
1364       PushDestructorCleanup(dtor, srcField);
1365 
1366     // If this is a __weak capture, emit the release directly.
1367     } else if (isARCWeakCapture) {
1368       EmitARCDestroyWeak(srcField);
1369 
1370     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1371     // hard to just emit this as a cleanup if we wanted to make sure
1372     // that things were done in reverse.
1373     } else {
1374       llvm::Value *value = Builder.CreateLoad(srcField);
1375       value = Builder.CreateBitCast(value, VoidPtrTy);
1376       BuildBlockRelease(value, flags);
1377     }
1378   }
1379 
1380   cleanups.ForceCleanup();
1381 
1382   FinishFunction();
1383 
1384   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1385 }
1386 
1387 namespace {
1388 
1389 /// Emits the copy/dispose helper functions for a __block object of id type.
1390 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1391   BlockFieldFlags Flags;
1392 
1393 public:
1394   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1395     : ByrefHelpers(alignment), Flags(flags) {}
1396 
1397   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1398                 llvm::Value *srcField) {
1399     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1400 
1401     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1402     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1403 
1404     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1405 
1406     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1407     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1408     CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1409   }
1410 
1411   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1412     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1413     llvm::Value *value = CGF.Builder.CreateLoad(field);
1414 
1415     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1416   }
1417 
1418   void profileImpl(llvm::FoldingSetNodeID &id) const {
1419     id.AddInteger(Flags.getBitMask());
1420   }
1421 };
1422 
1423 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1424 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1425 public:
1426   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1427 
1428   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1429                 llvm::Value *srcField) {
1430     CGF.EmitARCMoveWeak(destField, srcField);
1431   }
1432 
1433   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1434     CGF.EmitARCDestroyWeak(field);
1435   }
1436 
1437   void profileImpl(llvm::FoldingSetNodeID &id) const {
1438     // 0 is distinguishable from all pointers and byref flags
1439     id.AddInteger(0);
1440   }
1441 };
1442 
1443 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1444 /// that's not of block-pointer type.
1445 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1446 public:
1447   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1448 
1449   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1450                 llvm::Value *srcField) {
1451     // Do a "move" by copying the value and then zeroing out the old
1452     // variable.
1453 
1454     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1455     value->setAlignment(Alignment.getQuantity());
1456 
1457     llvm::Value *null =
1458       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1459 
1460     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1461     store->setAlignment(Alignment.getQuantity());
1462 
1463     store = CGF.Builder.CreateStore(null, srcField);
1464     store->setAlignment(Alignment.getQuantity());
1465   }
1466 
1467   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1468     llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1469     value->setAlignment(Alignment.getQuantity());
1470 
1471     CGF.EmitARCRelease(value, /*precise*/ false);
1472   }
1473 
1474   void profileImpl(llvm::FoldingSetNodeID &id) const {
1475     // 1 is distinguishable from all pointers and byref flags
1476     id.AddInteger(1);
1477   }
1478 };
1479 
1480 /// Emits the copy/dispose helpers for an ARC __block __strong
1481 /// variable that's of block-pointer type.
1482 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1483 public:
1484   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1485 
1486   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1487                 llvm::Value *srcField) {
1488     // Do the copy with objc_retainBlock; that's all that
1489     // _Block_object_assign would do anyway, and we'd have to pass the
1490     // right arguments to make sure it doesn't get no-op'ed.
1491     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1492     oldValue->setAlignment(Alignment.getQuantity());
1493 
1494     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1495 
1496     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1497     store->setAlignment(Alignment.getQuantity());
1498   }
1499 
1500   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1501     llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1502     value->setAlignment(Alignment.getQuantity());
1503 
1504     CGF.EmitARCRelease(value, /*precise*/ false);
1505   }
1506 
1507   void profileImpl(llvm::FoldingSetNodeID &id) const {
1508     // 2 is distinguishable from all pointers and byref flags
1509     id.AddInteger(2);
1510   }
1511 };
1512 
1513 /// Emits the copy/dispose helpers for a __block variable with a
1514 /// nontrivial copy constructor or destructor.
1515 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1516   QualType VarType;
1517   const Expr *CopyExpr;
1518 
1519 public:
1520   CXXByrefHelpers(CharUnits alignment, QualType type,
1521                   const Expr *copyExpr)
1522     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1523 
1524   bool needsCopy() const { return CopyExpr != 0; }
1525   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1526                 llvm::Value *srcField) {
1527     if (!CopyExpr) return;
1528     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1529   }
1530 
1531   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1532     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1533     CGF.PushDestructorCleanup(VarType, field);
1534     CGF.PopCleanupBlocks(cleanupDepth);
1535   }
1536 
1537   void profileImpl(llvm::FoldingSetNodeID &id) const {
1538     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1539   }
1540 };
1541 } // end anonymous namespace
1542 
1543 static llvm::Constant *
1544 generateByrefCopyHelper(CodeGenFunction &CGF,
1545                         llvm::StructType &byrefType,
1546                         CodeGenModule::ByrefHelpers &byrefInfo) {
1547   ASTContext &Context = CGF.getContext();
1548 
1549   QualType R = Context.VoidTy;
1550 
1551   FunctionArgList args;
1552   ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
1553   args.push_back(&dst);
1554 
1555   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1556   args.push_back(&src);
1557 
1558   const CGFunctionInfo &FI =
1559     CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
1560 
1561   CodeGenTypes &Types = CGF.CGM.getTypes();
1562   llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1563 
1564   // FIXME: We'd like to put these into a mergable by content, with
1565   // internal linkage.
1566   llvm::Function *Fn =
1567     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1568                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1569 
1570   IdentifierInfo *II
1571     = &Context.Idents.get("__Block_byref_object_copy_");
1572 
1573   FunctionDecl *FD = FunctionDecl::Create(Context,
1574                                           Context.getTranslationUnitDecl(),
1575                                           SourceLocation(),
1576                                           SourceLocation(), II, R, 0,
1577                                           SC_Static,
1578                                           SC_None,
1579                                           false, true);
1580 
1581   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1582 
1583   if (byrefInfo.needsCopy()) {
1584     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1585 
1586     // dst->x
1587     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1588     destField = CGF.Builder.CreateLoad(destField);
1589     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1590     destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
1591 
1592     // src->x
1593     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1594     srcField = CGF.Builder.CreateLoad(srcField);
1595     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1596     srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1597 
1598     byrefInfo.emitCopy(CGF, destField, srcField);
1599   }
1600 
1601   CGF.FinishFunction();
1602 
1603   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1604 }
1605 
1606 /// Build the copy helper for a __block variable.
1607 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1608                                             llvm::StructType &byrefType,
1609                                             CodeGenModule::ByrefHelpers &info) {
1610   CodeGenFunction CGF(CGM);
1611   return generateByrefCopyHelper(CGF, byrefType, info);
1612 }
1613 
1614 /// Generate code for a __block variable's dispose helper.
1615 static llvm::Constant *
1616 generateByrefDisposeHelper(CodeGenFunction &CGF,
1617                            llvm::StructType &byrefType,
1618                            CodeGenModule::ByrefHelpers &byrefInfo) {
1619   ASTContext &Context = CGF.getContext();
1620   QualType R = Context.VoidTy;
1621 
1622   FunctionArgList args;
1623   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1624   args.push_back(&src);
1625 
1626   const CGFunctionInfo &FI =
1627     CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
1628 
1629   CodeGenTypes &Types = CGF.CGM.getTypes();
1630   llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1631 
1632   // FIXME: We'd like to put these into a mergable by content, with
1633   // internal linkage.
1634   llvm::Function *Fn =
1635     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1636                            "__Block_byref_object_dispose_",
1637                            &CGF.CGM.getModule());
1638 
1639   IdentifierInfo *II
1640     = &Context.Idents.get("__Block_byref_object_dispose_");
1641 
1642   FunctionDecl *FD = FunctionDecl::Create(Context,
1643                                           Context.getTranslationUnitDecl(),
1644                                           SourceLocation(),
1645                                           SourceLocation(), II, R, 0,
1646                                           SC_Static,
1647                                           SC_None,
1648                                           false, true);
1649   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1650 
1651   if (byrefInfo.needsDispose()) {
1652     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1653     V = CGF.Builder.CreateLoad(V);
1654     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1655     V = CGF.Builder.CreateStructGEP(V, 6, "x");
1656 
1657     byrefInfo.emitDispose(CGF, V);
1658   }
1659 
1660   CGF.FinishFunction();
1661 
1662   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1663 }
1664 
1665 /// Build the dispose helper for a __block variable.
1666 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1667                                               llvm::StructType &byrefType,
1668                                             CodeGenModule::ByrefHelpers &info) {
1669   CodeGenFunction CGF(CGM);
1670   return generateByrefDisposeHelper(CGF, byrefType, info);
1671 }
1672 
1673 ///
1674 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1675                                                llvm::StructType &byrefTy,
1676                                                T &byrefInfo) {
1677   // Increase the field's alignment to be at least pointer alignment,
1678   // since the layout of the byref struct will guarantee at least that.
1679   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1680                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1681 
1682   llvm::FoldingSetNodeID id;
1683   byrefInfo.Profile(id);
1684 
1685   void *insertPos;
1686   CodeGenModule::ByrefHelpers *node
1687     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1688   if (node) return static_cast<T*>(node);
1689 
1690   byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1691   byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1692 
1693   T *copy = new (CGM.getContext()) T(byrefInfo);
1694   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1695   return copy;
1696 }
1697 
1698 CodeGenModule::ByrefHelpers *
1699 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1700                                    const AutoVarEmission &emission) {
1701   const VarDecl &var = *emission.Variable;
1702   QualType type = var.getType();
1703 
1704   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1705     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1706     if (!copyExpr && record->hasTrivialDestructor()) return 0;
1707 
1708     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1709     return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1710   }
1711 
1712   // Otherwise, if we don't have a retainable type, there's nothing to do.
1713   // that the runtime does extra copies.
1714   if (!type->isObjCRetainableType()) return 0;
1715 
1716   Qualifiers qs = type.getQualifiers();
1717 
1718   // If we have lifetime, that dominates.
1719   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1720     assert(getLangOptions().ObjCAutoRefCount);
1721 
1722     switch (lifetime) {
1723     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1724 
1725     // These are just bits as far as the runtime is concerned.
1726     case Qualifiers::OCL_ExplicitNone:
1727     case Qualifiers::OCL_Autoreleasing:
1728       return 0;
1729 
1730     // Tell the runtime that this is ARC __weak, called by the
1731     // byref routines.
1732     case Qualifiers::OCL_Weak: {
1733       ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1734       return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1735     }
1736 
1737     // ARC __strong __block variables need to be retained.
1738     case Qualifiers::OCL_Strong:
1739       // Block pointers need to be copied, and there's no direct
1740       // transfer possible.
1741       if (type->isBlockPointerType()) {
1742         ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1743         return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1744 
1745       // Otherwise, we transfer ownership of the retain from the stack
1746       // to the heap.
1747       } else {
1748         ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1749         return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1750       }
1751     }
1752     llvm_unreachable("fell out of lifetime switch!");
1753   }
1754 
1755   BlockFieldFlags flags;
1756   if (type->isBlockPointerType()) {
1757     flags |= BLOCK_FIELD_IS_BLOCK;
1758   } else if (CGM.getContext().isObjCNSObjectType(type) ||
1759              type->isObjCObjectPointerType()) {
1760     flags |= BLOCK_FIELD_IS_OBJECT;
1761   } else {
1762     return 0;
1763   }
1764 
1765   if (type.isObjCGCWeak())
1766     flags |= BLOCK_FIELD_IS_WEAK;
1767 
1768   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1769   return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1770 }
1771 
1772 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1773   assert(ByRefValueInfo.count(VD) && "Did not find value!");
1774 
1775   return ByRefValueInfo.find(VD)->second.second;
1776 }
1777 
1778 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1779                                                      const VarDecl *V) {
1780   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1781   Loc = Builder.CreateLoad(Loc);
1782   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1783                                 V->getNameAsString());
1784   return Loc;
1785 }
1786 
1787 /// BuildByRefType - This routine changes a __block variable declared as T x
1788 ///   into:
1789 ///
1790 ///      struct {
1791 ///        void *__isa;
1792 ///        void *__forwarding;
1793 ///        int32_t __flags;
1794 ///        int32_t __size;
1795 ///        void *__copy_helper;       // only if needed
1796 ///        void *__destroy_helper;    // only if needed
1797 ///        char padding[X];           // only if needed
1798 ///        T x;
1799 ///      } x
1800 ///
1801 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1802   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1803   if (Info.first)
1804     return Info.first;
1805 
1806   QualType Ty = D->getType();
1807 
1808   SmallVector<llvm::Type *, 8> types;
1809 
1810   llvm::StructType *ByRefType =
1811     llvm::StructType::create(getLLVMContext(),
1812                              "struct.__block_byref_" + D->getNameAsString());
1813 
1814   // void *__isa;
1815   types.push_back(Int8PtrTy);
1816 
1817   // void *__forwarding;
1818   types.push_back(llvm::PointerType::getUnqual(ByRefType));
1819 
1820   // int32_t __flags;
1821   types.push_back(Int32Ty);
1822 
1823   // int32_t __size;
1824   types.push_back(Int32Ty);
1825 
1826   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1827   if (HasCopyAndDispose) {
1828     /// void *__copy_helper;
1829     types.push_back(Int8PtrTy);
1830 
1831     /// void *__destroy_helper;
1832     types.push_back(Int8PtrTy);
1833   }
1834 
1835   bool Packed = false;
1836   CharUnits Align = getContext().getDeclAlign(D);
1837   if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1838     // We have to insert padding.
1839 
1840     // The struct above has 2 32-bit integers.
1841     unsigned CurrentOffsetInBytes = 4 * 2;
1842 
1843     // And either 2 or 4 pointers.
1844     CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1845       CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1846 
1847     // Align the offset.
1848     unsigned AlignedOffsetInBytes =
1849       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1850 
1851     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1852     if (NumPaddingBytes > 0) {
1853       llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1854       // FIXME: We need a sema error for alignment larger than the minimum of
1855       // the maximal stack alignment and the alignment of malloc on the system.
1856       if (NumPaddingBytes > 1)
1857         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1858 
1859       types.push_back(Ty);
1860 
1861       // We want a packed struct.
1862       Packed = true;
1863     }
1864   }
1865 
1866   // T x;
1867   types.push_back(ConvertTypeForMem(Ty));
1868 
1869   ByRefType->setBody(types, Packed);
1870 
1871   Info.first = ByRefType;
1872 
1873   Info.second = types.size() - 1;
1874 
1875   return Info.first;
1876 }
1877 
1878 /// Initialize the structural components of a __block variable, i.e.
1879 /// everything but the actual object.
1880 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
1881   // Find the address of the local.
1882   llvm::Value *addr = emission.Address;
1883 
1884   // That's an alloca of the byref structure type.
1885   llvm::StructType *byrefType = cast<llvm::StructType>(
1886                  cast<llvm::PointerType>(addr->getType())->getElementType());
1887 
1888   // Build the byref helpers if necessary.  This is null if we don't need any.
1889   CodeGenModule::ByrefHelpers *helpers =
1890     buildByrefHelpers(*byrefType, emission);
1891 
1892   const VarDecl &D = *emission.Variable;
1893   QualType type = D.getType();
1894 
1895   llvm::Value *V;
1896 
1897   // Initialize the 'isa', which is just 0 or 1.
1898   int isa = 0;
1899   if (type.isObjCGCWeak())
1900     isa = 1;
1901   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1902   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1903 
1904   // Store the address of the variable into its own forwarding pointer.
1905   Builder.CreateStore(addr,
1906                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1907 
1908   // Blocks ABI:
1909   //   c) the flags field is set to either 0 if no helper functions are
1910   //      needed or BLOCK_HAS_COPY_DISPOSE if they are,
1911   BlockFlags flags;
1912   if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
1913   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1914                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
1915 
1916   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1917   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
1918   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1919 
1920   if (helpers) {
1921     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
1922     Builder.CreateStore(helpers->CopyHelper, copy_helper);
1923 
1924     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
1925     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
1926   }
1927 }
1928 
1929 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
1930   llvm::Value *F = CGM.getBlockObjectDispose();
1931   llvm::Value *N;
1932   V = Builder.CreateBitCast(V, Int8PtrTy);
1933   N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
1934   Builder.CreateCall2(F, V, N);
1935 }
1936 
1937 namespace {
1938   struct CallBlockRelease : EHScopeStack::Cleanup {
1939     llvm::Value *Addr;
1940     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1941 
1942     void Emit(CodeGenFunction &CGF, Flags flags) {
1943       // Should we be passing FIELD_IS_WEAK here?
1944       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1945     }
1946   };
1947 }
1948 
1949 /// Enter a cleanup to destroy a __block variable.  Note that this
1950 /// cleanup should be a no-op if the variable hasn't left the stack
1951 /// yet; if a cleanup is required for the variable itself, that needs
1952 /// to be done externally.
1953 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1954   // We don't enter this cleanup if we're in pure-GC mode.
1955   if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
1956     return;
1957 
1958   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1959 }
1960 
1961 /// Adjust the declaration of something from the blocks API.
1962 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1963                                          llvm::Constant *C) {
1964   if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1965 
1966   llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1967   if (GV->isDeclaration() &&
1968       GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1969     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1970 }
1971 
1972 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1973   if (BlockObjectDispose)
1974     return BlockObjectDispose;
1975 
1976   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1977   llvm::FunctionType *fty
1978     = llvm::FunctionType::get(VoidTy, args, false);
1979   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1980   configureBlocksRuntimeObject(*this, BlockObjectDispose);
1981   return BlockObjectDispose;
1982 }
1983 
1984 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1985   if (BlockObjectAssign)
1986     return BlockObjectAssign;
1987 
1988   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1989   llvm::FunctionType *fty
1990     = llvm::FunctionType::get(VoidTy, args, false);
1991   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1992   configureBlocksRuntimeObject(*this, BlockObjectAssign);
1993   return BlockObjectAssign;
1994 }
1995 
1996 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1997   if (NSConcreteGlobalBlock)
1998     return NSConcreteGlobalBlock;
1999 
2000   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2001                                                 Int8PtrTy->getPointerTo(), 0);
2002   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2003   return NSConcreteGlobalBlock;
2004 }
2005 
2006 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2007   if (NSConcreteStackBlock)
2008     return NSConcreteStackBlock;
2009 
2010   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2011                                                Int8PtrTy->getPointerTo(), 0);
2012   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2013   return NSConcreteStackBlock;
2014 }
2015