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