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 BlockExpr *blockExpr, const char *N)
29   : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
30     HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
31 
32   // Skip asm prefix, if any.
33   if (Name && Name[0] == '\01')
34     ++Name;
35 }
36 
37 // Anchor the vtable to this translation unit.
38 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
39 
40 /// Build the given block as a global block.
41 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
42                                         const CGBlockInfo &blockInfo,
43                                         llvm::Constant *blockFn);
44 
45 /// Build the helper function to copy a block.
46 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
47                                        const CGBlockInfo &blockInfo) {
48   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
49 }
50 
51 /// Build the helper function to dipose of a block.
52 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
53                                           const CGBlockInfo &blockInfo) {
54   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
55 }
56 
57 /// Build the block descriptor constant for a block.
58 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
59                                             const CGBlockInfo &blockInfo) {
60   ASTContext &C = CGM.getContext();
61 
62   const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63   const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
64 
65   llvm::SmallVector<llvm::Constant*, 6> elements;
66 
67   // reserved
68   elements.push_back(llvm::ConstantInt::get(ulong, 0));
69 
70   // Size
71   // FIXME: What is the right way to say this doesn't fit?  We should give
72   // a user diagnostic in that case.  Better fix would be to change the
73   // API to size_t.
74   elements.push_back(llvm::ConstantInt::get(ulong,
75                                             blockInfo.BlockSize.getQuantity()));
76 
77   // Optional copy/dispose helpers.
78   if (blockInfo.NeedsCopyDispose) {
79     // copy_func_helper_decl
80     elements.push_back(buildCopyHelper(CGM, blockInfo));
81 
82     // destroy_func_decl
83     elements.push_back(buildDisposeHelper(CGM, blockInfo));
84   }
85 
86   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
87   std::string typeAtEncoding =
88     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
89   elements.push_back(llvm::ConstantExpr::getBitCast(
90                           CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
91 
92   // GC layout.
93   if (C.getLangOptions().ObjC1)
94     elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
95   else
96     elements.push_back(llvm::Constant::getNullValue(i8p));
97 
98   llvm::Constant *init =
99     llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
100                               elements.size(), false);
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     const llvm::Type *Type;
170 
171     BlockLayoutChunk(CharUnits align, CharUnits size,
172                      const BlockDecl::Capture *capture,
173                      const 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 record type has a mutable field.
193 static bool hasMutableField(const CXXRecordDecl *record) {
194   for (CXXRecordDecl::field_iterator
195          i = record->field_begin(), e = record->field_end(); i != e; ++i)
196     if ((*i)->isMutable())
197       return true;
198 
199   for (CXXRecordDecl::base_class_const_iterator
200          i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
201     const RecordType *record = i->getType()->castAs<RecordType>();
202     if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
203       return true;
204   }
205 
206   return false;
207 }
208 
209 /// Determines if the given type is safe for constant capture in C++.
210 static bool isSafeForCXXConstantCapture(QualType type) {
211   const RecordType *recordType =
212     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
213 
214   // Only records can be unsafe.
215   if (!recordType) return true;
216 
217   const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
218 
219   // Maintain semantics for classes with non-trivial dtors or copy ctors.
220   if (!record->hasTrivialDestructor()) return false;
221   if (!record->hasTrivialCopyConstructor()) return false;
222 
223   // Otherwise, we just have to make sure there aren't any mutable
224   // fields that might have changed since initialization.
225   return !hasMutableField(record);
226 }
227 
228 /// It is illegal to modify a const object after initialization.
229 /// Therefore, if a const object has a constant initializer, we don't
230 /// actually need to keep storage for it in the block; we'll just
231 /// rematerialize it at the start of the block function.  This is
232 /// acceptable because we make no promises about address stability of
233 /// captured variables.
234 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
235                                             const VarDecl *var) {
236   QualType type = var->getType();
237 
238   // We can only do this if the variable is const.
239   if (!type.isConstQualified()) return 0;
240 
241   // Furthermore, in C++ we have to worry about mutable fields:
242   // C++ [dcl.type.cv]p4:
243   //   Except that any class member declared mutable can be
244   //   modified, any attempt to modify a const object during its
245   //   lifetime results in undefined behavior.
246   if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
247     return 0;
248 
249   // If the variable doesn't have any initializer (shouldn't this be
250   // invalid?), it's not clear what we should do.  Maybe capture as
251   // zero?
252   const Expr *init = var->getInit();
253   if (!init) return 0;
254 
255   return CGM.EmitConstantExpr(init, var->getType());
256 }
257 
258 /// Get the low bit of a nonzero character count.  This is the
259 /// alignment of the nth byte if the 0th byte is universally aligned.
260 static CharUnits getLowBit(CharUnits v) {
261   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
262 }
263 
264 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
265                                 std::vector<const llvm::Type*> &elementTypes) {
266   ASTContext &C = CGM.getContext();
267 
268   // The header is basically a 'struct { void *; int; int; void *; void *; }'.
269   CharUnits ptrSize, ptrAlign, intSize, intAlign;
270   llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
271   llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
272 
273   // Are there crazy embedded platforms where this isn't true?
274   assert(intSize <= ptrSize && "layout assumptions horribly violated");
275 
276   CharUnits headerSize = ptrSize;
277   if (2 * intSize < ptrAlign) headerSize += ptrSize;
278   else headerSize += 2 * intSize;
279   headerSize += 2 * ptrSize;
280 
281   info.BlockAlign = ptrAlign;
282   info.BlockSize = headerSize;
283 
284   assert(elementTypes.empty());
285   const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
286   const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
287   elementTypes.push_back(i8p);
288   elementTypes.push_back(intTy);
289   elementTypes.push_back(intTy);
290   elementTypes.push_back(i8p);
291   elementTypes.push_back(CGM.getBlockDescriptorType());
292 
293   assert(elementTypes.size() == BlockHeaderSize);
294 }
295 
296 /// Compute the layout of the given block.  Attempts to lay the block
297 /// out with minimal space requirements.
298 static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
299   ASTContext &C = CGM.getContext();
300   const BlockDecl *block = info.getBlockDecl();
301 
302   std::vector<const llvm::Type*> elementTypes;
303   initializeForBlockHeader(CGM, info, elementTypes);
304 
305   if (!block->hasCaptures()) {
306     info.StructureType =
307       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
308     info.CanBeGlobal = true;
309     return;
310   }
311 
312   // Collect the layout chunks.
313   llvm::SmallVector<BlockLayoutChunk, 16> layout;
314   layout.reserve(block->capturesCXXThis() +
315                  (block->capture_end() - block->capture_begin()));
316 
317   CharUnits maxFieldAlign;
318 
319   // First, 'this'.
320   if (block->capturesCXXThis()) {
321     const DeclContext *DC = block->getDeclContext();
322     for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
323       ;
324     QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
325 
326     const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
327     std::pair<CharUnits,CharUnits> tinfo
328       = CGM.getContext().getTypeInfoInChars(thisType);
329     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
330 
331     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
332   }
333 
334   // Next, all the block captures.
335   for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
336          ce = block->capture_end(); ci != ce; ++ci) {
337     const VarDecl *variable = ci->getVariable();
338 
339     if (ci->isByRef()) {
340       // We have to copy/dispose of the __block reference.
341       info.NeedsCopyDispose = true;
342 
343       // Just use void* instead of a pointer to the byref type.
344       QualType byRefPtrTy = C.VoidPtrTy;
345 
346       const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
347       std::pair<CharUnits,CharUnits> tinfo
348         = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
349       maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
350 
351       layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
352                                         &*ci, llvmType));
353       continue;
354     }
355 
356     // Otherwise, build a layout chunk with the size and alignment of
357     // the declaration.
358     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
359       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
360       continue;
361     }
362 
363     // Block pointers require copy/dispose.
364     if (variable->getType()->isBlockPointerType()) {
365       info.NeedsCopyDispose = true;
366 
367     // So do Objective-C pointers.
368     } else if (variable->getType()->isObjCObjectPointerType() ||
369                C.isObjCNSObjectType(variable->getType())) {
370       info.NeedsCopyDispose = true;
371 
372     // So do types that require non-trivial copy construction.
373     } else if (ci->hasCopyExpr()) {
374       info.NeedsCopyDispose = true;
375       info.HasCXXObject = true;
376 
377     // And so do types with destructors.
378     } else if (CGM.getLangOptions().CPlusPlus) {
379       if (const CXXRecordDecl *record =
380             variable->getType()->getAsCXXRecordDecl()) {
381         if (!record->hasTrivialDestructor()) {
382           info.HasCXXObject = true;
383           info.NeedsCopyDispose = true;
384         }
385       }
386     }
387 
388     CharUnits size = C.getTypeSizeInChars(variable->getType());
389     CharUnits align = C.getDeclAlign(variable);
390     maxFieldAlign = std::max(maxFieldAlign, align);
391 
392     const llvm::Type *llvmType =
393       CGM.getTypes().ConvertTypeForMem(variable->getType());
394 
395     layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
396   }
397 
398   // If that was everything, we're done here.
399   if (layout.empty()) {
400     info.StructureType =
401       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
402     info.CanBeGlobal = true;
403     return;
404   }
405 
406   // Sort the layout by alignment.  We have to use a stable sort here
407   // to get reproducible results.  There should probably be an
408   // llvm::array_pod_stable_sort.
409   std::stable_sort(layout.begin(), layout.end());
410 
411   CharUnits &blockSize = info.BlockSize;
412   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
413 
414   // Assuming that the first byte in the header is maximally aligned,
415   // get the alignment of the first byte following the header.
416   CharUnits endAlign = getLowBit(blockSize);
417 
418   // If the end of the header isn't satisfactorily aligned for the
419   // maximum thing, look for things that are okay with the header-end
420   // alignment, and keep appending them until we get something that's
421   // aligned right.  This algorithm is only guaranteed optimal if
422   // that condition is satisfied at some point; otherwise we can get
423   // things like:
424   //   header                 // next byte has alignment 4
425   //   something_with_size_5; // next byte has alignment 1
426   //   something_with_alignment_8;
427   // which has 7 bytes of padding, as opposed to the naive solution
428   // which might have less (?).
429   if (endAlign < maxFieldAlign) {
430     llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
431       li = layout.begin() + 1, le = layout.end();
432 
433     // Look for something that the header end is already
434     // satisfactorily aligned for.
435     for (; li != le && endAlign < li->Alignment; ++li)
436       ;
437 
438     // If we found something that's naturally aligned for the end of
439     // the header, keep adding things...
440     if (li != le) {
441       llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
442       for (; li != le; ++li) {
443         assert(endAlign >= li->Alignment);
444 
445         li->setIndex(info, elementTypes.size());
446         elementTypes.push_back(li->Type);
447         blockSize += li->Size;
448         endAlign = getLowBit(blockSize);
449 
450         // ...until we get to the alignment of the maximum field.
451         if (endAlign >= maxFieldAlign)
452           break;
453       }
454 
455       // Don't re-append everything we just appended.
456       layout.erase(first, li);
457     }
458   }
459 
460   // At this point, we just have to add padding if the end align still
461   // isn't aligned right.
462   if (endAlign < maxFieldAlign) {
463     CharUnits padding = maxFieldAlign - endAlign;
464 
465     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
466                                                 padding.getQuantity()));
467     blockSize += padding;
468 
469     endAlign = getLowBit(blockSize);
470     assert(endAlign >= maxFieldAlign);
471   }
472 
473   // Slam everything else on now.  This works because they have
474   // strictly decreasing alignment and we expect that size is always a
475   // multiple of alignment.
476   for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
477          li = layout.begin(), le = layout.end(); li != le; ++li) {
478     assert(endAlign >= li->Alignment);
479     li->setIndex(info, elementTypes.size());
480     elementTypes.push_back(li->Type);
481     blockSize += li->Size;
482     endAlign = getLowBit(blockSize);
483   }
484 
485   info.StructureType =
486     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
487 }
488 
489 /// Emit a block literal expression in the current function.
490 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
491   std::string Name = CurFn->getName();
492   CGBlockInfo blockInfo(blockExpr, Name.c_str());
493 
494   // Compute information about the layout, etc., of this block.
495   computeBlockInfo(CGM, blockInfo);
496 
497   // Using that metadata, generate the actual block function.
498   llvm::Constant *blockFn
499     = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
500                                                  CurFuncDecl, LocalDeclMap);
501   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
502 
503   // If there is nothing to capture, we can emit this as a global block.
504   if (blockInfo.CanBeGlobal)
505     return buildGlobalBlock(CGM, blockInfo, blockFn);
506 
507   // Otherwise, we have to emit this as a local block.
508 
509   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
510   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
511 
512   // Build the block descriptor.
513   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
514 
515   const llvm::Type *intTy = ConvertType(getContext().IntTy);
516 
517   llvm::AllocaInst *blockAddr =
518     CreateTempAlloca(blockInfo.StructureType, "block");
519   blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
520 
521   // Compute the initial on-stack block flags.
522   BlockFlags flags = BLOCK_HAS_SIGNATURE;
523   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
524   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
525   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
526 
527   // Initialize the block literal.
528   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
529   Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
530                       Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
531   Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
532                       Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
533   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
534                                                        "block.invoke"));
535   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
536                                                           "block.descriptor"));
537 
538   // Finally, capture all the values into the block.
539   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
540 
541   // First, 'this'.
542   if (blockDecl->capturesCXXThis()) {
543     llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
544                                                 blockInfo.CXXThisIndex,
545                                                 "block.captured-this.addr");
546     Builder.CreateStore(LoadCXXThis(), addr);
547   }
548 
549   // Next, captured variables.
550   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
551          ce = blockDecl->capture_end(); ci != ce; ++ci) {
552     const VarDecl *variable = ci->getVariable();
553     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
554 
555     // Ignore constant captures.
556     if (capture.isConstant()) continue;
557 
558     QualType type = variable->getType();
559 
560     // This will be a [[type]]*, except that a byref entry will just be
561     // an i8**.
562     llvm::Value *blockField =
563       Builder.CreateStructGEP(blockAddr, capture.getIndex(),
564                               "block.captured");
565 
566     // Compute the address of the thing we're going to move into the
567     // block literal.
568     llvm::Value *src;
569     if (ci->isNested()) {
570       // We need to use the capture from the enclosing block.
571       const CGBlockInfo::Capture &enclosingCapture =
572         BlockInfo->getCapture(variable);
573 
574       // This is a [[type]]*, except that a byref entry wil just be an i8**.
575       src = Builder.CreateStructGEP(LoadBlockStruct(),
576                                     enclosingCapture.getIndex(),
577                                     "block.capture.addr");
578     } else {
579       // This is a [[type]]*.
580       src = LocalDeclMap[variable];
581     }
582 
583     // For byrefs, we just write the pointer to the byref struct into
584     // the block field.  There's no need to chase the forwarding
585     // pointer at this point, since we're building something that will
586     // live a shorter life than the stack byref anyway.
587     if (ci->isByRef()) {
588       // Get a void* that points to the byref struct.
589       if (ci->isNested())
590         src = Builder.CreateLoad(src, "byref.capture");
591       else
592         src = Builder.CreateBitCast(src, VoidPtrTy);
593 
594       // Write that void* into the capture field.
595       Builder.CreateStore(src, blockField);
596 
597     // If we have a copy constructor, evaluate that into the block field.
598     } else if (const Expr *copyExpr = ci->getCopyExpr()) {
599       EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
600 
601     // If it's a reference variable, copy the reference into the block field.
602     } else if (type->isReferenceType()) {
603       Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
604 
605     // Otherwise, fake up a POD copy into the block field.
606     } else {
607       // We use one of these or the other depending on whether the
608       // reference is nested.
609       DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
610                             SourceLocation());
611       BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
612                               VK_LValue, SourceLocation(), /*byref*/ false);
613 
614       Expr *declRef =
615         (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
616 
617       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
618                            declRef, VK_RValue);
619       EmitExprAsInit(&l2r, variable, blockField,
620                      getContext().getDeclAlign(variable),
621                      /*captured by init*/ false);
622     }
623 
624     // Push a destructor if necessary.  The semantics for when this
625     // actually gets run are really obscure.
626     if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
627       PushDestructorCleanup(type, blockField);
628   }
629 
630   // Cast to the converted block-pointer type, which happens (somewhat
631   // unfortunately) to be a pointer to function type.
632   llvm::Value *result =
633     Builder.CreateBitCast(blockAddr,
634                           ConvertType(blockInfo.getBlockExpr()->getType()));
635 
636   return result;
637 }
638 
639 
640 const llvm::Type *CodeGenModule::getBlockDescriptorType() {
641   if (BlockDescriptorType)
642     return BlockDescriptorType;
643 
644   const llvm::Type *UnsignedLongTy =
645     getTypes().ConvertType(getContext().UnsignedLongTy);
646 
647   // struct __block_descriptor {
648   //   unsigned long reserved;
649   //   unsigned long block_size;
650   //
651   //   // later, the following will be added
652   //
653   //   struct {
654   //     void (*copyHelper)();
655   //     void (*copyHelper)();
656   //   } helpers;                // !!! optional
657   //
658   //   const char *signature;   // the block signature
659   //   const char *layout;      // reserved
660   // };
661   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
662                                               UnsignedLongTy,
663                                               UnsignedLongTy,
664                                               NULL);
665 
666   getModule().addTypeName("struct.__block_descriptor",
667                           BlockDescriptorType);
668 
669   // Now form a pointer to that.
670   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
671   return BlockDescriptorType;
672 }
673 
674 const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
675   if (GenericBlockLiteralType)
676     return GenericBlockLiteralType;
677 
678   const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
679 
680   // struct __block_literal_generic {
681   //   void *__isa;
682   //   int __flags;
683   //   int __reserved;
684   //   void (*__invoke)(void *);
685   //   struct __block_descriptor *__descriptor;
686   // };
687   GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
688                                                   VoidPtrTy,
689                                                   IntTy,
690                                                   IntTy,
691                                                   VoidPtrTy,
692                                                   BlockDescPtrTy,
693                                                   NULL);
694 
695   getModule().addTypeName("struct.__block_literal_generic",
696                           GenericBlockLiteralType);
697 
698   return GenericBlockLiteralType;
699 }
700 
701 
702 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
703                                           ReturnValueSlot ReturnValue) {
704   const BlockPointerType *BPT =
705     E->getCallee()->getType()->getAs<BlockPointerType>();
706 
707   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
708 
709   // Get a pointer to the generic block literal.
710   const llvm::Type *BlockLiteralTy =
711     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
712 
713   // Bitcast the callee to a block literal.
714   llvm::Value *BlockLiteral =
715     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
716 
717   // Get the function pointer from the literal.
718   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
719 
720   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
721 
722   // Add the block literal.
723   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
724   CallArgList Args;
725   Args.add(RValue::get(BlockLiteral), VoidPtrTy);
726 
727   QualType FnType = BPT->getPointeeType();
728 
729   // And the rest of the arguments.
730   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
731                E->arg_begin(), E->arg_end());
732 
733   // Load the function.
734   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
735 
736   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
737   QualType ResultType = FuncTy->getResultType();
738 
739   const CGFunctionInfo &FnInfo =
740     CGM.getTypes().getFunctionInfo(ResultType, Args,
741                                    FuncTy->getExtInfo());
742 
743   // Cast the function pointer to the right type.
744   const llvm::Type *BlockFTy =
745     CGM.getTypes().GetFunctionType(FnInfo, false);
746 
747   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
748   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
749 
750   // And call the block.
751   return EmitCall(FnInfo, Func, ReturnValue, Args);
752 }
753 
754 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
755                                                  bool isByRef) {
756   assert(BlockInfo && "evaluating block ref without block information?");
757   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
758 
759   // Handle constant captures.
760   if (capture.isConstant()) return LocalDeclMap[variable];
761 
762   llvm::Value *addr =
763     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
764                             "block.capture.addr");
765 
766   if (isByRef) {
767     // addr should be a void** right now.  Load, then cast the result
768     // to byref*.
769 
770     addr = Builder.CreateLoad(addr);
771     const llvm::PointerType *byrefPointerType
772       = llvm::PointerType::get(BuildByRefType(variable), 0);
773     addr = Builder.CreateBitCast(addr, byrefPointerType,
774                                  "byref.addr");
775 
776     // Follow the forwarding pointer.
777     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
778     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
779 
780     // Cast back to byref* and GEP over to the actual object.
781     addr = Builder.CreateBitCast(addr, byrefPointerType);
782     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
783                                    variable->getNameAsString());
784   }
785 
786   if (variable->getType()->isReferenceType())
787     addr = Builder.CreateLoad(addr, "ref.tmp");
788 
789   return addr;
790 }
791 
792 llvm::Constant *
793 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
794                                     const char *name) {
795   CGBlockInfo blockInfo(blockExpr, name);
796 
797   // Compute information about the layout, etc., of this block.
798   computeBlockInfo(*this, blockInfo);
799 
800   // Using that metadata, generate the actual block function.
801   llvm::Constant *blockFn;
802   {
803     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
804     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
805                                                            blockInfo,
806                                                            0, LocalDeclMap);
807   }
808   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
809 
810   return buildGlobalBlock(*this, blockInfo, blockFn);
811 }
812 
813 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
814                                         const CGBlockInfo &blockInfo,
815                                         llvm::Constant *blockFn) {
816   assert(blockInfo.CanBeGlobal);
817 
818   // Generate the constants for the block literal initializer.
819   llvm::Constant *fields[BlockHeaderSize];
820 
821   // isa
822   fields[0] = CGM.getNSConcreteGlobalBlock();
823 
824   // __flags
825   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
826   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
827 
828   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
829 
830   // Reserved
831   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
832 
833   // Function
834   fields[3] = blockFn;
835 
836   // Descriptor
837   fields[4] = buildBlockDescriptor(CGM, blockInfo);
838 
839   llvm::Constant *init =
840     llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
841                               /*packed*/ false);
842 
843   llvm::GlobalVariable *literal =
844     new llvm::GlobalVariable(CGM.getModule(),
845                              init->getType(),
846                              /*constant*/ true,
847                              llvm::GlobalVariable::InternalLinkage,
848                              init,
849                              "__block_literal_global");
850   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
851 
852   // Return a constant of the appropriately-casted type.
853   const llvm::Type *requiredType =
854     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
855   return llvm::ConstantExpr::getBitCast(literal, requiredType);
856 }
857 
858 llvm::Function *
859 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
860                                        const CGBlockInfo &blockInfo,
861                                        const Decl *outerFnDecl,
862                                        const DeclMapTy &ldm) {
863   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
864 
865   // Check if we should generate debug info for this block function.
866   if (CGM.getModuleDebugInfo())
867     DebugInfo = CGM.getModuleDebugInfo();
868 
869   BlockInfo = &blockInfo;
870 
871   // Arrange for local static and local extern declarations to appear
872   // to be local to this function as well, in case they're directly
873   // referenced in a block.
874   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
875     const VarDecl *var = dyn_cast<VarDecl>(i->first);
876     if (var && !var->hasLocalStorage())
877       LocalDeclMap[var] = i->second;
878   }
879 
880   // Begin building the function declaration.
881 
882   // Build the argument list.
883   FunctionArgList args;
884 
885   // The first argument is the block pointer.  Just take it as a void*
886   // and cast it later.
887   QualType selfTy = getContext().VoidPtrTy;
888   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
889 
890   ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
891                              SourceLocation(), II, selfTy);
892   args.push_back(&selfDecl);
893 
894   // Now add the rest of the parameters.
895   for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
896        e = blockDecl->param_end(); i != e; ++i)
897     args.push_back(*i);
898 
899   // Create the function declaration.
900   const FunctionProtoType *fnType =
901     cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
902   const CGFunctionInfo &fnInfo =
903     CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
904                                    fnType->getExtInfo());
905   if (CGM.ReturnTypeUsesSRet(fnInfo))
906     blockInfo.UsesStret = true;
907 
908   const llvm::FunctionType *fnLLVMType =
909     CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
910 
911   MangleBuffer name;
912   CGM.getBlockMangledName(GD, name, blockDecl);
913   llvm::Function *fn =
914     llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
915                            name.getString(), &CGM.getModule());
916   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
917 
918   // Begin generating the function.
919   StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
920                 blockInfo.getBlockExpr()->getBody()->getLocStart());
921   CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
922 
923   // Okay.  Undo some of what StartFunction did.
924 
925   // Pull the 'self' reference out of the local decl map.
926   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
927   LocalDeclMap.erase(&selfDecl);
928   BlockPointer = Builder.CreateBitCast(blockAddr,
929                                        blockInfo.StructureType->getPointerTo(),
930                                        "block");
931 
932   // If we have a C++ 'this' reference, go ahead and force it into
933   // existence now.
934   if (blockDecl->capturesCXXThis()) {
935     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
936                                                 blockInfo.CXXThisIndex,
937                                                 "block.captured-this");
938     CXXThisValue = Builder.CreateLoad(addr, "this");
939   }
940 
941   // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
942   // appease it.
943   if (const ObjCMethodDecl *method
944         = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
945     const VarDecl *self = method->getSelfDecl();
946 
947     // There might not be a capture for 'self', but if there is...
948     if (blockInfo.Captures.count(self)) {
949       const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
950       llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
951                                                       capture.getIndex(),
952                                                       "block.captured-self");
953       LocalDeclMap[self] = selfAddr;
954     }
955   }
956 
957   // Also force all the constant captures.
958   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
959          ce = blockDecl->capture_end(); ci != ce; ++ci) {
960     const VarDecl *variable = ci->getVariable();
961     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
962     if (!capture.isConstant()) continue;
963 
964     unsigned align = getContext().getDeclAlign(variable).getQuantity();
965 
966     llvm::AllocaInst *alloca =
967       CreateMemTemp(variable->getType(), "block.captured-const");
968     alloca->setAlignment(align);
969 
970     Builder.CreateStore(capture.getConstant(), alloca, align);
971 
972     LocalDeclMap[variable] = alloca;
973   }
974 
975   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
976   llvm::BasicBlock *entry = Builder.GetInsertBlock();
977   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
978   --entry_ptr;
979 
980   EmitStmt(blockDecl->getBody());
981 
982   // Remember where we were...
983   llvm::BasicBlock *resume = Builder.GetInsertBlock();
984 
985   // Go back to the entry.
986   ++entry_ptr;
987   Builder.SetInsertPoint(entry, entry_ptr);
988 
989   // Emit debug information for all the BlockDeclRefDecls.
990   // FIXME: also for 'this'
991   if (CGDebugInfo *DI = getDebugInfo()) {
992     for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
993            ce = blockDecl->capture_end(); ci != ce; ++ci) {
994       const VarDecl *variable = ci->getVariable();
995       DI->setLocation(variable->getLocation());
996 
997       const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
998       if (capture.isConstant()) {
999         DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1000                                       Builder);
1001         continue;
1002       }
1003 
1004       DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1005                                             Builder, blockInfo);
1006     }
1007   }
1008 
1009   // And resume where we left off.
1010   if (resume == 0)
1011     Builder.ClearInsertionPoint();
1012   else
1013     Builder.SetInsertPoint(resume);
1014 
1015   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1016 
1017   return fn;
1018 }
1019 
1020 /*
1021     notes.push_back(HelperInfo());
1022     HelperInfo &note = notes.back();
1023     note.index = capture.getIndex();
1024     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1025     note.cxxbar_import = ci->getCopyExpr();
1026 
1027     if (ci->isByRef()) {
1028       note.flag = BLOCK_FIELD_IS_BYREF;
1029       if (type.isObjCGCWeak())
1030         note.flag |= BLOCK_FIELD_IS_WEAK;
1031     } else if (type->isBlockPointerType()) {
1032       note.flag = BLOCK_FIELD_IS_BLOCK;
1033     } else {
1034       note.flag = BLOCK_FIELD_IS_OBJECT;
1035     }
1036  */
1037 
1038 
1039 
1040 
1041 
1042 llvm::Constant *
1043 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1044   ASTContext &C = getContext();
1045 
1046   FunctionArgList args;
1047   ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1048   args.push_back(&dstDecl);
1049   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1050   args.push_back(&srcDecl);
1051 
1052   const CGFunctionInfo &FI =
1053       CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
1054 
1055   // FIXME: it would be nice if these were mergeable with things with
1056   // identical semantics.
1057   const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
1058 
1059   llvm::Function *Fn =
1060     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1061                            "__copy_helper_block_", &CGM.getModule());
1062 
1063   IdentifierInfo *II
1064     = &CGM.getContext().Idents.get("__copy_helper_block_");
1065 
1066   // Check if we should generate debug info for this block helper function.
1067   if (CGM.getModuleDebugInfo())
1068     DebugInfo = CGM.getModuleDebugInfo();
1069 
1070   FunctionDecl *FD = FunctionDecl::Create(C,
1071                                           C.getTranslationUnitDecl(),
1072                                           SourceLocation(),
1073                                           SourceLocation(), II, C.VoidTy, 0,
1074                                           SC_Static,
1075                                           SC_None,
1076                                           false,
1077                                           true);
1078   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1079 
1080   const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1081 
1082   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1083   src = Builder.CreateLoad(src);
1084   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1085 
1086   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1087   dst = Builder.CreateLoad(dst);
1088   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1089 
1090   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1091 
1092   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1093          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1094     const VarDecl *variable = ci->getVariable();
1095     QualType type = variable->getType();
1096 
1097     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1098     if (capture.isConstant()) continue;
1099 
1100     const Expr *copyExpr = ci->getCopyExpr();
1101     unsigned flags = 0;
1102 
1103     if (copyExpr) {
1104       assert(!ci->isByRef());
1105       // don't bother computing flags
1106     } else if (ci->isByRef()) {
1107       flags = BLOCK_FIELD_IS_BYREF;
1108       if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1109     } else if (type->isBlockPointerType()) {
1110       flags = BLOCK_FIELD_IS_BLOCK;
1111     } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1112       flags = BLOCK_FIELD_IS_OBJECT;
1113     }
1114 
1115     if (!copyExpr && !flags) continue;
1116 
1117     unsigned index = capture.getIndex();
1118     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1119     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1120 
1121     // If there's an explicit copy expression, we do that.
1122     if (copyExpr) {
1123       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1124     } else {
1125       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1126       srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1127       llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1128       Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1129                           llvm::ConstantInt::get(Int32Ty, flags));
1130     }
1131   }
1132 
1133   FinishFunction();
1134 
1135   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1136 }
1137 
1138 llvm::Constant *
1139 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1140   ASTContext &C = getContext();
1141 
1142   FunctionArgList args;
1143   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1144   args.push_back(&srcDecl);
1145 
1146   const CGFunctionInfo &FI =
1147       CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
1148 
1149   // FIXME: We'd like to put these into a mergable by content, with
1150   // internal linkage.
1151   const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
1152 
1153   llvm::Function *Fn =
1154     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1155                            "__destroy_helper_block_", &CGM.getModule());
1156 
1157   // Check if we should generate debug info for this block destroy function.
1158   if (CGM.getModuleDebugInfo())
1159     DebugInfo = CGM.getModuleDebugInfo();
1160 
1161   IdentifierInfo *II
1162     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1163 
1164   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1165                                           SourceLocation(),
1166                                           SourceLocation(), II, C.VoidTy, 0,
1167                                           SC_Static,
1168                                           SC_None,
1169                                           false, true);
1170   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1171 
1172   const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1173 
1174   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1175   src = Builder.CreateLoad(src);
1176   src = Builder.CreateBitCast(src, structPtrTy, "block");
1177 
1178   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1179 
1180   CodeGenFunction::RunCleanupsScope cleanups(*this);
1181 
1182   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1183          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1184     const VarDecl *variable = ci->getVariable();
1185     QualType type = variable->getType();
1186 
1187     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1188     if (capture.isConstant()) continue;
1189 
1190     BlockFieldFlags flags;
1191     const CXXDestructorDecl *dtor = 0;
1192 
1193     if (ci->isByRef()) {
1194       flags = BLOCK_FIELD_IS_BYREF;
1195       if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1196     } else if (type->isBlockPointerType()) {
1197       flags = BLOCK_FIELD_IS_BLOCK;
1198     } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1199       flags = BLOCK_FIELD_IS_OBJECT;
1200     } else if (C.getLangOptions().CPlusPlus) {
1201       if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1202         if (!record->hasTrivialDestructor())
1203           dtor = record->getDestructor();
1204     }
1205 
1206     if (!dtor && flags.empty()) continue;
1207 
1208     unsigned index = capture.getIndex();
1209     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1210 
1211     // If there's an explicit copy expression, we do that.
1212     if (dtor) {
1213       PushDestructorCleanup(dtor, srcField);
1214 
1215     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1216     // hard to just emit this as a cleanup if we wanted to make sure
1217     // that things were done in reverse.
1218     } else {
1219       llvm::Value *value = Builder.CreateLoad(srcField);
1220       value = Builder.CreateBitCast(value, VoidPtrTy);
1221       BuildBlockRelease(value, flags);
1222     }
1223   }
1224 
1225   cleanups.ForceCleanup();
1226 
1227   FinishFunction();
1228 
1229   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1230 }
1231 
1232 namespace {
1233 
1234 /// Emits the copy/dispose helper functions for a __block object of id type.
1235 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1236   BlockFieldFlags Flags;
1237 
1238 public:
1239   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1240     : ByrefHelpers(alignment), Flags(flags) {}
1241 
1242   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1243                 llvm::Value *srcField) {
1244     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1245 
1246     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1247     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1248 
1249     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1250 
1251     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1252     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1253     CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1254   }
1255 
1256   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1257     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1258     llvm::Value *value = CGF.Builder.CreateLoad(field);
1259 
1260     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1261   }
1262 
1263   void profileImpl(llvm::FoldingSetNodeID &id) const {
1264     id.AddInteger(Flags.getBitMask());
1265   }
1266 };
1267 
1268 /// Emits the copy/dispose helpers for a __block variable with a
1269 /// nontrivial copy constructor or destructor.
1270 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1271   QualType VarType;
1272   const Expr *CopyExpr;
1273 
1274 public:
1275   CXXByrefHelpers(CharUnits alignment, QualType type,
1276                   const Expr *copyExpr)
1277     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1278 
1279   bool needsCopy() const { return CopyExpr != 0; }
1280   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1281                 llvm::Value *srcField) {
1282     if (!CopyExpr) return;
1283     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1284   }
1285 
1286   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1287     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1288     CGF.PushDestructorCleanup(VarType, field);
1289     CGF.PopCleanupBlocks(cleanupDepth);
1290   }
1291 
1292   void profileImpl(llvm::FoldingSetNodeID &id) const {
1293     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1294   }
1295 };
1296 } // end anonymous namespace
1297 
1298 static llvm::Constant *
1299 generateByrefCopyHelper(CodeGenFunction &CGF,
1300                         const llvm::StructType &byrefType,
1301                         CodeGenModule::ByrefHelpers &byrefInfo) {
1302   ASTContext &Context = CGF.getContext();
1303 
1304   QualType R = Context.VoidTy;
1305 
1306   FunctionArgList args;
1307   ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
1308   args.push_back(&dst);
1309 
1310   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1311   args.push_back(&src);
1312 
1313   const CGFunctionInfo &FI =
1314     CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
1315 
1316   CodeGenTypes &Types = CGF.CGM.getTypes();
1317   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1318 
1319   // FIXME: We'd like to put these into a mergable by content, with
1320   // internal linkage.
1321   llvm::Function *Fn =
1322     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1323                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1324 
1325   IdentifierInfo *II
1326     = &Context.Idents.get("__Block_byref_object_copy_");
1327 
1328   FunctionDecl *FD = FunctionDecl::Create(Context,
1329                                           Context.getTranslationUnitDecl(),
1330                                           SourceLocation(),
1331                                           SourceLocation(), II, R, 0,
1332                                           SC_Static,
1333                                           SC_None,
1334                                           false, true);
1335   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1336 
1337   if (byrefInfo.needsCopy()) {
1338     const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1339 
1340     // dst->x
1341     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1342     destField = CGF.Builder.CreateLoad(destField);
1343     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1344     destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
1345 
1346     // src->x
1347     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1348     srcField = CGF.Builder.CreateLoad(srcField);
1349     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1350     srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1351 
1352     byrefInfo.emitCopy(CGF, destField, srcField);
1353   }
1354 
1355   CGF.FinishFunction();
1356 
1357   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1358 }
1359 
1360 /// Build the copy helper for a __block variable.
1361 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1362                                             const llvm::StructType &byrefType,
1363                                             CodeGenModule::ByrefHelpers &info) {
1364   CodeGenFunction CGF(CGM);
1365   return generateByrefCopyHelper(CGF, byrefType, info);
1366 }
1367 
1368 /// Generate code for a __block variable's dispose helper.
1369 static llvm::Constant *
1370 generateByrefDisposeHelper(CodeGenFunction &CGF,
1371                            const llvm::StructType &byrefType,
1372                            CodeGenModule::ByrefHelpers &byrefInfo) {
1373   ASTContext &Context = CGF.getContext();
1374   QualType R = Context.VoidTy;
1375 
1376   FunctionArgList args;
1377   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1378   args.push_back(&src);
1379 
1380   const CGFunctionInfo &FI =
1381     CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
1382 
1383   CodeGenTypes &Types = CGF.CGM.getTypes();
1384   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1385 
1386   // FIXME: We'd like to put these into a mergable by content, with
1387   // internal linkage.
1388   llvm::Function *Fn =
1389     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1390                            "__Block_byref_object_dispose_",
1391                            &CGF.CGM.getModule());
1392 
1393   IdentifierInfo *II
1394     = &Context.Idents.get("__Block_byref_object_dispose_");
1395 
1396   FunctionDecl *FD = FunctionDecl::Create(Context,
1397                                           Context.getTranslationUnitDecl(),
1398                                           SourceLocation(),
1399                                           SourceLocation(), II, R, 0,
1400                                           SC_Static,
1401                                           SC_None,
1402                                           false, true);
1403   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1404 
1405   if (byrefInfo.needsDispose()) {
1406     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1407     V = CGF.Builder.CreateLoad(V);
1408     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1409     V = CGF.Builder.CreateStructGEP(V, 6, "x");
1410 
1411     byrefInfo.emitDispose(CGF, V);
1412   }
1413 
1414   CGF.FinishFunction();
1415 
1416   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1417 }
1418 
1419 /// Build the dispose helper for a __block variable.
1420 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1421                                               const llvm::StructType &byrefType,
1422                                             CodeGenModule::ByrefHelpers &info) {
1423   CodeGenFunction CGF(CGM);
1424   return generateByrefDisposeHelper(CGF, byrefType, info);
1425 }
1426 
1427 ///
1428 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1429                                                const llvm::StructType &byrefTy,
1430                                                T &byrefInfo) {
1431   // Increase the field's alignment to be at least pointer alignment,
1432   // since the layout of the byref struct will guarantee at least that.
1433   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1434                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1435 
1436   llvm::FoldingSetNodeID id;
1437   byrefInfo.Profile(id);
1438 
1439   void *insertPos;
1440   CodeGenModule::ByrefHelpers *node
1441     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1442   if (node) return static_cast<T*>(node);
1443 
1444   byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1445   byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1446 
1447   T *copy = new (CGM.getContext()) T(byrefInfo);
1448   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1449   return copy;
1450 }
1451 
1452 CodeGenModule::ByrefHelpers *
1453 CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1454                                    const AutoVarEmission &emission) {
1455   const VarDecl &var = *emission.Variable;
1456   QualType type = var.getType();
1457 
1458   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1459     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1460     if (!copyExpr && record->hasTrivialDestructor()) return 0;
1461 
1462     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1463     return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1464   }
1465 
1466   BlockFieldFlags flags;
1467   if (type->isBlockPointerType()) {
1468     flags |= BLOCK_FIELD_IS_BLOCK;
1469   } else if (CGM.getContext().isObjCNSObjectType(type) ||
1470              type->isObjCObjectPointerType()) {
1471     flags |= BLOCK_FIELD_IS_OBJECT;
1472   } else {
1473     return 0;
1474   }
1475 
1476   if (type.isObjCGCWeak())
1477     flags |= BLOCK_FIELD_IS_WEAK;
1478 
1479   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1480   return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1481 }
1482 
1483 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1484   assert(ByRefValueInfo.count(VD) && "Did not find value!");
1485 
1486   return ByRefValueInfo.find(VD)->second.second;
1487 }
1488 
1489 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1490                                                      const VarDecl *V) {
1491   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1492   Loc = Builder.CreateLoad(Loc);
1493   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1494                                 V->getNameAsString());
1495   return Loc;
1496 }
1497 
1498 /// BuildByRefType - This routine changes a __block variable declared as T x
1499 ///   into:
1500 ///
1501 ///      struct {
1502 ///        void *__isa;
1503 ///        void *__forwarding;
1504 ///        int32_t __flags;
1505 ///        int32_t __size;
1506 ///        void *__copy_helper;       // only if needed
1507 ///        void *__destroy_helper;    // only if needed
1508 ///        char padding[X];           // only if needed
1509 ///        T x;
1510 ///      } x
1511 ///
1512 const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1513   std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1514   if (Info.first)
1515     return Info.first;
1516 
1517   QualType Ty = D->getType();
1518 
1519   std::vector<const llvm::Type *> Types;
1520 
1521   llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1522 
1523   // void *__isa;
1524   Types.push_back(Int8PtrTy);
1525 
1526   // void *__forwarding;
1527   Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
1528 
1529   // int32_t __flags;
1530   Types.push_back(Int32Ty);
1531 
1532   // int32_t __size;
1533   Types.push_back(Int32Ty);
1534 
1535   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1536   if (HasCopyAndDispose) {
1537     /// void *__copy_helper;
1538     Types.push_back(Int8PtrTy);
1539 
1540     /// void *__destroy_helper;
1541     Types.push_back(Int8PtrTy);
1542   }
1543 
1544   bool Packed = false;
1545   CharUnits Align = getContext().getDeclAlign(D);
1546   if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1547     // We have to insert padding.
1548 
1549     // The struct above has 2 32-bit integers.
1550     unsigned CurrentOffsetInBytes = 4 * 2;
1551 
1552     // And either 2 or 4 pointers.
1553     CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1554       CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1555 
1556     // Align the offset.
1557     unsigned AlignedOffsetInBytes =
1558       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1559 
1560     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1561     if (NumPaddingBytes > 0) {
1562       const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1563       // FIXME: We need a sema error for alignment larger than the minimum of
1564       // the maximal stack alignmint and the alignment of malloc on the system.
1565       if (NumPaddingBytes > 1)
1566         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1567 
1568       Types.push_back(Ty);
1569 
1570       // We want a packed struct.
1571       Packed = true;
1572     }
1573   }
1574 
1575   // T x;
1576   Types.push_back(ConvertTypeForMem(Ty));
1577 
1578   const llvm::Type *T = llvm::StructType::get(getLLVMContext(), Types, Packed);
1579 
1580   cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1581   CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1582                               ByRefTypeHolder.get());
1583 
1584   Info.first = ByRefTypeHolder.get();
1585 
1586   Info.second = Types.size() - 1;
1587 
1588   return Info.first;
1589 }
1590 
1591 /// Initialize the structural components of a __block variable, i.e.
1592 /// everything but the actual object.
1593 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
1594   // Find the address of the local.
1595   llvm::Value *addr = emission.Address;
1596 
1597   // That's an alloca of the byref structure type.
1598   const llvm::StructType *byrefType = cast<llvm::StructType>(
1599                  cast<llvm::PointerType>(addr->getType())->getElementType());
1600 
1601   // Build the byref helpers if necessary.  This is null if we don't need any.
1602   CodeGenModule::ByrefHelpers *helpers =
1603     buildByrefHelpers(*byrefType, emission);
1604 
1605   const VarDecl &D = *emission.Variable;
1606   QualType type = D.getType();
1607 
1608   llvm::Value *V;
1609 
1610   // Initialize the 'isa', which is just 0 or 1.
1611   int isa = 0;
1612   if (type.isObjCGCWeak())
1613     isa = 1;
1614   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1615   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1616 
1617   // Store the address of the variable into its own forwarding pointer.
1618   Builder.CreateStore(addr,
1619                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1620 
1621   // Blocks ABI:
1622   //   c) the flags field is set to either 0 if no helper functions are
1623   //      needed or BLOCK_HAS_COPY_DISPOSE if they are,
1624   BlockFlags flags;
1625   if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
1626   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1627                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
1628 
1629   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1630   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
1631   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1632 
1633   if (helpers) {
1634     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
1635     Builder.CreateStore(helpers->CopyHelper, copy_helper);
1636 
1637     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
1638     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
1639   }
1640 }
1641 
1642 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
1643   llvm::Value *F = CGM.getBlockObjectDispose();
1644   llvm::Value *N;
1645   V = Builder.CreateBitCast(V, Int8PtrTy);
1646   N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
1647   Builder.CreateCall2(F, V, N);
1648 }
1649 
1650 namespace {
1651   struct CallBlockRelease : EHScopeStack::Cleanup {
1652     llvm::Value *Addr;
1653     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1654 
1655     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1656       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1657     }
1658   };
1659 }
1660 
1661 /// Enter a cleanup to destroy a __block variable.  Note that this
1662 /// cleanup should be a no-op if the variable hasn't left the stack
1663 /// yet; if a cleanup is required for the variable itself, that needs
1664 /// to be done externally.
1665 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1666   // We don't enter this cleanup if we're in pure-GC mode.
1667   if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1668     return;
1669 
1670   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1671 }
1672