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