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