clang API Documentation

CGBlocks.cpp
Go to the documentation of this file.
00001 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit blocks.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CGBlocks.h"
00015 #include "CGDebugInfo.h"
00016 #include "CGObjCRuntime.h"
00017 #include "CodeGenFunction.h"
00018 #include "CodeGenModule.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/Module.h"
00024 #include <algorithm>
00025 #include <cstdio>
00026 
00027 using namespace clang;
00028 using namespace CodeGen;
00029 
00030 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
00031   : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
00032     HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
00033     StructureType(0), Block(block),
00034     DominatingIP(0) {
00035     
00036   // Skip asm prefix, if any.  'name' is usually taken directly from
00037   // the mangled name of the enclosing function.
00038   if (!name.empty() && name[0] == '\01')
00039     name = name.substr(1);
00040 }
00041 
00042 // Anchor the vtable to this translation unit.
00043 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
00044 
00045 /// Build the given block as a global block.
00046 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
00047                                         const CGBlockInfo &blockInfo,
00048                                         llvm::Constant *blockFn);
00049 
00050 /// Build the helper function to copy a block.
00051 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
00052                                        const CGBlockInfo &blockInfo) {
00053   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
00054 }
00055 
00056 /// Build the helper function to dispose of a block.
00057 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
00058                                           const CGBlockInfo &blockInfo) {
00059   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
00060 }
00061 
00062 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
00063 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
00064 /// meta-data and contains stationary information about the block literal.
00065 /// Its definition will have 4 (or optinally 6) words.
00066 /// \code
00067 /// struct Block_descriptor {
00068 ///   unsigned long reserved;
00069 ///   unsigned long size;  // size of Block_literal metadata in bytes.
00070 ///   void *copy_func_helper_decl;  // optional copy helper.
00071 ///   void *destroy_func_decl; // optioanl destructor helper.
00072 ///   void *block_method_encoding_address; // @encode for block literal signature.
00073 ///   void *block_layout_info; // encoding of captured block variables.
00074 /// };
00075 /// \endcode
00076 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
00077                                             const CGBlockInfo &blockInfo) {
00078   ASTContext &C = CGM.getContext();
00079 
00080   llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
00081   llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
00082 
00083   SmallVector<llvm::Constant*, 6> elements;
00084 
00085   // reserved
00086   elements.push_back(llvm::ConstantInt::get(ulong, 0));
00087 
00088   // Size
00089   // FIXME: What is the right way to say this doesn't fit?  We should give
00090   // a user diagnostic in that case.  Better fix would be to change the
00091   // API to size_t.
00092   elements.push_back(llvm::ConstantInt::get(ulong,
00093                                             blockInfo.BlockSize.getQuantity()));
00094 
00095   // Optional copy/dispose helpers.
00096   if (blockInfo.NeedsCopyDispose) {
00097     // copy_func_helper_decl
00098     elements.push_back(buildCopyHelper(CGM, blockInfo));
00099 
00100     // destroy_func_decl
00101     elements.push_back(buildDisposeHelper(CGM, blockInfo));
00102   }
00103 
00104   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
00105   std::string typeAtEncoding =
00106     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
00107   elements.push_back(llvm::ConstantExpr::getBitCast(
00108                           CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
00109   
00110   // GC layout.
00111   if (C.getLangOpts().ObjC1) {
00112     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
00113       elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
00114     else
00115       elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
00116   }
00117   else
00118     elements.push_back(llvm::Constant::getNullValue(i8p));
00119 
00120   llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
00121 
00122   llvm::GlobalVariable *global =
00123     new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
00124                              llvm::GlobalValue::InternalLinkage,
00125                              init, "__block_descriptor_tmp");
00126 
00127   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
00128 }
00129 
00130 /*
00131   Purely notional variadic template describing the layout of a block.
00132 
00133   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
00134   struct Block_literal {
00135     /// Initialized to one of:
00136     ///   extern void *_NSConcreteStackBlock[];
00137     ///   extern void *_NSConcreteGlobalBlock[];
00138     ///
00139     /// In theory, we could start one off malloc'ed by setting
00140     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
00141     /// this isa:
00142     ///   extern void *_NSConcreteMallocBlock[];
00143     struct objc_class *isa;
00144 
00145     /// These are the flags (with corresponding bit number) that the
00146     /// compiler is actually supposed to know about.
00147     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
00148     ///   descriptor provides copy and dispose helper functions
00149     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
00150     ///   object with a nontrivial destructor or copy constructor
00151     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
00152     ///   as global memory
00153     ///  29. BLOCK_USE_STRET - indicates that the block function
00154     ///   uses stret, which objc_msgSend needs to know about
00155     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
00156     ///   @encoded signature string
00157     /// And we're not supposed to manipulate these:
00158     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
00159     ///   to malloc'ed memory
00160     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
00161     ///   to GC-allocated memory
00162     /// Additionally, the bottom 16 bits are a reference count which
00163     /// should be zero on the stack.
00164     int flags;
00165 
00166     /// Reserved;  should be zero-initialized.
00167     int reserved;
00168 
00169     /// Function pointer generated from block literal.
00170     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
00171 
00172     /// Block description metadata generated from block literal.
00173     struct Block_descriptor *block_descriptor;
00174 
00175     /// Captured values follow.
00176     _CapturesTypes captures...;
00177   };
00178  */
00179 
00180 /// The number of fields in a block header.
00181 const unsigned BlockHeaderSize = 5;
00182 
00183 namespace {
00184   /// A chunk of data that we actually have to capture in the block.
00185   struct BlockLayoutChunk {
00186     CharUnits Alignment;
00187     CharUnits Size;
00188     Qualifiers::ObjCLifetime Lifetime;
00189     const BlockDecl::Capture *Capture; // null for 'this'
00190     llvm::Type *Type;
00191 
00192     BlockLayoutChunk(CharUnits align, CharUnits size,
00193                      Qualifiers::ObjCLifetime lifetime,
00194                      const BlockDecl::Capture *capture,
00195                      llvm::Type *type)
00196       : Alignment(align), Size(size), Lifetime(lifetime),
00197         Capture(capture), Type(type) {}
00198 
00199     /// Tell the block info that this chunk has the given field index.
00200     void setIndex(CGBlockInfo &info, unsigned index) {
00201       if (!Capture)
00202         info.CXXThisIndex = index;
00203       else
00204         info.Captures[Capture->getVariable()]
00205           = CGBlockInfo::Capture::makeIndex(index);
00206     }
00207   };
00208 
00209   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
00210   /// all __weak together. Preserve descending alignment in all situations.
00211   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
00212     CharUnits LeftValue, RightValue;
00213     bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
00214     bool RightByref = right.Capture ? right.Capture->isByRef() : false;
00215     
00216     if (left.Lifetime == Qualifiers::OCL_Strong &&
00217         left.Alignment >= right.Alignment)
00218       LeftValue = CharUnits::fromQuantity(64);
00219     else if (LeftByref && left.Alignment >= right.Alignment)
00220       LeftValue = CharUnits::fromQuantity(32);
00221     else if (left.Lifetime == Qualifiers::OCL_Weak &&
00222              left.Alignment >= right.Alignment)
00223       LeftValue = CharUnits::fromQuantity(16);
00224     else
00225       LeftValue = left.Alignment;
00226     if (right.Lifetime == Qualifiers::OCL_Strong &&
00227         right.Alignment >= left.Alignment)
00228       RightValue = CharUnits::fromQuantity(64);
00229     else if (RightByref && right.Alignment >= left.Alignment)
00230       RightValue = CharUnits::fromQuantity(32);
00231     else if (right.Lifetime == Qualifiers::OCL_Weak &&
00232              right.Alignment >= left.Alignment)
00233       RightValue = CharUnits::fromQuantity(16);
00234     else
00235       RightValue = right.Alignment;
00236     
00237       return LeftValue > RightValue;
00238   }
00239 }
00240 
00241 /// Determines if the given type is safe for constant capture in C++.
00242 static bool isSafeForCXXConstantCapture(QualType type) {
00243   const RecordType *recordType =
00244     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
00245 
00246   // Only records can be unsafe.
00247   if (!recordType) return true;
00248 
00249   const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
00250 
00251   // Maintain semantics for classes with non-trivial dtors or copy ctors.
00252   if (!record->hasTrivialDestructor()) return false;
00253   if (record->hasNonTrivialCopyConstructor()) return false;
00254 
00255   // Otherwise, we just have to make sure there aren't any mutable
00256   // fields that might have changed since initialization.
00257   return !record->hasMutableFields();
00258 }
00259 
00260 /// It is illegal to modify a const object after initialization.
00261 /// Therefore, if a const object has a constant initializer, we don't
00262 /// actually need to keep storage for it in the block; we'll just
00263 /// rematerialize it at the start of the block function.  This is
00264 /// acceptable because we make no promises about address stability of
00265 /// captured variables.
00266 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
00267                                             CodeGenFunction *CGF,
00268                                             const VarDecl *var) {
00269   QualType type = var->getType();
00270 
00271   // We can only do this if the variable is const.
00272   if (!type.isConstQualified()) return 0;
00273 
00274   // Furthermore, in C++ we have to worry about mutable fields:
00275   // C++ [dcl.type.cv]p4:
00276   //   Except that any class member declared mutable can be
00277   //   modified, any attempt to modify a const object during its
00278   //   lifetime results in undefined behavior.
00279   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
00280     return 0;
00281 
00282   // If the variable doesn't have any initializer (shouldn't this be
00283   // invalid?), it's not clear what we should do.  Maybe capture as
00284   // zero?
00285   const Expr *init = var->getInit();
00286   if (!init) return 0;
00287 
00288   return CGM.EmitConstantInit(*var, CGF);
00289 }
00290 
00291 /// Get the low bit of a nonzero character count.  This is the
00292 /// alignment of the nth byte if the 0th byte is universally aligned.
00293 static CharUnits getLowBit(CharUnits v) {
00294   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
00295 }
00296 
00297 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
00298                              SmallVectorImpl<llvm::Type*> &elementTypes) {
00299   ASTContext &C = CGM.getContext();
00300 
00301   // The header is basically a 'struct { void *; int; int; void *; void *; }'.
00302   CharUnits ptrSize, ptrAlign, intSize, intAlign;
00303   std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
00304   std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
00305 
00306   // Are there crazy embedded platforms where this isn't true?
00307   assert(intSize <= ptrSize && "layout assumptions horribly violated");
00308 
00309   CharUnits headerSize = ptrSize;
00310   if (2 * intSize < ptrAlign) headerSize += ptrSize;
00311   else headerSize += 2 * intSize;
00312   headerSize += 2 * ptrSize;
00313 
00314   info.BlockAlign = ptrAlign;
00315   info.BlockSize = headerSize;
00316 
00317   assert(elementTypes.empty());
00318   llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
00319   llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
00320   elementTypes.push_back(i8p);
00321   elementTypes.push_back(intTy);
00322   elementTypes.push_back(intTy);
00323   elementTypes.push_back(i8p);
00324   elementTypes.push_back(CGM.getBlockDescriptorType());
00325 
00326   assert(elementTypes.size() == BlockHeaderSize);
00327 }
00328 
00329 /// Compute the layout of the given block.  Attempts to lay the block
00330 /// out with minimal space requirements.
00331 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
00332                              CGBlockInfo &info) {
00333   ASTContext &C = CGM.getContext();
00334   const BlockDecl *block = info.getBlockDecl();
00335 
00336   SmallVector<llvm::Type*, 8> elementTypes;
00337   initializeForBlockHeader(CGM, info, elementTypes);
00338 
00339   if (!block->hasCaptures()) {
00340     info.StructureType =
00341       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00342     info.CanBeGlobal = true;
00343     return;
00344   }
00345   else if (C.getLangOpts().ObjC1 &&
00346            CGM.getLangOpts().getGC() == LangOptions::NonGC)
00347     info.HasCapturedVariableLayout = true;
00348   
00349   // Collect the layout chunks.
00350   SmallVector<BlockLayoutChunk, 16> layout;
00351   layout.reserve(block->capturesCXXThis() +
00352                  (block->capture_end() - block->capture_begin()));
00353 
00354   CharUnits maxFieldAlign;
00355 
00356   // First, 'this'.
00357   if (block->capturesCXXThis()) {
00358     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
00359            "Can't capture 'this' outside a method");
00360     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
00361 
00362     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
00363     std::pair<CharUnits,CharUnits> tinfo
00364       = CGM.getContext().getTypeInfoInChars(thisType);
00365     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
00366 
00367     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
00368                                       Qualifiers::OCL_None,
00369                                       0, llvmType));
00370   }
00371 
00372   // Next, all the block captures.
00373   for (const auto &CI : block->captures()) {
00374     const VarDecl *variable = CI.getVariable();
00375 
00376     if (CI.isByRef()) {
00377       // We have to copy/dispose of the __block reference.
00378       info.NeedsCopyDispose = true;
00379 
00380       // Just use void* instead of a pointer to the byref type.
00381       QualType byRefPtrTy = C.VoidPtrTy;
00382 
00383       llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
00384       std::pair<CharUnits,CharUnits> tinfo
00385         = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
00386       maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
00387 
00388       layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
00389                                         Qualifiers::OCL_None, &CI, llvmType));
00390       continue;
00391     }
00392 
00393     // Otherwise, build a layout chunk with the size and alignment of
00394     // the declaration.
00395     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
00396       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
00397       continue;
00398     }
00399 
00400     // If we have a lifetime qualifier, honor it for capture purposes.
00401     // That includes *not* copying it if it's __unsafe_unretained.
00402     Qualifiers::ObjCLifetime lifetime =
00403       variable->getType().getObjCLifetime();
00404     if (lifetime) {
00405       switch (lifetime) {
00406       case Qualifiers::OCL_None: llvm_unreachable("impossible");
00407       case Qualifiers::OCL_ExplicitNone:
00408       case Qualifiers::OCL_Autoreleasing:
00409         break;
00410 
00411       case Qualifiers::OCL_Strong:
00412       case Qualifiers::OCL_Weak:
00413         info.NeedsCopyDispose = true;
00414       }
00415 
00416     // Block pointers require copy/dispose.  So do Objective-C pointers.
00417     } else if (variable->getType()->isObjCRetainableType()) {
00418       info.NeedsCopyDispose = true;
00419       // used for mrr below.
00420       lifetime = Qualifiers::OCL_Strong;
00421 
00422     // So do types that require non-trivial copy construction.
00423     } else if (CI.hasCopyExpr()) {
00424       info.NeedsCopyDispose = true;
00425       info.HasCXXObject = true;
00426 
00427     // And so do types with destructors.
00428     } else if (CGM.getLangOpts().CPlusPlus) {
00429       if (const CXXRecordDecl *record =
00430             variable->getType()->getAsCXXRecordDecl()) {
00431         if (!record->hasTrivialDestructor()) {
00432           info.HasCXXObject = true;
00433           info.NeedsCopyDispose = true;
00434         }
00435       }
00436     }
00437 
00438     QualType VT = variable->getType();
00439     CharUnits size = C.getTypeSizeInChars(VT);
00440     CharUnits align = C.getDeclAlign(variable);
00441     
00442     maxFieldAlign = std::max(maxFieldAlign, align);
00443 
00444     llvm::Type *llvmType =
00445       CGM.getTypes().ConvertTypeForMem(VT);
00446     
00447     layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
00448   }
00449 
00450   // If that was everything, we're done here.
00451   if (layout.empty()) {
00452     info.StructureType =
00453       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00454     info.CanBeGlobal = true;
00455     return;
00456   }
00457 
00458   // Sort the layout by alignment.  We have to use a stable sort here
00459   // to get reproducible results.  There should probably be an
00460   // llvm::array_pod_stable_sort.
00461   std::stable_sort(layout.begin(), layout.end());
00462   
00463   // Needed for blocks layout info.
00464   info.BlockHeaderForcedGapOffset = info.BlockSize;
00465   info.BlockHeaderForcedGapSize = CharUnits::Zero();
00466   
00467   CharUnits &blockSize = info.BlockSize;
00468   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
00469 
00470   // Assuming that the first byte in the header is maximally aligned,
00471   // get the alignment of the first byte following the header.
00472   CharUnits endAlign = getLowBit(blockSize);
00473 
00474   // If the end of the header isn't satisfactorily aligned for the
00475   // maximum thing, look for things that are okay with the header-end
00476   // alignment, and keep appending them until we get something that's
00477   // aligned right.  This algorithm is only guaranteed optimal if
00478   // that condition is satisfied at some point; otherwise we can get
00479   // things like:
00480   //   header                 // next byte has alignment 4
00481   //   something_with_size_5; // next byte has alignment 1
00482   //   something_with_alignment_8;
00483   // which has 7 bytes of padding, as opposed to the naive solution
00484   // which might have less (?).
00485   if (endAlign < maxFieldAlign) {
00486     SmallVectorImpl<BlockLayoutChunk>::iterator
00487       li = layout.begin() + 1, le = layout.end();
00488 
00489     // Look for something that the header end is already
00490     // satisfactorily aligned for.
00491     for (; li != le && endAlign < li->Alignment; ++li)
00492       ;
00493 
00494     // If we found something that's naturally aligned for the end of
00495     // the header, keep adding things...
00496     if (li != le) {
00497       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
00498       for (; li != le; ++li) {
00499         assert(endAlign >= li->Alignment);
00500 
00501         li->setIndex(info, elementTypes.size());
00502         elementTypes.push_back(li->Type);
00503         blockSize += li->Size;
00504         endAlign = getLowBit(blockSize);
00505 
00506         // ...until we get to the alignment of the maximum field.
00507         if (endAlign >= maxFieldAlign) {
00508           if (li == first) {
00509             // No user field was appended. So, a gap was added.
00510             // Save total gap size for use in block layout bit map.
00511             info.BlockHeaderForcedGapSize = li->Size;
00512           }
00513           break;
00514         }
00515       }
00516       // Don't re-append everything we just appended.
00517       layout.erase(first, li);
00518     }
00519   }
00520 
00521   assert(endAlign == getLowBit(blockSize));
00522   
00523   // At this point, we just have to add padding if the end align still
00524   // isn't aligned right.
00525   if (endAlign < maxFieldAlign) {
00526     CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
00527     CharUnits padding = newBlockSize - blockSize;
00528 
00529     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
00530                                                 padding.getQuantity()));
00531     blockSize = newBlockSize;
00532     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
00533   }
00534 
00535   assert(endAlign >= maxFieldAlign);
00536   assert(endAlign == getLowBit(blockSize));
00537   // Slam everything else on now.  This works because they have
00538   // strictly decreasing alignment and we expect that size is always a
00539   // multiple of alignment.
00540   for (SmallVectorImpl<BlockLayoutChunk>::iterator
00541          li = layout.begin(), le = layout.end(); li != le; ++li) {
00542     assert(endAlign >= li->Alignment);
00543     li->setIndex(info, elementTypes.size());
00544     elementTypes.push_back(li->Type);
00545     blockSize += li->Size;
00546     endAlign = getLowBit(blockSize);
00547   }
00548 
00549   info.StructureType =
00550     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00551 }
00552 
00553 /// Enter the scope of a block.  This should be run at the entrance to
00554 /// a full-expression so that the block's cleanups are pushed at the
00555 /// right place in the stack.
00556 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
00557   assert(CGF.HaveInsertPoint());
00558 
00559   // Allocate the block info and place it at the head of the list.
00560   CGBlockInfo &blockInfo =
00561     *new CGBlockInfo(block, CGF.CurFn->getName());
00562   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
00563   CGF.FirstBlockInfo = &blockInfo;
00564 
00565   // Compute information about the layout, etc., of this block,
00566   // pushing cleanups as necessary.
00567   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
00568 
00569   // Nothing else to do if it can be global.
00570   if (blockInfo.CanBeGlobal) return;
00571 
00572   // Make the allocation for the block.
00573   blockInfo.Address =
00574     CGF.CreateTempAlloca(blockInfo.StructureType, "block");
00575   blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
00576 
00577   // If there are cleanups to emit, enter them (but inactive).
00578   if (!blockInfo.NeedsCopyDispose) return;
00579 
00580   // Walk through the captures (in order) and find the ones not
00581   // captured by constant.
00582   for (const auto &CI : block->captures()) {
00583     // Ignore __block captures; there's nothing special in the
00584     // on-stack block that we need to do for them.
00585     if (CI.isByRef()) continue;
00586 
00587     // Ignore variables that are constant-captured.
00588     const VarDecl *variable = CI.getVariable();
00589     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
00590     if (capture.isConstant()) continue;
00591 
00592     // Ignore objects that aren't destructed.
00593     QualType::DestructionKind dtorKind =
00594       variable->getType().isDestructedType();
00595     if (dtorKind == QualType::DK_none) continue;
00596 
00597     CodeGenFunction::Destroyer *destroyer;
00598 
00599     // Block captures count as local values and have imprecise semantics.
00600     // They also can't be arrays, so need to worry about that.
00601     if (dtorKind == QualType::DK_objc_strong_lifetime) {
00602       destroyer = CodeGenFunction::destroyARCStrongImprecise;
00603     } else {
00604       destroyer = CGF.getDestroyer(dtorKind);
00605     }
00606 
00607     // GEP down to the address.
00608     llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
00609                                                     capture.getIndex());
00610 
00611     // We can use that GEP as the dominating IP.
00612     if (!blockInfo.DominatingIP)
00613       blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
00614 
00615     CleanupKind cleanupKind = InactiveNormalCleanup;
00616     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
00617     if (useArrayEHCleanup) 
00618       cleanupKind = InactiveNormalAndEHCleanup;
00619 
00620     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
00621                     destroyer, useArrayEHCleanup);
00622 
00623     // Remember where that cleanup was.
00624     capture.setCleanup(CGF.EHStack.stable_begin());
00625   }
00626 }
00627 
00628 /// Enter a full-expression with a non-trivial number of objects to
00629 /// clean up.  This is in this file because, at the moment, the only
00630 /// kind of cleanup object is a BlockDecl*.
00631 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
00632   assert(E->getNumObjects() != 0);
00633   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
00634   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
00635          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
00636     enterBlockScope(*this, *i);
00637   }
00638 }
00639 
00640 /// Find the layout for the given block in a linked list and remove it.
00641 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
00642                                            const BlockDecl *block) {
00643   while (true) {
00644     assert(head && *head);
00645     CGBlockInfo *cur = *head;
00646 
00647     // If this is the block we're looking for, splice it out of the list.
00648     if (cur->getBlockDecl() == block) {
00649       *head = cur->NextBlockInfo;
00650       return cur;
00651     }
00652 
00653     head = &cur->NextBlockInfo;
00654   }
00655 }
00656 
00657 /// Destroy a chain of block layouts.
00658 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
00659   assert(head && "destroying an empty chain");
00660   do {
00661     CGBlockInfo *cur = head;
00662     head = cur->NextBlockInfo;
00663     delete cur;
00664   } while (head != 0);
00665 }
00666 
00667 /// Emit a block literal expression in the current function.
00668 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
00669   // If the block has no captures, we won't have a pre-computed
00670   // layout for it.
00671   if (!blockExpr->getBlockDecl()->hasCaptures()) {
00672     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
00673     computeBlockInfo(CGM, this, blockInfo);
00674     blockInfo.BlockExpression = blockExpr;
00675     return EmitBlockLiteral(blockInfo);
00676   }
00677 
00678   // Find the block info for this block and take ownership of it.
00679   std::unique_ptr<CGBlockInfo> blockInfo;
00680   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
00681                                          blockExpr->getBlockDecl()));
00682 
00683   blockInfo->BlockExpression = blockExpr;
00684   return EmitBlockLiteral(*blockInfo);
00685 }
00686 
00687 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
00688   // Using the computed layout, generate the actual block function.
00689   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
00690   llvm::Constant *blockFn
00691     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
00692                                                        LocalDeclMap,
00693                                                        isLambdaConv);
00694   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
00695 
00696   // If there is nothing to capture, we can emit this as a global block.
00697   if (blockInfo.CanBeGlobal)
00698     return buildGlobalBlock(CGM, blockInfo, blockFn);
00699 
00700   // Otherwise, we have to emit this as a local block.
00701 
00702   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
00703   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
00704 
00705   // Build the block descriptor.
00706   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
00707 
00708   llvm::AllocaInst *blockAddr = blockInfo.Address;
00709   assert(blockAddr && "block has no address!");
00710 
00711   // Compute the initial on-stack block flags.
00712   BlockFlags flags = BLOCK_HAS_SIGNATURE;
00713   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
00714   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
00715   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
00716   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
00717 
00718   // Initialize the block literal.
00719   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
00720   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
00721                       Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
00722   Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
00723                       Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
00724   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
00725                                                        "block.invoke"));
00726   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
00727                                                           "block.descriptor"));
00728 
00729   // Finally, capture all the values into the block.
00730   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
00731 
00732   // First, 'this'.
00733   if (blockDecl->capturesCXXThis()) {
00734     llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
00735                                                 blockInfo.CXXThisIndex,
00736                                                 "block.captured-this.addr");
00737     Builder.CreateStore(LoadCXXThis(), addr);
00738   }
00739 
00740   // Next, captured variables.
00741   for (const auto &CI : blockDecl->captures()) {
00742     const VarDecl *variable = CI.getVariable();
00743     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
00744 
00745     // Ignore constant captures.
00746     if (capture.isConstant()) continue;
00747 
00748     QualType type = variable->getType();
00749     CharUnits align = getContext().getDeclAlign(variable);
00750 
00751     // This will be a [[type]]*, except that a byref entry will just be
00752     // an i8**.
00753     llvm::Value *blockField =
00754       Builder.CreateStructGEP(blockAddr, capture.getIndex(),
00755                               "block.captured");
00756 
00757     // Compute the address of the thing we're going to move into the
00758     // block literal.
00759     llvm::Value *src;
00760     if (BlockInfo && CI.isNested()) {
00761       // We need to use the capture from the enclosing block.
00762       const CGBlockInfo::Capture &enclosingCapture =
00763         BlockInfo->getCapture(variable);
00764 
00765       // This is a [[type]]*, except that a byref entry wil just be an i8**.
00766       src = Builder.CreateStructGEP(LoadBlockStruct(),
00767                                     enclosingCapture.getIndex(),
00768                                     "block.capture.addr");
00769     } else if (blockDecl->isConversionFromLambda()) {
00770       // The lambda capture in a lambda's conversion-to-block-pointer is
00771       // special; we'll simply emit it directly.
00772       src = 0;
00773     } else {
00774       // Just look it up in the locals map, which will give us back a
00775       // [[type]]*.  If that doesn't work, do the more elaborate DRE
00776       // emission.
00777       src = LocalDeclMap.lookup(variable);
00778       if (!src) {
00779         DeclRefExpr declRef(const_cast<VarDecl *>(variable),
00780                             /*refersToEnclosing*/ CI.isNested(), type,
00781                             VK_LValue, SourceLocation());
00782         src = EmitDeclRefLValue(&declRef).getAddress();
00783       }
00784     }
00785 
00786     // For byrefs, we just write the pointer to the byref struct into
00787     // the block field.  There's no need to chase the forwarding
00788     // pointer at this point, since we're building something that will
00789     // live a shorter life than the stack byref anyway.
00790     if (CI.isByRef()) {
00791       // Get a void* that points to the byref struct.
00792       if (CI.isNested())
00793         src = Builder.CreateAlignedLoad(src, align.getQuantity(),
00794                                         "byref.capture");
00795       else
00796         src = Builder.CreateBitCast(src, VoidPtrTy);
00797 
00798       // Write that void* into the capture field.
00799       Builder.CreateAlignedStore(src, blockField, align.getQuantity());
00800 
00801     // If we have a copy constructor, evaluate that into the block field.
00802     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
00803       if (blockDecl->isConversionFromLambda()) {
00804         // If we have a lambda conversion, emit the expression
00805         // directly into the block instead.
00806         AggValueSlot Slot =
00807             AggValueSlot::forAddr(blockField, align, Qualifiers(),
00808                                   AggValueSlot::IsDestructed,
00809                                   AggValueSlot::DoesNotNeedGCBarriers,
00810                                   AggValueSlot::IsNotAliased);
00811         EmitAggExpr(copyExpr, Slot);
00812       } else {
00813         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
00814       }
00815 
00816     // If it's a reference variable, copy the reference into the block field.
00817     } else if (type->isReferenceType()) {
00818       llvm::Value *ref =
00819         Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
00820       Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
00821 
00822     // If this is an ARC __strong block-pointer variable, don't do a
00823     // block copy.
00824     //
00825     // TODO: this can be generalized into the normal initialization logic:
00826     // we should never need to do a block-copy when initializing a local
00827     // variable, because the local variable's lifetime should be strictly
00828     // contained within the stack block's.
00829     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
00830                type->isBlockPointerType()) {
00831       // Load the block and do a simple retain.
00832       LValue srcLV = MakeAddrLValue(src, type, align);
00833       llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
00834       value = EmitARCRetainNonBlock(value);
00835 
00836       // Do a primitive store to the block field.
00837       LValue destLV = MakeAddrLValue(blockField, type, align);
00838       EmitStoreOfScalar(value, destLV, /*init*/ true);
00839 
00840     // Otherwise, fake up a POD copy into the block field.
00841     } else {
00842       // Fake up a new variable so that EmitScalarInit doesn't think
00843       // we're referring to the variable in its own initializer.
00844       ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
00845                                             /*name*/ 0, type);
00846 
00847       // We use one of these or the other depending on whether the
00848       // reference is nested.
00849       DeclRefExpr declRef(const_cast<VarDecl*>(variable),
00850                           /*refersToEnclosing*/ CI.isNested(), type,
00851                           VK_LValue, SourceLocation());
00852 
00853       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
00854                            &declRef, VK_RValue);
00855       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
00856                      MakeAddrLValue(blockField, type, align),
00857                      /*captured by init*/ false);
00858     }
00859 
00860     // Activate the cleanup if layout pushed one.
00861     if (!CI.isByRef()) {
00862       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
00863       if (cleanup.isValid())
00864         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
00865     }
00866   }
00867 
00868   // Cast to the converted block-pointer type, which happens (somewhat
00869   // unfortunately) to be a pointer to function type.
00870   llvm::Value *result =
00871     Builder.CreateBitCast(blockAddr,
00872                           ConvertType(blockInfo.getBlockExpr()->getType()));
00873 
00874   return result;
00875 }
00876 
00877 
00878 llvm::Type *CodeGenModule::getBlockDescriptorType() {
00879   if (BlockDescriptorType)
00880     return BlockDescriptorType;
00881 
00882   llvm::Type *UnsignedLongTy =
00883     getTypes().ConvertType(getContext().UnsignedLongTy);
00884 
00885   // struct __block_descriptor {
00886   //   unsigned long reserved;
00887   //   unsigned long block_size;
00888   //
00889   //   // later, the following will be added
00890   //
00891   //   struct {
00892   //     void (*copyHelper)();
00893   //     void (*copyHelper)();
00894   //   } helpers;                // !!! optional
00895   //
00896   //   const char *signature;   // the block signature
00897   //   const char *layout;      // reserved
00898   // };
00899   BlockDescriptorType =
00900     llvm::StructType::create("struct.__block_descriptor",
00901                              UnsignedLongTy, UnsignedLongTy, NULL);
00902 
00903   // Now form a pointer to that.
00904   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
00905   return BlockDescriptorType;
00906 }
00907 
00908 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
00909   if (GenericBlockLiteralType)
00910     return GenericBlockLiteralType;
00911 
00912   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
00913 
00914   // struct __block_literal_generic {
00915   //   void *__isa;
00916   //   int __flags;
00917   //   int __reserved;
00918   //   void (*__invoke)(void *);
00919   //   struct __block_descriptor *__descriptor;
00920   // };
00921   GenericBlockLiteralType =
00922     llvm::StructType::create("struct.__block_literal_generic",
00923                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
00924                              BlockDescPtrTy, NULL);
00925 
00926   return GenericBlockLiteralType;
00927 }
00928 
00929 
00930 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E, 
00931                                           ReturnValueSlot ReturnValue) {
00932   const BlockPointerType *BPT =
00933     E->getCallee()->getType()->getAs<BlockPointerType>();
00934 
00935   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
00936 
00937   // Get a pointer to the generic block literal.
00938   llvm::Type *BlockLiteralTy =
00939     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
00940 
00941   // Bitcast the callee to a block literal.
00942   llvm::Value *BlockLiteral =
00943     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
00944 
00945   // Get the function pointer from the literal.
00946   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
00947 
00948   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
00949 
00950   // Add the block literal.
00951   CallArgList Args;
00952   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
00953 
00954   QualType FnType = BPT->getPointeeType();
00955 
00956   // And the rest of the arguments.
00957   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
00958                E->arg_begin(), E->arg_end());
00959 
00960   // Load the function.
00961   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
00962 
00963   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
00964   const CGFunctionInfo &FnInfo =
00965     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
00966 
00967   // Cast the function pointer to the right type.
00968   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
00969 
00970   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
00971   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
00972 
00973   // And call the block.
00974   return EmitCall(FnInfo, Func, ReturnValue, Args);
00975 }
00976 
00977 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
00978                                                  bool isByRef) {
00979   assert(BlockInfo && "evaluating block ref without block information?");
00980   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
00981 
00982   // Handle constant captures.
00983   if (capture.isConstant()) return LocalDeclMap[variable];
00984 
00985   llvm::Value *addr =
00986     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
00987                             "block.capture.addr");
00988 
00989   if (isByRef) {
00990     // addr should be a void** right now.  Load, then cast the result
00991     // to byref*.
00992 
00993     addr = Builder.CreateLoad(addr);
00994     llvm::PointerType *byrefPointerType
00995       = llvm::PointerType::get(BuildByRefType(variable), 0);
00996     addr = Builder.CreateBitCast(addr, byrefPointerType,
00997                                  "byref.addr");
00998 
00999     // Follow the forwarding pointer.
01000     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
01001     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
01002 
01003     // Cast back to byref* and GEP over to the actual object.
01004     addr = Builder.CreateBitCast(addr, byrefPointerType);
01005     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable), 
01006                                    variable->getNameAsString());
01007   }
01008 
01009   if (variable->getType()->isReferenceType())
01010     addr = Builder.CreateLoad(addr, "ref.tmp");
01011 
01012   return addr;
01013 }
01014 
01015 llvm::Constant *
01016 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
01017                                     const char *name) {
01018   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
01019   blockInfo.BlockExpression = blockExpr;
01020 
01021   // Compute information about the layout, etc., of this block.
01022   computeBlockInfo(*this, 0, blockInfo);
01023 
01024   // Using that metadata, generate the actual block function.
01025   llvm::Constant *blockFn;
01026   {
01027     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
01028     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
01029                                                            blockInfo,
01030                                                            LocalDeclMap,
01031                                                            false);
01032   }
01033   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
01034 
01035   return buildGlobalBlock(*this, blockInfo, blockFn);
01036 }
01037 
01038 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
01039                                         const CGBlockInfo &blockInfo,
01040                                         llvm::Constant *blockFn) {
01041   assert(blockInfo.CanBeGlobal);
01042 
01043   // Generate the constants for the block literal initializer.
01044   llvm::Constant *fields[BlockHeaderSize];
01045 
01046   // isa
01047   fields[0] = CGM.getNSConcreteGlobalBlock();
01048 
01049   // __flags
01050   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
01051   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
01052                                       
01053   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
01054 
01055   // Reserved
01056   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
01057 
01058   // Function
01059   fields[3] = blockFn;
01060 
01061   // Descriptor
01062   fields[4] = buildBlockDescriptor(CGM, blockInfo);
01063 
01064   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
01065 
01066   llvm::GlobalVariable *literal =
01067     new llvm::GlobalVariable(CGM.getModule(),
01068                              init->getType(),
01069                              /*constant*/ true,
01070                              llvm::GlobalVariable::InternalLinkage,
01071                              init,
01072                              "__block_literal_global");
01073   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
01074 
01075   // Return a constant of the appropriately-casted type.
01076   llvm::Type *requiredType =
01077     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
01078   return llvm::ConstantExpr::getBitCast(literal, requiredType);
01079 }
01080 
01081 llvm::Function *
01082 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
01083                                        const CGBlockInfo &blockInfo,
01084                                        const DeclMapTy &ldm,
01085                                        bool IsLambdaConversionToBlock) {
01086   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01087 
01088   CurGD = GD;
01089   
01090   BlockInfo = &blockInfo;
01091 
01092   // Arrange for local static and local extern declarations to appear
01093   // to be local to this function as well, in case they're directly
01094   // referenced in a block.
01095   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
01096     const VarDecl *var = dyn_cast<VarDecl>(i->first);
01097     if (var && !var->hasLocalStorage())
01098       LocalDeclMap[var] = i->second;
01099   }
01100 
01101   // Begin building the function declaration.
01102 
01103   // Build the argument list.
01104   FunctionArgList args;
01105 
01106   // The first argument is the block pointer.  Just take it as a void*
01107   // and cast it later.
01108   QualType selfTy = getContext().VoidPtrTy;
01109   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
01110 
01111   ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
01112                              SourceLocation(), II, selfTy);
01113   args.push_back(&selfDecl);
01114 
01115   // Now add the rest of the parameters.
01116   for (auto i : blockDecl->params())
01117     args.push_back(i);
01118 
01119   // Create the function declaration.
01120   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
01121   const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
01122       fnType->getReturnType(), args, fnType->getExtInfo(),
01123       fnType->isVariadic());
01124   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
01125     blockInfo.UsesStret = true;
01126 
01127   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
01128 
01129   MangleBuffer name;
01130   CGM.getBlockMangledName(GD, name, blockDecl);
01131   llvm::Function *fn =
01132     llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage, 
01133                            name.getString(), &CGM.getModule());
01134   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
01135 
01136   // Begin generating the function.
01137   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
01138                 blockDecl->getLocation(),
01139                 blockInfo.getBlockExpr()->getBody()->getLocStart());
01140 
01141   // Okay.  Undo some of what StartFunction did.
01142   
01143   // Pull the 'self' reference out of the local decl map.
01144   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
01145   LocalDeclMap.erase(&selfDecl);
01146   BlockPointer = Builder.CreateBitCast(blockAddr,
01147                                        blockInfo.StructureType->getPointerTo(),
01148                                        "block");
01149   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
01150   // won't delete the dbg.declare intrinsics for captured variables.
01151   llvm::Value *BlockPointerDbgLoc = BlockPointer;
01152   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01153     // Allocate a stack slot for it, so we can point the debugger to it
01154     llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
01155                                                 "block.addr");
01156     unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
01157     Alloca->setAlignment(Align);
01158     // Set the DebugLocation to empty, so the store is recognized as a
01159     // frame setup instruction by llvm::DwarfDebug::beginFunction().
01160     NoLocation NL(*this, Builder);
01161     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
01162     BlockPointerDbgLoc = Alloca;
01163   }
01164 
01165   // If we have a C++ 'this' reference, go ahead and force it into
01166   // existence now.
01167   if (blockDecl->capturesCXXThis()) {
01168     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
01169                                                 blockInfo.CXXThisIndex,
01170                                                 "block.captured-this");
01171     CXXThisValue = Builder.CreateLoad(addr, "this");
01172   }
01173 
01174   // Also force all the constant captures.
01175   for (const auto &CI : blockDecl->captures()) {
01176     const VarDecl *variable = CI.getVariable();
01177     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01178     if (!capture.isConstant()) continue;
01179 
01180     unsigned align = getContext().getDeclAlign(variable).getQuantity();
01181 
01182     llvm::AllocaInst *alloca =
01183       CreateMemTemp(variable->getType(), "block.captured-const");
01184     alloca->setAlignment(align);
01185 
01186     Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
01187 
01188     LocalDeclMap[variable] = alloca;
01189   }
01190 
01191   // Save a spot to insert the debug information for all the DeclRefExprs.
01192   llvm::BasicBlock *entry = Builder.GetInsertBlock();
01193   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
01194   --entry_ptr;
01195 
01196   if (IsLambdaConversionToBlock)
01197     EmitLambdaBlockInvokeBody();
01198   else {
01199     PGO.assignRegionCounters(blockDecl, fn);
01200     RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
01201     Cnt.beginRegion(Builder);
01202     EmitStmt(blockDecl->getBody());
01203     PGO.emitInstrumentationData();
01204     PGO.destroyRegionCounters();
01205   }
01206 
01207   // Remember where we were...
01208   llvm::BasicBlock *resume = Builder.GetInsertBlock();
01209 
01210   // Go back to the entry.
01211   ++entry_ptr;
01212   Builder.SetInsertPoint(entry, entry_ptr);
01213 
01214   // Emit debug information for all the DeclRefExprs.
01215   // FIXME: also for 'this'
01216   if (CGDebugInfo *DI = getDebugInfo()) {
01217     for (const auto &CI : blockDecl->captures()) {
01218       const VarDecl *variable = CI.getVariable();
01219       DI->EmitLocation(Builder, variable->getLocation());
01220 
01221       if (CGM.getCodeGenOpts().getDebugInfo()
01222             >= CodeGenOptions::LimitedDebugInfo) {
01223         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01224         if (capture.isConstant()) {
01225           DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
01226                                         Builder);
01227           continue;
01228         }
01229 
01230         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
01231                                               Builder, blockInfo);
01232       }
01233     }
01234     // Recover location if it was changed in the above loop.
01235     DI->EmitLocation(Builder,
01236                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
01237   }
01238 
01239   // And resume where we left off.
01240   if (resume == 0)
01241     Builder.ClearInsertionPoint();
01242   else
01243     Builder.SetInsertPoint(resume);
01244 
01245   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
01246 
01247   return fn;
01248 }
01249 
01250 /*
01251     notes.push_back(HelperInfo());
01252     HelperInfo &note = notes.back();
01253     note.index = capture.getIndex();
01254     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
01255     note.cxxbar_import = ci->getCopyExpr();
01256 
01257     if (ci->isByRef()) {
01258       note.flag = BLOCK_FIELD_IS_BYREF;
01259       if (type.isObjCGCWeak())
01260         note.flag |= BLOCK_FIELD_IS_WEAK;
01261     } else if (type->isBlockPointerType()) {
01262       note.flag = BLOCK_FIELD_IS_BLOCK;
01263     } else {
01264       note.flag = BLOCK_FIELD_IS_OBJECT;
01265     }
01266  */
01267 
01268 
01269 /// Generate the copy-helper function for a block closure object:
01270 ///   static void block_copy_helper(block_t *dst, block_t *src);
01271 /// The runtime will have previously initialized 'dst' by doing a
01272 /// bit-copy of 'src'.
01273 ///
01274 /// Note that this copies an entire block closure object to the heap;
01275 /// it should not be confused with a 'byref copy helper', which moves
01276 /// the contents of an individual __block variable to the heap.
01277 llvm::Constant *
01278 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
01279   ASTContext &C = getContext();
01280 
01281   FunctionArgList args;
01282   ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
01283   args.push_back(&dstDecl);
01284   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
01285   args.push_back(&srcDecl);
01286 
01287   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
01288       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
01289 
01290   // FIXME: it would be nice if these were mergeable with things with
01291   // identical semantics.
01292   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
01293 
01294   llvm::Function *Fn =
01295     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01296                            "__copy_helper_block_", &CGM.getModule());
01297 
01298   IdentifierInfo *II
01299     = &CGM.getContext().Idents.get("__copy_helper_block_");
01300 
01301   FunctionDecl *FD = FunctionDecl::Create(C,
01302                                           C.getTranslationUnitDecl(),
01303                                           SourceLocation(),
01304                                           SourceLocation(), II, C.VoidTy, 0,
01305                                           SC_Static,
01306                                           false,
01307                                           false);
01308   // Create a scope with an artificial location for the body of this function.
01309   ArtificialLocation AL(*this, Builder);
01310   StartFunction(FD, C.VoidTy, Fn, FI, args);
01311   AL.Emit();
01312 
01313   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
01314 
01315   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
01316   src = Builder.CreateLoad(src);
01317   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
01318 
01319   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
01320   dst = Builder.CreateLoad(dst);
01321   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
01322 
01323   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01324 
01325   for (const auto &CI : blockDecl->captures()) {
01326     const VarDecl *variable = CI.getVariable();
01327     QualType type = variable->getType();
01328 
01329     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01330     if (capture.isConstant()) continue;
01331 
01332     const Expr *copyExpr = CI.getCopyExpr();
01333     BlockFieldFlags flags;
01334 
01335     bool useARCWeakCopy = false;
01336     bool useARCStrongCopy = false;
01337 
01338     if (copyExpr) {
01339       assert(!CI.isByRef());
01340       // don't bother computing flags
01341 
01342     } else if (CI.isByRef()) {
01343       flags = BLOCK_FIELD_IS_BYREF;
01344       if (type.isObjCGCWeak())
01345         flags |= BLOCK_FIELD_IS_WEAK;
01346 
01347     } else if (type->isObjCRetainableType()) {
01348       flags = BLOCK_FIELD_IS_OBJECT;
01349       bool isBlockPointer = type->isBlockPointerType();
01350       if (isBlockPointer)
01351         flags = BLOCK_FIELD_IS_BLOCK;
01352 
01353       // Special rules for ARC captures:
01354       if (getLangOpts().ObjCAutoRefCount) {
01355         Qualifiers qs = type.getQualifiers();
01356 
01357         // We need to register __weak direct captures with the runtime.
01358         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
01359           useARCWeakCopy = true;
01360 
01361         // We need to retain the copied value for __strong direct captures.
01362         } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
01363           // If it's a block pointer, we have to copy the block and
01364           // assign that to the destination pointer, so we might as
01365           // well use _Block_object_assign.  Otherwise we can avoid that.
01366           if (!isBlockPointer)
01367             useARCStrongCopy = true;
01368 
01369         // Otherwise the memcpy is fine.
01370         } else {
01371           continue;
01372         }
01373 
01374       // Non-ARC captures of retainable pointers are strong and
01375       // therefore require a call to _Block_object_assign.
01376       } else {
01377         // fall through
01378       }
01379     } else {
01380       continue;
01381     }
01382 
01383     unsigned index = capture.getIndex();
01384     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
01385     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
01386 
01387     // If there's an explicit copy expression, we do that.
01388     if (copyExpr) {
01389       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
01390     } else if (useARCWeakCopy) {
01391       EmitARCCopyWeak(dstField, srcField);
01392     } else {
01393       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
01394       if (useARCStrongCopy) {
01395         // At -O0, store null into the destination field (so that the
01396         // storeStrong doesn't over-release) and then call storeStrong.
01397         // This is a workaround to not having an initStrong call.
01398         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01399           llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
01400           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
01401           Builder.CreateStore(null, dstField);
01402           EmitARCStoreStrongCall(dstField, srcValue, true);
01403 
01404         // With optimization enabled, take advantage of the fact that
01405         // the blocks runtime guarantees a memcpy of the block data, and
01406         // just emit a retain of the src field.
01407         } else {
01408           EmitARCRetainNonBlock(srcValue);
01409 
01410           // We don't need this anymore, so kill it.  It's not quite
01411           // worth the annoyance to avoid creating it in the first place.
01412           cast<llvm::Instruction>(dstField)->eraseFromParent();
01413         }
01414       } else {
01415         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
01416         llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
01417         llvm::Value *args[] = {
01418           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
01419         };
01420 
01421         bool copyCanThrow = false;
01422         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
01423           const Expr *copyExpr =
01424             CGM.getContext().getBlockVarCopyInits(variable);
01425           if (copyExpr) {
01426             copyCanThrow = true; // FIXME: reuse the noexcept logic
01427           }
01428         }
01429 
01430         if (copyCanThrow) {
01431           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
01432         } else {
01433           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
01434         }
01435       }
01436     }
01437   }
01438 
01439   FinishFunction();
01440 
01441   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
01442 }
01443 
01444 /// Generate the destroy-helper function for a block closure object:
01445 ///   static void block_destroy_helper(block_t *theBlock);
01446 ///
01447 /// Note that this destroys a heap-allocated block closure object;
01448 /// it should not be confused with a 'byref destroy helper', which
01449 /// destroys the heap-allocated contents of an individual __block
01450 /// variable.
01451 llvm::Constant *
01452 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
01453   ASTContext &C = getContext();
01454 
01455   FunctionArgList args;
01456   ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
01457   args.push_back(&srcDecl);
01458 
01459   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
01460       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
01461 
01462   // FIXME: We'd like to put these into a mergable by content, with
01463   // internal linkage.
01464   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
01465 
01466   llvm::Function *Fn =
01467     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01468                            "__destroy_helper_block_", &CGM.getModule());
01469 
01470   IdentifierInfo *II
01471     = &CGM.getContext().Idents.get("__destroy_helper_block_");
01472 
01473   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
01474                                           SourceLocation(),
01475                                           SourceLocation(), II, C.VoidTy, 0,
01476                                           SC_Static,
01477                                           false, false);
01478   // Create a scope with an artificial location for the body of this function.
01479   ArtificialLocation AL(*this, Builder);
01480   StartFunction(FD, C.VoidTy, Fn, FI, args);
01481   AL.Emit();
01482 
01483   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
01484 
01485   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
01486   src = Builder.CreateLoad(src);
01487   src = Builder.CreateBitCast(src, structPtrTy, "block");
01488 
01489   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01490 
01491   CodeGenFunction::RunCleanupsScope cleanups(*this);
01492 
01493   for (const auto &CI : blockDecl->captures()) {
01494     const VarDecl *variable = CI.getVariable();
01495     QualType type = variable->getType();
01496 
01497     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01498     if (capture.isConstant()) continue;
01499 
01500     BlockFieldFlags flags;
01501     const CXXDestructorDecl *dtor = 0;
01502 
01503     bool useARCWeakDestroy = false;
01504     bool useARCStrongDestroy = false;
01505 
01506     if (CI.isByRef()) {
01507       flags = BLOCK_FIELD_IS_BYREF;
01508       if (type.isObjCGCWeak())
01509         flags |= BLOCK_FIELD_IS_WEAK;
01510     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
01511       if (record->hasTrivialDestructor())
01512         continue;
01513       dtor = record->getDestructor();
01514     } else if (type->isObjCRetainableType()) {
01515       flags = BLOCK_FIELD_IS_OBJECT;
01516       if (type->isBlockPointerType())
01517         flags = BLOCK_FIELD_IS_BLOCK;
01518 
01519       // Special rules for ARC captures.
01520       if (getLangOpts().ObjCAutoRefCount) {
01521         Qualifiers qs = type.getQualifiers();
01522 
01523         // Don't generate special dispose logic for a captured object
01524         // unless it's __strong or __weak.
01525         if (!qs.hasStrongOrWeakObjCLifetime())
01526           continue;
01527 
01528         // Support __weak direct captures.
01529         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
01530           useARCWeakDestroy = true;
01531 
01532         // Tools really want us to use objc_storeStrong here.
01533         else
01534           useARCStrongDestroy = true;
01535       }
01536     } else {
01537       continue;
01538     }
01539 
01540     unsigned index = capture.getIndex();
01541     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
01542 
01543     // If there's an explicit copy expression, we do that.
01544     if (dtor) {
01545       PushDestructorCleanup(dtor, srcField);
01546 
01547     // If this is a __weak capture, emit the release directly.
01548     } else if (useARCWeakDestroy) {
01549       EmitARCDestroyWeak(srcField);
01550 
01551     // Destroy strong objects with a call if requested.
01552     } else if (useARCStrongDestroy) {
01553       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
01554 
01555     // Otherwise we call _Block_object_dispose.  It wouldn't be too
01556     // hard to just emit this as a cleanup if we wanted to make sure
01557     // that things were done in reverse.
01558     } else {
01559       llvm::Value *value = Builder.CreateLoad(srcField);
01560       value = Builder.CreateBitCast(value, VoidPtrTy);
01561       BuildBlockRelease(value, flags);
01562     }
01563   }
01564 
01565   cleanups.ForceCleanup();
01566 
01567   FinishFunction();
01568 
01569   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
01570 }
01571 
01572 namespace {
01573 
01574 /// Emits the copy/dispose helper functions for a __block object of id type.
01575 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
01576   BlockFieldFlags Flags;
01577 
01578 public:
01579   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
01580     : ByrefHelpers(alignment), Flags(flags) {}
01581 
01582   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01583                 llvm::Value *srcField) override {
01584     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
01585 
01586     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
01587     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
01588 
01589     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
01590 
01591     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
01592     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
01593 
01594     llvm::Value *args[] = { destField, srcValue, flagsVal };
01595     CGF.EmitNounwindRuntimeCall(fn, args);
01596   }
01597 
01598   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01599     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
01600     llvm::Value *value = CGF.Builder.CreateLoad(field);
01601 
01602     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
01603   }
01604 
01605   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01606     id.AddInteger(Flags.getBitMask());
01607   }
01608 };
01609 
01610 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
01611 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
01612 public:
01613   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01614 
01615   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01616                 llvm::Value *srcField) override {
01617     CGF.EmitARCMoveWeak(destField, srcField);
01618   }
01619 
01620   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01621     CGF.EmitARCDestroyWeak(field);
01622   }
01623 
01624   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01625     // 0 is distinguishable from all pointers and byref flags
01626     id.AddInteger(0);
01627   }
01628 };
01629 
01630 /// Emits the copy/dispose helpers for an ARC __block __strong variable
01631 /// that's not of block-pointer type.
01632 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
01633 public:
01634   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01635 
01636   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01637                 llvm::Value *srcField) override {
01638     // Do a "move" by copying the value and then zeroing out the old
01639     // variable.
01640 
01641     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
01642     value->setAlignment(Alignment.getQuantity());
01643     
01644     llvm::Value *null =
01645       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
01646 
01647     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
01648       llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
01649       store->setAlignment(Alignment.getQuantity());
01650       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
01651       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
01652       return;
01653     }
01654     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
01655     store->setAlignment(Alignment.getQuantity());
01656 
01657     store = CGF.Builder.CreateStore(null, srcField);
01658     store->setAlignment(Alignment.getQuantity());
01659   }
01660 
01661   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01662     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
01663   }
01664 
01665   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01666     // 1 is distinguishable from all pointers and byref flags
01667     id.AddInteger(1);
01668   }
01669 };
01670 
01671 /// Emits the copy/dispose helpers for an ARC __block __strong
01672 /// variable that's of block-pointer type.
01673 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
01674 public:
01675   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01676 
01677   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01678                 llvm::Value *srcField) override {
01679     // Do the copy with objc_retainBlock; that's all that
01680     // _Block_object_assign would do anyway, and we'd have to pass the
01681     // right arguments to make sure it doesn't get no-op'ed.
01682     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
01683     oldValue->setAlignment(Alignment.getQuantity());
01684 
01685     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
01686 
01687     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
01688     store->setAlignment(Alignment.getQuantity());
01689   }
01690 
01691   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01692     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
01693   }
01694 
01695   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01696     // 2 is distinguishable from all pointers and byref flags
01697     id.AddInteger(2);
01698   }
01699 };
01700 
01701 /// Emits the copy/dispose helpers for a __block variable with a
01702 /// nontrivial copy constructor or destructor.
01703 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
01704   QualType VarType;
01705   const Expr *CopyExpr;
01706 
01707 public:
01708   CXXByrefHelpers(CharUnits alignment, QualType type,
01709                   const Expr *copyExpr)
01710     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
01711 
01712   bool needsCopy() const override { return CopyExpr != 0; }
01713   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01714                 llvm::Value *srcField) override {
01715     if (!CopyExpr) return;
01716     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
01717   }
01718 
01719   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01720     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
01721     CGF.PushDestructorCleanup(VarType, field);
01722     CGF.PopCleanupBlocks(cleanupDepth);
01723   }
01724 
01725   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01726     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
01727   }
01728 };
01729 } // end anonymous namespace
01730 
01731 static llvm::Constant *
01732 generateByrefCopyHelper(CodeGenFunction &CGF,
01733                         llvm::StructType &byrefType,
01734                         unsigned valueFieldIndex,
01735                         CodeGenModule::ByrefHelpers &byrefInfo) {
01736   ASTContext &Context = CGF.getContext();
01737 
01738   QualType R = Context.VoidTy;
01739 
01740   FunctionArgList args;
01741   ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
01742   args.push_back(&dst);
01743 
01744   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
01745   args.push_back(&src);
01746 
01747   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
01748       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
01749 
01750   CodeGenTypes &Types = CGF.CGM.getTypes();
01751   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
01752 
01753   // FIXME: We'd like to put these into a mergable by content, with
01754   // internal linkage.
01755   llvm::Function *Fn =
01756     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01757                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
01758 
01759   IdentifierInfo *II
01760     = &Context.Idents.get("__Block_byref_object_copy_");
01761 
01762   FunctionDecl *FD = FunctionDecl::Create(Context,
01763                                           Context.getTranslationUnitDecl(),
01764                                           SourceLocation(),
01765                                           SourceLocation(), II, R, 0,
01766                                           SC_Static,
01767                                           false, false);
01768 
01769   CGF.StartFunction(FD, R, Fn, FI, args);
01770 
01771   if (byrefInfo.needsCopy()) {
01772     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
01773 
01774     // dst->x
01775     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
01776     destField = CGF.Builder.CreateLoad(destField);
01777     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
01778     destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
01779 
01780     // src->x
01781     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
01782     srcField = CGF.Builder.CreateLoad(srcField);
01783     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
01784     srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
01785 
01786     byrefInfo.emitCopy(CGF, destField, srcField);
01787   }  
01788 
01789   CGF.FinishFunction();
01790 
01791   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
01792 }
01793 
01794 /// Build the copy helper for a __block variable.
01795 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
01796                                             llvm::StructType &byrefType,
01797                                             unsigned byrefValueIndex,
01798                                             CodeGenModule::ByrefHelpers &info) {
01799   CodeGenFunction CGF(CGM);
01800   return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
01801 }
01802 
01803 /// Generate code for a __block variable's dispose helper.
01804 static llvm::Constant *
01805 generateByrefDisposeHelper(CodeGenFunction &CGF,
01806                            llvm::StructType &byrefType,
01807                            unsigned byrefValueIndex,
01808                            CodeGenModule::ByrefHelpers &byrefInfo) {
01809   ASTContext &Context = CGF.getContext();
01810   QualType R = Context.VoidTy;
01811 
01812   FunctionArgList args;
01813   ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
01814   args.push_back(&src);
01815 
01816   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
01817       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
01818 
01819   CodeGenTypes &Types = CGF.CGM.getTypes();
01820   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
01821 
01822   // FIXME: We'd like to put these into a mergable by content, with
01823   // internal linkage.
01824   llvm::Function *Fn =
01825     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01826                            "__Block_byref_object_dispose_",
01827                            &CGF.CGM.getModule());
01828 
01829   IdentifierInfo *II
01830     = &Context.Idents.get("__Block_byref_object_dispose_");
01831 
01832   FunctionDecl *FD = FunctionDecl::Create(Context,
01833                                           Context.getTranslationUnitDecl(),
01834                                           SourceLocation(),
01835                                           SourceLocation(), II, R, 0,
01836                                           SC_Static,
01837                                           false, false);
01838   CGF.StartFunction(FD, R, Fn, FI, args);
01839 
01840   if (byrefInfo.needsDispose()) {
01841     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
01842     V = CGF.Builder.CreateLoad(V);
01843     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
01844     V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
01845 
01846     byrefInfo.emitDispose(CGF, V);
01847   }
01848 
01849   CGF.FinishFunction();
01850 
01851   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
01852 }
01853 
01854 /// Build the dispose helper for a __block variable.
01855 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
01856                                               llvm::StructType &byrefType,
01857                                                unsigned byrefValueIndex,
01858                                             CodeGenModule::ByrefHelpers &info) {
01859   CodeGenFunction CGF(CGM);
01860   return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
01861 }
01862 
01863 /// Lazily build the copy and dispose helpers for a __block variable
01864 /// with the given information.
01865 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
01866                                                llvm::StructType &byrefTy,
01867                                                unsigned byrefValueIndex,
01868                                                T &byrefInfo) {
01869   // Increase the field's alignment to be at least pointer alignment,
01870   // since the layout of the byref struct will guarantee at least that.
01871   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
01872                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
01873 
01874   llvm::FoldingSetNodeID id;
01875   byrefInfo.Profile(id);
01876 
01877   void *insertPos;
01878   CodeGenModule::ByrefHelpers *node
01879     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
01880   if (node) return static_cast<T*>(node);
01881 
01882   byrefInfo.CopyHelper =
01883     buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
01884   byrefInfo.DisposeHelper =
01885     buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
01886 
01887   T *copy = new (CGM.getContext()) T(byrefInfo);
01888   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
01889   return copy;
01890 }
01891 
01892 /// Build the copy and dispose helpers for the given __block variable
01893 /// emission.  Places the helpers in the global cache.  Returns null
01894 /// if no helpers are required.
01895 CodeGenModule::ByrefHelpers *
01896 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
01897                                    const AutoVarEmission &emission) {
01898   const VarDecl &var = *emission.Variable;
01899   QualType type = var.getType();
01900 
01901   unsigned byrefValueIndex = getByRefValueLLVMField(&var);
01902 
01903   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
01904     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
01905     if (!copyExpr && record->hasTrivialDestructor()) return 0;
01906 
01907     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
01908     return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01909   }
01910 
01911   // Otherwise, if we don't have a retainable type, there's nothing to do.
01912   // that the runtime does extra copies.
01913   if (!type->isObjCRetainableType()) return 0;
01914 
01915   Qualifiers qs = type.getQualifiers();
01916 
01917   // If we have lifetime, that dominates.
01918   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
01919     assert(getLangOpts().ObjCAutoRefCount);
01920 
01921     switch (lifetime) {
01922     case Qualifiers::OCL_None: llvm_unreachable("impossible");
01923 
01924     // These are just bits as far as the runtime is concerned.
01925     case Qualifiers::OCL_ExplicitNone:
01926     case Qualifiers::OCL_Autoreleasing:
01927       return 0;
01928 
01929     // Tell the runtime that this is ARC __weak, called by the
01930     // byref routines.
01931     case Qualifiers::OCL_Weak: {
01932       ARCWeakByrefHelpers byrefInfo(emission.Alignment);
01933       return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01934     }
01935 
01936     // ARC __strong __block variables need to be retained.
01937     case Qualifiers::OCL_Strong:
01938       // Block pointers need to be copied, and there's no direct
01939       // transfer possible.
01940       if (type->isBlockPointerType()) {
01941         ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
01942         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01943 
01944       // Otherwise, we transfer ownership of the retain from the stack
01945       // to the heap.
01946       } else {
01947         ARCStrongByrefHelpers byrefInfo(emission.Alignment);
01948         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01949       }
01950     }
01951     llvm_unreachable("fell out of lifetime switch!");
01952   }
01953 
01954   BlockFieldFlags flags;
01955   if (type->isBlockPointerType()) {
01956     flags |= BLOCK_FIELD_IS_BLOCK;
01957   } else if (CGM.getContext().isObjCNSObjectType(type) || 
01958              type->isObjCObjectPointerType()) {
01959     flags |= BLOCK_FIELD_IS_OBJECT;
01960   } else {
01961     return 0;
01962   }
01963 
01964   if (type.isObjCGCWeak())
01965     flags |= BLOCK_FIELD_IS_WEAK;
01966 
01967   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
01968   return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01969 }
01970 
01971 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
01972   assert(ByRefValueInfo.count(VD) && "Did not find value!");
01973   
01974   return ByRefValueInfo.find(VD)->second.second;
01975 }
01976 
01977 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
01978                                                      const VarDecl *V) {
01979   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
01980   Loc = Builder.CreateLoad(Loc);
01981   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
01982                                 V->getNameAsString());
01983   return Loc;
01984 }
01985 
01986 /// BuildByRefType - This routine changes a __block variable declared as T x
01987 ///   into:
01988 ///
01989 ///      struct {
01990 ///        void *__isa;
01991 ///        void *__forwarding;
01992 ///        int32_t __flags;
01993 ///        int32_t __size;
01994 ///        void *__copy_helper;       // only if needed
01995 ///        void *__destroy_helper;    // only if needed
01996 ///        void *__byref_variable_layout;// only if needed
01997 ///        char padding[X];           // only if needed
01998 ///        T x;
01999 ///      } x
02000 ///
02001 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
02002   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
02003   if (Info.first)
02004     return Info.first;
02005   
02006   QualType Ty = D->getType();
02007 
02008   SmallVector<llvm::Type *, 8> types;
02009   
02010   llvm::StructType *ByRefType =
02011     llvm::StructType::create(getLLVMContext(),
02012                              "struct.__block_byref_" + D->getNameAsString());
02013   
02014   // void *__isa;
02015   types.push_back(Int8PtrTy);
02016   
02017   // void *__forwarding;
02018   types.push_back(llvm::PointerType::getUnqual(ByRefType));
02019   
02020   // int32_t __flags;
02021   types.push_back(Int32Ty);
02022     
02023   // int32_t __size;
02024   types.push_back(Int32Ty);
02025   // Note that this must match *exactly* the logic in buildByrefHelpers.
02026   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
02027   if (HasCopyAndDispose) {
02028     /// void *__copy_helper;
02029     types.push_back(Int8PtrTy);
02030     
02031     /// void *__destroy_helper;
02032     types.push_back(Int8PtrTy);
02033   }
02034   bool HasByrefExtendedLayout = false;
02035   Qualifiers::ObjCLifetime Lifetime;
02036   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
02037       HasByrefExtendedLayout)
02038     /// void *__byref_variable_layout;
02039     types.push_back(Int8PtrTy);
02040 
02041   bool Packed = false;
02042   CharUnits Align = getContext().getDeclAlign(D);
02043   if (Align >
02044       getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
02045     // We have to insert padding.
02046     
02047     // The struct above has 2 32-bit integers.
02048     unsigned CurrentOffsetInBytes = 4 * 2;
02049     
02050     // And either 2, 3, 4 or 5 pointers.
02051     unsigned noPointers = 2;
02052     if (HasCopyAndDispose)
02053       noPointers += 2;
02054     if (HasByrefExtendedLayout)
02055       noPointers += 1;
02056     
02057     CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
02058     
02059     // Align the offset.
02060     unsigned AlignedOffsetInBytes = 
02061       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
02062     
02063     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
02064     if (NumPaddingBytes > 0) {
02065       llvm::Type *Ty = Int8Ty;
02066       // FIXME: We need a sema error for alignment larger than the minimum of
02067       // the maximal stack alignment and the alignment of malloc on the system.
02068       if (NumPaddingBytes > 1)
02069         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
02070     
02071       types.push_back(Ty);
02072 
02073       // We want a packed struct.
02074       Packed = true;
02075     }
02076   }
02077 
02078   // T x;
02079   types.push_back(ConvertTypeForMem(Ty));
02080   
02081   ByRefType->setBody(types, Packed);
02082   
02083   Info.first = ByRefType;
02084   
02085   Info.second = types.size() - 1;
02086   
02087   return Info.first;
02088 }
02089 
02090 /// Initialize the structural components of a __block variable, i.e.
02091 /// everything but the actual object.
02092 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
02093   // Find the address of the local.
02094   llvm::Value *addr = emission.Address;
02095 
02096   // That's an alloca of the byref structure type.
02097   llvm::StructType *byrefType = cast<llvm::StructType>(
02098                  cast<llvm::PointerType>(addr->getType())->getElementType());
02099 
02100   // Build the byref helpers if necessary.  This is null if we don't need any.
02101   CodeGenModule::ByrefHelpers *helpers =
02102     buildByrefHelpers(*byrefType, emission);
02103 
02104   const VarDecl &D = *emission.Variable;
02105   QualType type = D.getType();
02106 
02107   bool HasByrefExtendedLayout;
02108   Qualifiers::ObjCLifetime ByrefLifetime;
02109   bool ByRefHasLifetime =
02110     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
02111   
02112   llvm::Value *V;
02113 
02114   // Initialize the 'isa', which is just 0 or 1.
02115   int isa = 0;
02116   if (type.isObjCGCWeak())
02117     isa = 1;
02118   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
02119   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
02120 
02121   // Store the address of the variable into its own forwarding pointer.
02122   Builder.CreateStore(addr,
02123                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
02124 
02125   // Blocks ABI:
02126   //   c) the flags field is set to either 0 if no helper functions are
02127   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
02128   BlockFlags flags;
02129   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
02130   if (ByRefHasLifetime) {
02131     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
02132       else switch (ByrefLifetime) {
02133         case Qualifiers::OCL_Strong:
02134           flags |= BLOCK_BYREF_LAYOUT_STRONG;
02135           break;
02136         case Qualifiers::OCL_Weak:
02137           flags |= BLOCK_BYREF_LAYOUT_WEAK;
02138           break;
02139         case Qualifiers::OCL_ExplicitNone:
02140           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
02141           break;
02142         case Qualifiers::OCL_None:
02143           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
02144             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
02145           break;
02146         default:
02147           break;
02148       }
02149     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
02150       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
02151       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
02152         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
02153       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
02154         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
02155         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
02156           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
02157         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
02158           printf(" BLOCK_BYREF_LAYOUT_STRONG");
02159         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
02160           printf(" BLOCK_BYREF_LAYOUT_WEAK");
02161         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
02162           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
02163         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
02164           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
02165       }
02166       printf("\n");
02167     }
02168   }
02169   
02170   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
02171                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
02172 
02173   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
02174   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
02175   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
02176 
02177   if (helpers) {
02178     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
02179     Builder.CreateStore(helpers->CopyHelper, copy_helper);
02180 
02181     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
02182     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
02183   }
02184   if (ByRefHasLifetime && HasByrefExtendedLayout) {
02185     llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
02186     llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
02187                                                          "byref.layout");
02188     // cast destination to pointer to source type.
02189     llvm::Type *DesTy = ByrefLayoutInfo->getType();
02190     DesTy = DesTy->getPointerTo();
02191     llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
02192     Builder.CreateStore(ByrefLayoutInfo, BC);
02193   }
02194 }
02195 
02196 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
02197   llvm::Value *F = CGM.getBlockObjectDispose();
02198   llvm::Value *args[] = {
02199     Builder.CreateBitCast(V, Int8PtrTy),
02200     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
02201   };
02202   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
02203 }
02204 
02205 namespace {
02206   struct CallBlockRelease : EHScopeStack::Cleanup {
02207     llvm::Value *Addr;
02208     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
02209 
02210     void Emit(CodeGenFunction &CGF, Flags flags) override {
02211       // Should we be passing FIELD_IS_WEAK here?
02212       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
02213     }
02214   };
02215 }
02216 
02217 /// Enter a cleanup to destroy a __block variable.  Note that this
02218 /// cleanup should be a no-op if the variable hasn't left the stack
02219 /// yet; if a cleanup is required for the variable itself, that needs
02220 /// to be done externally.
02221 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
02222   // We don't enter this cleanup if we're in pure-GC mode.
02223   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
02224     return;
02225 
02226   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
02227 }
02228 
02229 /// Adjust the declaration of something from the blocks API.
02230 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
02231                                          llvm::Constant *C) {
02232   if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
02233 
02234   llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
02235   if (GV->isDeclaration() &&
02236       GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
02237     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
02238 }
02239 
02240 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
02241   if (BlockObjectDispose)
02242     return BlockObjectDispose;
02243 
02244   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
02245   llvm::FunctionType *fty
02246     = llvm::FunctionType::get(VoidTy, args, false);
02247   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
02248   configureBlocksRuntimeObject(*this, BlockObjectDispose);
02249   return BlockObjectDispose;
02250 }
02251 
02252 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
02253   if (BlockObjectAssign)
02254     return BlockObjectAssign;
02255 
02256   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
02257   llvm::FunctionType *fty
02258     = llvm::FunctionType::get(VoidTy, args, false);
02259   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
02260   configureBlocksRuntimeObject(*this, BlockObjectAssign);
02261   return BlockObjectAssign;
02262 }
02263 
02264 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
02265   if (NSConcreteGlobalBlock)
02266     return NSConcreteGlobalBlock;
02267 
02268   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
02269                                                 Int8PtrTy->getPointerTo(), 0);
02270   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
02271   return NSConcreteGlobalBlock;
02272 }
02273 
02274 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
02275   if (NSConcreteStackBlock)
02276     return NSConcreteStackBlock;
02277 
02278   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
02279                                                Int8PtrTy->getPointerTo(), 0);
02280   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
02281   return NSConcreteStackBlock;  
02282 }