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 "clang/AST/DeclObjC.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Target/TargetData.h"
22 #include <algorithm>
23 
24 using namespace clang;
25 using namespace CodeGen;
26 
27 llvm::Constant *CodeGenFunction::
28 BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
29                          const llvm::StructType* Ty,
30                          std::vector<HelperInfo> *NoteForHelper) {
31   const llvm::Type *UnsignedLongTy
32     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
33   llvm::Constant *C;
34   std::vector<llvm::Constant*> Elts;
35 
36   // reserved
37   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
38   Elts.push_back(C);
39 
40   // Size
41   // FIXME: What is the right way to say this doesn't fit?  We should give
42   // a user diagnostic in that case.  Better fix would be to change the
43   // API to size_t.
44   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
45   Elts.push_back(C);
46 
47   // optional copy/dispose helpers
48   if (BlockHasCopyDispose) {
49     // copy_func_helper_decl
50     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
51 
52     // destroy_func_decl
53     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
54   }
55 
56   // Signature.  non-optional ObjC-style method descriptor @encode sequence
57   std::string BlockTypeEncoding;
58   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
59 
60   Elts.push_back(llvm::ConstantExpr::getBitCast(
61           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
62 
63   // Layout.
64   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
65   Elts.push_back(C);
66 
67   C = llvm::ConstantStruct::get(VMContext, Elts, false);
68 
69   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
70                                llvm::GlobalValue::InternalLinkage,
71                                C, "__block_descriptor_tmp");
72   return C;
73 }
74 
75 llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
76   if (NSConcreteGlobalBlock == 0)
77     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
78                                                       "_NSConcreteGlobalBlock");
79   return NSConcreteGlobalBlock;
80 }
81 
82 llvm::Constant *BlockModule::getNSConcreteStackBlock() {
83   if (NSConcreteStackBlock == 0)
84     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
85                                                      "_NSConcreteStackBlock");
86   return NSConcreteStackBlock;
87 }
88 
89 static void CollectBlockDeclRefInfo(
90   const Stmt *S, CodeGenFunction::BlockInfo &Info,
91   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
92   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
93        I != E; ++I)
94     if (*I)
95       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
96 
97   // We want to ensure we walk down into block literals so we can find
98   // all nested BlockDeclRefExprs.
99   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
100     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
101     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
102   }
103 
104   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
105     // FIXME: Handle enums.
106     if (isa<FunctionDecl>(BDRE->getDecl()))
107       return;
108 
109     // Only Decls that escape are added.
110     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
111       Info.DeclRefs.push_back(BDRE);
112   }
113 }
114 
115 /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
116 /// declared as a global variable instead of on the stack.
117 static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
118   return Info.DeclRefs.empty();
119 }
120 
121 /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
122 /// ensure we can generate the debug information for the parameter for the block
123 /// invoke function.
124 static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
125                                      CodeGenFunction *CGF) {
126   // FIXME: Also always forward the this pointer in C++ as well.
127 
128   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
129     CGF->AllocateBlockDecl(Info.DeclRefs[i]);
130 }
131 
132 // FIXME: Push most into CGM, passing down a few bits, like current function
133 // name.
134 llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
135 
136   std::string Name = CurFn->getName();
137   CodeGenFunction::BlockInfo Info(0, Name.c_str());
138   llvm::SmallSet<const DeclContext *, 16> InnerContexts;
139   InnerContexts.insert(BE->getBlockDecl());
140   CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
141 
142   // Check if the block can be global.
143   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
144   // to just have one code path.  We should move this function into CGM and pass
145   // CGF, then we can just check to see if CGF is 0.
146   if (0 && CanBlockBeGlobal(Info))
147     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
148 
149   size_t BlockFields = 5;
150 
151   std::vector<llvm::Constant*> Elts(BlockFields);
152 
153   llvm::Constant *C;
154   llvm::Value *V;
155 
156   {
157     // C = BuildBlockStructInitlist();
158     unsigned int flags = BLOCK_HAS_SIGNATURE;
159 
160     // We run this first so that we set BlockHasCopyDispose from the entire
161     // block literal.
162     // __invoke
163     CharUnits subBlockSize;
164     CharUnits subBlockAlign;
165     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
166     bool subBlockHasCopyDispose = false;
167     llvm::Function *Fn
168       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
169                                                    LocalDeclMap,
170                                                    subBlockSize,
171                                                    subBlockAlign,
172                                                    subBlockDeclRefDecls,
173                                                    subBlockHasCopyDispose);
174     BlockHasCopyDispose |= subBlockHasCopyDispose;
175     Elts[3] = Fn;
176 
177     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
178     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
179     if (subBlockHasCopyDispose)
180       flags |= BLOCK_HAS_COPY_DISPOSE;
181 
182     // __isa
183     C = CGM.getNSConcreteStackBlock();
184     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
185     Elts[0] = C;
186 
187     // __flags
188     {
189       QualType BPT = BE->getType();
190       const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
191       QualType ResultType = ftype->getResultType();
192 
193       CallArgList Args;
194       CodeGenTypes &Types = CGM.getTypes();
195       const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
196                                                        FunctionType::ExtInfo());
197       if (CGM.ReturnTypeUsesSret(FnInfo))
198         flags |= BLOCK_USE_STRET;
199     }
200     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
201       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
202     C = llvm::ConstantInt::get(IntTy, flags);
203     Elts[1] = C;
204 
205     // __reserved
206     C = llvm::ConstantInt::get(IntTy, 0);
207     Elts[2] = C;
208 
209     if (subBlockDeclRefDecls.size() == 0) {
210       // __descriptor
211       Elts[4] = BuildDescriptorBlockDecl(BE, subBlockHasCopyDispose, subBlockSize,
212                                          0, 0);
213 
214       // Optimize to being a global block.
215       Elts[0] = CGM.getNSConcreteGlobalBlock();
216 
217       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
218 
219       C = llvm::ConstantStruct::get(VMContext, Elts, false);
220 
221       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
222                                    llvm::GlobalValue::InternalLinkage, C,
223                                    "__block_holder_tmp_" +
224                                    llvm::Twine(CGM.getGlobalUniqueCount()));
225       QualType BPT = BE->getType();
226       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
227       return C;
228     }
229 
230     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
231     for (int i=0; i<4; ++i)
232       Types[i] = Elts[i]->getType();
233     Types[4] = PtrToInt8Ty;
234 
235     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
236       const Expr *E = subBlockDeclRefDecls[i];
237       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
238       QualType Ty = E->getType();
239       if (BDRE && BDRE->isByRef()) {
240         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
241       } else
242         Types[i+BlockFields] = ConvertType(Ty);
243     }
244 
245     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
246 
247     llvm::AllocaInst *A = CreateTempAlloca(Ty);
248     A->setAlignment(subBlockAlign.getQuantity());
249     V = A;
250 
251     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
252     int helpersize = 0;
253 
254     for (unsigned i=0; i<4; ++i)
255       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
256 
257     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
258       {
259         // FIXME: Push const down.
260         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
261         DeclRefExpr *DR;
262         ValueDecl *VD;
263 
264         DR = dyn_cast<DeclRefExpr>(E);
265         // Skip padding.
266         if (DR) continue;
267 
268         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
269         VD = BDRE->getDecl();
270 
271         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
272         NoteForHelper[helpersize].index = i+5;
273         NoteForHelper[helpersize].RequiresCopying
274           = BlockRequiresCopying(VD->getType());
275         NoteForHelper[helpersize].flag
276           = (VD->getType()->isBlockPointerType()
277              ? BLOCK_FIELD_IS_BLOCK
278              : BLOCK_FIELD_IS_OBJECT);
279 
280         if (LocalDeclMap[VD]) {
281           if (BDRE->isByRef()) {
282             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
283               // FIXME: Someone double check this.
284               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
285             llvm::Value *Loc = LocalDeclMap[VD];
286             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
287             Loc = Builder.CreateLoad(Loc);
288             Builder.CreateStore(Loc, Addr);
289             ++helpersize;
290             continue;
291           } else
292             E = new (getContext()) DeclRefExpr (VD,
293                                                 VD->getType(),
294                                                 SourceLocation());
295         }
296         if (BDRE->isByRef()) {
297           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
298             // FIXME: Someone double check this.
299             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
300           E = new (getContext())
301             UnaryOperator(E, UnaryOperator::AddrOf,
302                           getContext().getPointerType(E->getType()),
303                           SourceLocation());
304         }
305         ++helpersize;
306 
307         RValue r = EmitAnyExpr(E, Addr, false);
308         if (r.isScalar()) {
309           llvm::Value *Loc = r.getScalarVal();
310           const llvm::Type *Ty = Types[i+BlockFields];
311           if  (BDRE->isByRef()) {
312             // E is now the address of the value field, instead, we want the
313             // address of the actual ByRef struct.  We optimize this slightly
314             // compared to gcc by not grabbing the forwarding slot as this must
315             // be done during Block_copy for us, and we can postpone the work
316             // until then.
317             CharUnits offset = BlockDecls[BDRE->getDecl()];
318 
319             llvm::Value *BlockLiteral = LoadBlockStruct();
320 
321             Loc = Builder.CreateGEP(BlockLiteral,
322                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
323                                                            offset.getQuantity()),
324                                     "block.literal");
325             Ty = llvm::PointerType::get(Ty, 0);
326             Loc = Builder.CreateBitCast(Loc, Ty);
327             Loc = Builder.CreateLoad(Loc);
328             // Loc = Builder.CreateBitCast(Loc, Ty);
329           }
330           Builder.CreateStore(Loc, Addr);
331         } else if (r.isComplex())
332           // FIXME: implement
333           ErrorUnsupported(BE, "complex in block literal");
334         else if (r.isAggregate())
335           ; // Already created into the destination
336         else
337           assert (0 && "bad block variable");
338         // FIXME: Ensure that the offset created by the backend for
339         // the struct matches the previously computed offset in BlockDecls.
340       }
341     NoteForHelper.resize(helpersize);
342 
343     // __descriptor
344     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
345                                                        subBlockHasCopyDispose,
346                                                        subBlockSize, Ty,
347                                                        &NoteForHelper);
348     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
349     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
350   }
351 
352   QualType BPT = BE->getType();
353   V = Builder.CreateBitCast(V, ConvertType(BPT));
354   // See if this is a __weak block variable and the must call objc_read_weak
355   // on it.
356   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
357   QualType RES = ftype->getResultType();
358   if (RES.isObjCGCWeak()) {
359     // Must cast argument to id*
360     const llvm::Type *ObjectPtrTy =
361       ConvertType(CGM.getContext().getObjCIdType());
362     const llvm::Type *PtrObjectPtrTy =
363       llvm::PointerType::getUnqual(ObjectPtrTy);
364     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
365     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
366   }
367   return V;
368 }
369 
370 
371 const llvm::Type *BlockModule::getBlockDescriptorType() {
372   if (BlockDescriptorType)
373     return BlockDescriptorType;
374 
375   const llvm::Type *UnsignedLongTy =
376     getTypes().ConvertType(getContext().UnsignedLongTy);
377 
378   // struct __block_descriptor {
379   //   unsigned long reserved;
380   //   unsigned long block_size;
381   //
382   //   // later, the following will be added
383   //
384   //   struct {
385   //     void (*copyHelper)();
386   //     void (*copyHelper)();
387   //   } helpers;                // !!! optional
388   //
389   //   const char *signature;   // the block signature
390   //   const char *layout;      // reserved
391   // };
392   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
393                                               UnsignedLongTy,
394                                               UnsignedLongTy,
395                                               NULL);
396 
397   getModule().addTypeName("struct.__block_descriptor",
398                           BlockDescriptorType);
399 
400   return BlockDescriptorType;
401 }
402 
403 const llvm::Type *BlockModule::getGenericBlockLiteralType() {
404   if (GenericBlockLiteralType)
405     return GenericBlockLiteralType;
406 
407   const llvm::Type *BlockDescPtrTy =
408     llvm::PointerType::getUnqual(getBlockDescriptorType());
409 
410   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
411     getTypes().ConvertType(getContext().IntTy));
412 
413   // struct __block_literal_generic {
414   //   void *__isa;
415   //   int __flags;
416   //   int __reserved;
417   //   void (*__invoke)(void *);
418   //   struct __block_descriptor *__descriptor;
419   // };
420   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
421                                                   PtrToInt8Ty,
422                                                   IntTy,
423                                                   IntTy,
424                                                   PtrToInt8Ty,
425                                                   BlockDescPtrTy,
426                                                   NULL);
427 
428   getModule().addTypeName("struct.__block_literal_generic",
429                           GenericBlockLiteralType);
430 
431   return GenericBlockLiteralType;
432 }
433 
434 
435 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
436                                           ReturnValueSlot ReturnValue) {
437   const BlockPointerType *BPT =
438     E->getCallee()->getType()->getAs<BlockPointerType>();
439 
440   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
441 
442   // Get a pointer to the generic block literal.
443   const llvm::Type *BlockLiteralTy =
444     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
445 
446   // Bitcast the callee to a block literal.
447   llvm::Value *BlockLiteral =
448     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
449 
450   // Get the function pointer from the literal.
451   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
452 
453   BlockLiteral =
454     Builder.CreateBitCast(BlockLiteral,
455                           llvm::Type::getInt8PtrTy(VMContext),
456                           "tmp");
457 
458   // Add the block literal.
459   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
460   CallArgList Args;
461   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
462 
463   QualType FnType = BPT->getPointeeType();
464 
465   // And the rest of the arguments.
466   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
467                E->arg_begin(), E->arg_end());
468 
469   // Load the function.
470   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
471 
472   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
473   QualType ResultType = FuncTy->getResultType();
474 
475   const CGFunctionInfo &FnInfo =
476     CGM.getTypes().getFunctionInfo(ResultType, Args,
477                                    FuncTy->getExtInfo());
478 
479   // Cast the function pointer to the right type.
480   const llvm::Type *BlockFTy =
481     CGM.getTypes().GetFunctionType(FnInfo, false);
482 
483   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
484   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
485 
486   // And call the block.
487   return EmitCall(FnInfo, Func, ReturnValue, Args);
488 }
489 
490 CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
491   const ValueDecl *VD = E->getDecl();
492   CharUnits &offset = BlockDecls[VD];
493 
494   // See if we have already allocated an offset for this variable.
495   if (offset.isPositive())
496     return offset;
497 
498   // Don't run the expensive check, unless we have to.
499   if (!BlockHasCopyDispose)
500     if (E->isByRef()
501         || BlockRequiresCopying(E->getType()))
502       BlockHasCopyDispose = true;
503 
504   // if not, allocate one now.
505   offset = getBlockOffset(E);
506 
507   return offset;
508 }
509 
510 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
511   const ValueDecl *VD = E->getDecl();
512   CharUnits offset = AllocateBlockDecl(E);
513 
514 
515   llvm::Value *BlockLiteral = LoadBlockStruct();
516   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
517                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
518                                                          offset.getQuantity()),
519                                      "block.literal");
520   if (E->isByRef()) {
521     const llvm::Type *PtrStructTy
522       = llvm::PointerType::get(BuildByRefType(VD), 0);
523     // The block literal will need a copy/destroy helper.
524     BlockHasCopyDispose = true;
525 
526     const llvm::Type *Ty = PtrStructTy;
527     Ty = llvm::PointerType::get(Ty, 0);
528     V = Builder.CreateBitCast(V, Ty);
529     V = Builder.CreateLoad(V);
530     V = Builder.CreateStructGEP(V, 1, "forwarding");
531     V = Builder.CreateLoad(V);
532     V = Builder.CreateBitCast(V, PtrStructTy);
533     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
534                                 VD->getNameAsString());
535     if (VD->getType()->isReferenceType())
536       V = Builder.CreateLoad(V);
537   } else {
538     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
539 
540     Ty = llvm::PointerType::get(Ty, 0);
541     V = Builder.CreateBitCast(V, Ty);
542   }
543   return V;
544 }
545 
546 void CodeGenFunction::BlockForwardSelf() {
547   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
548   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
549   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
550   if (DMEntry)
551     return;
552   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
553   BlockDeclRefExpr *BDRE = new (getContext())
554     BlockDeclRefExpr(SelfDecl,
555                      SelfDecl->getType(), SourceLocation(), false);
556   DMEntry = GetAddrOfBlockDecl(BDRE);
557 }
558 
559 llvm::Constant *
560 BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
561   // Generate the block descriptor.
562   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
563   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
564     getTypes().ConvertType(getContext().IntTy));
565 
566   llvm::Constant *DescriptorFields[4];
567 
568   // Reserved
569   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
570 
571   // Block literal size. For global blocks we just use the size of the generic
572   // block literal struct.
573   CharUnits BlockLiteralSize =
574     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
575   DescriptorFields[1] =
576     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
577 
578   // signature.  non-optional ObjC-style method descriptor @encode sequence
579   std::string BlockTypeEncoding;
580   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
581 
582   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
583           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
584 
585   // layout
586   DescriptorFields[3] =
587     llvm::ConstantInt::get(UnsignedLongTy,0);
588 
589   // build the structure from the 4 elements
590   llvm::Constant *DescriptorStruct =
591     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
592 
593   llvm::GlobalVariable *Descriptor =
594     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
595                              llvm::GlobalVariable::InternalLinkage,
596                              DescriptorStruct, "__block_descriptor_global");
597 
598   int FieldCount = 5;
599   // Generate the constants for the block literal.
600 
601   std::vector<llvm::Constant*> LiteralFields(FieldCount);
602 
603   CodeGenFunction::BlockInfo Info(0, n);
604   CharUnits subBlockSize;
605   CharUnits subBlockAlign;
606   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
607   bool subBlockHasCopyDispose = false;
608   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
609   llvm::Function *Fn
610     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
611                                                  subBlockSize,
612                                                  subBlockAlign,
613                                                  subBlockDeclRefDecls,
614                                                  subBlockHasCopyDispose);
615   assert(subBlockSize == BlockLiteralSize
616          && "no imports allowed for global block");
617 
618   // isa
619   LiteralFields[0] = getNSConcreteGlobalBlock();
620 
621   // Flags
622   LiteralFields[1] =
623     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
624 
625   // Reserved
626   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
627 
628   // Function
629   LiteralFields[3] = Fn;
630 
631   // Descriptor
632   LiteralFields[4] = Descriptor;
633 
634   llvm::Constant *BlockLiteralStruct =
635     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
636 
637   llvm::GlobalVariable *BlockLiteral =
638     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
639                              llvm::GlobalVariable::InternalLinkage,
640                              BlockLiteralStruct, "__block_literal_global");
641 
642   return BlockLiteral;
643 }
644 
645 llvm::Value *CodeGenFunction::LoadBlockStruct() {
646   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
647                                       "self");
648   // For now, we codegen based upon byte offsets.
649   return Builder.CreateBitCast(V, PtrToInt8Ty);
650 }
651 
652 llvm::Function *
653 CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
654                                        const BlockInfo& Info,
655                                        const Decl *OuterFuncDecl,
656                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
657                                        CharUnits &Size,
658                                        CharUnits &Align,
659                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
660                                        bool &subBlockHasCopyDispose) {
661 
662   // Check if we should generate debug info for this block.
663   if (CGM.getDebugInfo())
664     DebugInfo = CGM.getDebugInfo();
665 
666   // Arrange for local static and local extern declarations to appear
667   // to be local to this function as well, as they are directly referenced
668   // in a block.
669   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
670        i != ldm.end();
671        ++i) {
672     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
673 
674     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
675       LocalDeclMap[VD] = i->second;
676   }
677 
678   BlockOffset =
679       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
680   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
681 
682   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
683   QualType ResultType;
684   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
685   bool IsVariadic;
686   if (const FunctionProtoType *FTy =
687       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
688     ResultType = FTy->getResultType();
689     IsVariadic = FTy->isVariadic();
690   } else {
691     // K&R style block.
692     ResultType = BlockFunctionType->getResultType();
693     IsVariadic = false;
694   }
695 
696   FunctionArgList Args;
697 
698   CurFuncDecl = OuterFuncDecl;
699 
700   const BlockDecl *BD = BExpr->getBlockDecl();
701 
702   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
703 
704   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
705   AllocateAllBlockDeclRefs(Info, this);
706 
707   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
708                                                   BlockDeclRefDecls);
709   // FIXME: This leaks
710   ImplicitParamDecl *SelfDecl =
711     ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
712                               SourceLocation(), II,
713                               ParmTy);
714 
715   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
716   BlockStructDecl = SelfDecl;
717 
718   for (BlockDecl::param_const_iterator i = BD->param_begin(),
719        e = BD->param_end(); i != e; ++i)
720     Args.push_back(std::make_pair(*i, (*i)->getType()));
721 
722   const CGFunctionInfo &FI =
723     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
724 
725   CodeGenTypes &Types = CGM.getTypes();
726   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
727 
728   llvm::Function *Fn =
729     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
730                            llvm::Twine("__") + Info.Name + "_block_invoke_",
731                            &CGM.getModule());
732 
733   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
734 
735   StartFunction(BD, ResultType, Fn, Args,
736                 BExpr->getBody()->getLocEnd());
737 
738   CurFuncDecl = OuterFuncDecl;
739   CurCodeDecl = BD;
740 
741   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
742   llvm::BasicBlock *entry = Builder.GetInsertBlock();
743   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
744   --entry_ptr;
745 
746   EmitStmt(BExpr->getBody());
747 
748   // Remember where we were...
749   llvm::BasicBlock *resume = Builder.GetInsertBlock();
750 
751   // Go back to the entry.
752   ++entry_ptr;
753   Builder.SetInsertPoint(entry, entry_ptr);
754 
755   if (CGDebugInfo *DI = getDebugInfo()) {
756     // Emit debug information for all the BlockDeclRefDecls.
757     for (unsigned i = 0, e = BlockDeclRefDecls.size(); i != e; ++i) {
758       if (const BlockDeclRefExpr *BDRE =
759             dyn_cast<BlockDeclRefExpr>(BlockDeclRefDecls[i])) {
760         const ValueDecl *D = BDRE->getDecl();
761         DI->setLocation(D->getLocation());
762         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
763                                              LocalDeclMap[getBlockStructDecl()],
764                                               Builder, this);
765       }
766     }
767   }
768   // And resume where we left off.
769   if (resume == 0)
770     Builder.ClearInsertionPoint();
771   else
772     Builder.SetInsertPoint(resume);
773 
774   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
775 
776   // The runtime needs a minimum alignment of a void *.
777   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
778   BlockOffset = CharUnits::fromQuantity(
779       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
780                                MinAlign.getQuantity()));
781 
782   Size = BlockOffset;
783   Align = BlockAlign;
784   subBlockDeclRefDecls = BlockDeclRefDecls;
785   subBlockHasCopyDispose |= BlockHasCopyDispose;
786   return Fn;
787 }
788 
789 CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
790   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
791 
792   CharUnits Size = getContext().getTypeSizeInChars(D->getType());
793   CharUnits Align = getContext().getDeclAlign(D);
794 
795   if (BDRE->isByRef()) {
796     Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
797     Align = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
798   }
799 
800   assert ((Align.isPositive()) && "alignment must be 1 byte or more");
801 
802   CharUnits OldOffset = BlockOffset;
803 
804   // Ensure proper alignment, even if it means we have to have a gap
805   BlockOffset = CharUnits::fromQuantity(
806       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
807   BlockAlign = std::max(Align, BlockAlign);
808 
809   CharUnits Pad = BlockOffset - OldOffset;
810   if (Pad.isPositive()) {
811     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
812     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
813                                                        llvm::APInt(32,
814                                                          Pad.getQuantity()),
815                                                        ArrayType::Normal, 0);
816     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
817                                          0, QualType(PadTy), 0,
818                                          VarDecl::None, VarDecl::None);
819     Expr *E;
820     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
821                                        SourceLocation());
822     BlockDeclRefDecls.push_back(E);
823   }
824   BlockDeclRefDecls.push_back(BDRE);
825 
826   BlockOffset += Size;
827   return BlockOffset-Size;
828 }
829 
830 llvm::Constant *BlockFunction::
831 GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
832                            std::vector<HelperInfo> *NoteForHelperp) {
833   QualType R = getContext().VoidTy;
834 
835   FunctionArgList Args;
836   // FIXME: This leaks
837   ImplicitParamDecl *Dst =
838     ImplicitParamDecl::Create(getContext(), 0,
839                               SourceLocation(), 0,
840                               getContext().getPointerType(getContext().VoidTy));
841   Args.push_back(std::make_pair(Dst, Dst->getType()));
842   ImplicitParamDecl *Src =
843     ImplicitParamDecl::Create(getContext(), 0,
844                               SourceLocation(), 0,
845                               getContext().getPointerType(getContext().VoidTy));
846   Args.push_back(std::make_pair(Src, Src->getType()));
847 
848   const CGFunctionInfo &FI =
849       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
850 
851   // FIXME: We'd like to put these into a mergable by content, with
852   // internal linkage.
853   CodeGenTypes &Types = CGM.getTypes();
854   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
855 
856   llvm::Function *Fn =
857     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
858                            "__copy_helper_block_", &CGM.getModule());
859 
860   IdentifierInfo *II
861     = &CGM.getContext().Idents.get("__copy_helper_block_");
862 
863   FunctionDecl *FD = FunctionDecl::Create(getContext(),
864                                           getContext().getTranslationUnitDecl(),
865                                           SourceLocation(), II, R, 0,
866                                           FunctionDecl::Static,
867                                           FunctionDecl::None,
868                                           false,
869                                           true);
870   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
871 
872   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
873   llvm::Type *PtrPtrT;
874 
875   if (NoteForHelperp) {
876     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
877 
878     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
879     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
880     SrcObj = Builder.CreateLoad(SrcObj);
881 
882     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
883     llvm::Type *PtrPtrT;
884     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
885     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
886     DstObj = Builder.CreateLoad(DstObj);
887 
888     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
889       int flag = NoteForHelper[i].flag;
890       int index = NoteForHelper[i].index;
891 
892       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
893           || NoteForHelper[i].RequiresCopying) {
894         llvm::Value *Srcv = SrcObj;
895         Srcv = Builder.CreateStructGEP(Srcv, index);
896         Srcv = Builder.CreateBitCast(Srcv,
897                                      llvm::PointerType::get(PtrToInt8Ty, 0));
898         Srcv = Builder.CreateLoad(Srcv);
899 
900         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
901         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
902 
903         llvm::Value *N = llvm::ConstantInt::get(
904               llvm::Type::getInt32Ty(T->getContext()), flag);
905         llvm::Value *F = getBlockObjectAssign();
906         Builder.CreateCall3(F, Dstv, Srcv, N);
907       }
908     }
909   }
910 
911   CGF.FinishFunction();
912 
913   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
914 }
915 
916 llvm::Constant *BlockFunction::
917 GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
918                               const llvm::StructType* T,
919                               std::vector<HelperInfo> *NoteForHelperp) {
920   QualType R = getContext().VoidTy;
921 
922   FunctionArgList Args;
923   // FIXME: This leaks
924   ImplicitParamDecl *Src =
925     ImplicitParamDecl::Create(getContext(), 0,
926                               SourceLocation(), 0,
927                               getContext().getPointerType(getContext().VoidTy));
928 
929   Args.push_back(std::make_pair(Src, Src->getType()));
930 
931   const CGFunctionInfo &FI =
932       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
933 
934   // FIXME: We'd like to put these into a mergable by content, with
935   // internal linkage.
936   CodeGenTypes &Types = CGM.getTypes();
937   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
938 
939   llvm::Function *Fn =
940     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
941                            "__destroy_helper_block_", &CGM.getModule());
942 
943   IdentifierInfo *II
944     = &CGM.getContext().Idents.get("__destroy_helper_block_");
945 
946   FunctionDecl *FD = FunctionDecl::Create(getContext(),
947                                           getContext().getTranslationUnitDecl(),
948                                           SourceLocation(), II, R, 0,
949                                           FunctionDecl::Static,
950                                           FunctionDecl::None,
951                                           false, true);
952   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
953 
954   if (NoteForHelperp) {
955     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
956 
957     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
958     llvm::Type *PtrPtrT;
959     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
960     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
961     SrcObj = Builder.CreateLoad(SrcObj);
962 
963     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
964       int flag = NoteForHelper[i].flag;
965       int index = NoteForHelper[i].index;
966 
967       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
968           || NoteForHelper[i].RequiresCopying) {
969         llvm::Value *Srcv = SrcObj;
970         Srcv = Builder.CreateStructGEP(Srcv, index);
971         Srcv = Builder.CreateBitCast(Srcv,
972                                      llvm::PointerType::get(PtrToInt8Ty, 0));
973         Srcv = Builder.CreateLoad(Srcv);
974 
975         BuildBlockRelease(Srcv, flag);
976       }
977     }
978   }
979 
980   CGF.FinishFunction();
981 
982   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
983 }
984 
985 llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
986                                        std::vector<HelperInfo> *NoteForHelper) {
987   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
988                                                          T, NoteForHelper);
989 }
990 
991 llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
992                                       std::vector<HelperInfo> *NoteForHelperp) {
993   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
994                                                             T, NoteForHelperp);
995 }
996 
997 llvm::Constant *BlockFunction::
998 GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
999   QualType R = getContext().VoidTy;
1000 
1001   FunctionArgList Args;
1002   // FIXME: This leaks
1003   ImplicitParamDecl *Dst =
1004     ImplicitParamDecl::Create(getContext(), 0,
1005                               SourceLocation(), 0,
1006                               getContext().getPointerType(getContext().VoidTy));
1007   Args.push_back(std::make_pair(Dst, Dst->getType()));
1008 
1009   // FIXME: This leaks
1010   ImplicitParamDecl *Src =
1011     ImplicitParamDecl::Create(getContext(), 0,
1012                               SourceLocation(), 0,
1013                               getContext().getPointerType(getContext().VoidTy));
1014   Args.push_back(std::make_pair(Src, Src->getType()));
1015 
1016   const CGFunctionInfo &FI =
1017       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1018 
1019   CodeGenTypes &Types = CGM.getTypes();
1020   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1021 
1022   // FIXME: We'd like to put these into a mergable by content, with
1023   // internal linkage.
1024   llvm::Function *Fn =
1025     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1026                            "__Block_byref_id_object_copy_", &CGM.getModule());
1027 
1028   IdentifierInfo *II
1029     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1030 
1031   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1032                                           getContext().getTranslationUnitDecl(),
1033                                           SourceLocation(), II, R, 0,
1034                                           FunctionDecl::Static,
1035                                           FunctionDecl::None,
1036                                           false, true);
1037   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1038 
1039   // dst->x
1040   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
1041   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
1042   V = Builder.CreateLoad(V);
1043   V = Builder.CreateStructGEP(V, 6, "x");
1044   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1045 
1046   // src->x
1047   V = CGF.GetAddrOfLocalVar(Src);
1048   V = Builder.CreateLoad(V);
1049   V = Builder.CreateBitCast(V, T);
1050   V = Builder.CreateStructGEP(V, 6, "x");
1051   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1052   llvm::Value *SrcObj = Builder.CreateLoad(V);
1053 
1054   flag |= BLOCK_BYREF_CALLER;
1055 
1056   llvm::Value *N = llvm::ConstantInt::get(
1057           llvm::Type::getInt32Ty(T->getContext()), flag);
1058   llvm::Value *F = getBlockObjectAssign();
1059   Builder.CreateCall3(F, DstObj, SrcObj, N);
1060 
1061   CGF.FinishFunction();
1062 
1063   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1064 }
1065 
1066 llvm::Constant *
1067 BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1068                                                   int flag) {
1069   QualType R = getContext().VoidTy;
1070 
1071   FunctionArgList Args;
1072   // FIXME: This leaks
1073   ImplicitParamDecl *Src =
1074     ImplicitParamDecl::Create(getContext(), 0,
1075                               SourceLocation(), 0,
1076                               getContext().getPointerType(getContext().VoidTy));
1077 
1078   Args.push_back(std::make_pair(Src, Src->getType()));
1079 
1080   const CGFunctionInfo &FI =
1081       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1082 
1083   CodeGenTypes &Types = CGM.getTypes();
1084   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1085 
1086   // FIXME: We'd like to put these into a mergable by content, with
1087   // internal linkage.
1088   llvm::Function *Fn =
1089     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1090                            "__Block_byref_id_object_dispose_",
1091                            &CGM.getModule());
1092 
1093   IdentifierInfo *II
1094     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1095 
1096   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1097                                           getContext().getTranslationUnitDecl(),
1098                                           SourceLocation(), II, R, 0,
1099                                           FunctionDecl::Static,
1100                                           FunctionDecl::None,
1101                                           false, true);
1102   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1103 
1104   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
1105   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
1106   V = Builder.CreateLoad(V);
1107   V = Builder.CreateStructGEP(V, 6, "x");
1108   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1109   V = Builder.CreateLoad(V);
1110 
1111   flag |= BLOCK_BYREF_CALLER;
1112   BuildBlockRelease(V, flag);
1113   CGF.FinishFunction();
1114 
1115   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1116 }
1117 
1118 llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1119                                                     int Flag, unsigned Align) {
1120   // All alignments below that of pointer alignment collapse down to just
1121   // pointer alignment, as we always have at least that much alignment to begin
1122   // with.
1123   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1124 
1125   // As an optimization, we only generate a single function of each kind we
1126   // might need.  We need a different one for each alignment and for each
1127   // setting of flags.  We mix Align and flag to get the kind.
1128   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1129   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1130   if (Entry)
1131     return Entry;
1132   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1133 }
1134 
1135 llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1136                                                        int Flag,
1137                                                        unsigned Align) {
1138   // All alignments below that of pointer alignment collpase down to just
1139   // pointer alignment, as we always have at least that much alignment to begin
1140   // with.
1141   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1142 
1143   // As an optimization, we only generate a single function of each kind we
1144   // might need.  We need a different one for each alignment and for each
1145   // setting of flags.  We mix Align and flag to get the kind.
1146   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1147   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1148   if (Entry)
1149     return Entry;
1150   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1151 }
1152 
1153 llvm::Value *BlockFunction::getBlockObjectDispose() {
1154   if (CGM.BlockObjectDispose == 0) {
1155     const llvm::FunctionType *FTy;
1156     std::vector<const llvm::Type*> ArgTys;
1157     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1158     ArgTys.push_back(PtrToInt8Ty);
1159     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
1160     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1161     CGM.BlockObjectDispose
1162       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1163   }
1164   return CGM.BlockObjectDispose;
1165 }
1166 
1167 llvm::Value *BlockFunction::getBlockObjectAssign() {
1168   if (CGM.BlockObjectAssign == 0) {
1169     const llvm::FunctionType *FTy;
1170     std::vector<const llvm::Type*> ArgTys;
1171     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1172     ArgTys.push_back(PtrToInt8Ty);
1173     ArgTys.push_back(PtrToInt8Ty);
1174     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
1175     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1176     CGM.BlockObjectAssign
1177       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1178   }
1179   return CGM.BlockObjectAssign;
1180 }
1181 
1182 void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1183   llvm::Value *F = getBlockObjectDispose();
1184   llvm::Value *N;
1185   V = Builder.CreateBitCast(V, PtrToInt8Ty);
1186   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1187   Builder.CreateCall2(F, V, N);
1188 }
1189 
1190 ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1191 
1192 BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1193                              CGBuilderTy &B)
1194   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
1195   PtrToInt8Ty = llvm::PointerType::getUnqual(
1196             llvm::Type::getInt8Ty(VMContext));
1197 
1198   BlockHasCopyDispose = false;
1199 }
1200