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