1acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//
3acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//                     The LLVM Compiler Infrastructure
4acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//
5acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson// This file is distributed under the University of Illinois Open Source
6acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson// License. See LICENSE.TXT for details.
7acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//
8acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//===----------------------------------------------------------------------===//
9acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//
10acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson// This contains code to emit blocks.
11acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//
12acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson//===----------------------------------------------------------------------===//
13acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
1455fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CGBlocks.h"
15b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump#include "CGDebugInfo.h"
16263c4dec5f0fda5a77ed99f3ccd456c15cb8720fFariborz Jahanian#include "CGObjCRuntime.h"
1755fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CodeGenFunction.h"
18acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson#include "CodeGenModule.h"
196cc88f78fd36d3511b89412b193494b3e423cbffMike Stump#include "clang/AST/DeclObjC.h"
206876fe615e16b0e76c7711e129e470305b7e9d41Benjamin Kramer#include "llvm/ADT/SmallSet.h"
213b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/DataLayout.h"
223b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Module.h"
23bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall#include "llvm/Support/CallSite.h"
24acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson#include <algorithm>
257d4b9fabf3778ca90aa45392a49cb9c082709929Fariborz Jahanian#include <cstdio>
26f42e4a6e089e8413247400fe58ad299193371f9cTorok Edwin
27acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlssonusing namespace clang;
28acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlssonusing namespace CodeGen;
29acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
301a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallCGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
311a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian    HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian    StructureType(0), Block(block),
346f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    DominatingIP(0) {
35ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall
361a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Skip asm prefix, if any.  'name' is usually taken directly from
371a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // the mangled name of the enclosing function.
381a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  if (!name.empty() && name[0] == '\01')
391a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    name = name.substr(1);
40ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall}
41ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall
42f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall// Anchor the vtable to this translation unit.
43f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallCodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
456b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Build the given block as a global block.
466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        const CGBlockInfo &blockInfo,
486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        llvm::Constant *blockFn);
49ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall
506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Build the helper function to copy a block.
516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                       const CGBlockInfo &blockInfo) {
536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Build the helper function to dipose of a block.
576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                          const CGBlockInfo &blockInfo) {
596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
62af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// buildBlockDescriptor is accessed from 5th field of the Block_literal
64af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// meta-data and contains stationary information about the block literal.
65af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// Its definition will have 4 (or optinally 6) words.
66af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// struct Block_descriptor {
67af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   unsigned long reserved;
68af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   unsigned long size;  // size of Block_literal metadata in bytes.
69af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   void *copy_func_helper_decl;  // optional copy helper.
70af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   void *destroy_func_decl; // optioanl destructor helper.
71af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   void *block_method_encoding_address;//@encode for block literal signature.
72af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian///   void *block_layout_info; // encoding of captured block variables.
73af879c0222791b5e026653a834df1c5c1fb41552Fariborz Jahanian/// };
746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
756b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                            const CGBlockInfo &blockInfo) {
766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  ASTContext &C = CGM.getContext();
776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
782acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
792acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
815f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Constant*, 6> elements;
82e5fee25e71266712522cff554f25c59b3078a429Mike Stump
83e5fee25e71266712522cff554f25c59b3078a429Mike Stump  // reserved
846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elements.push_back(llvm::ConstantInt::get(ulong, 0));
85e5fee25e71266712522cff554f25c59b3078a429Mike Stump
86e5fee25e71266712522cff554f25c59b3078a429Mike Stump  // Size
87d6840002c37ba25effe5eb4bb89c4ae2e1d80945Mike Stump  // FIXME: What is the right way to say this doesn't fit?  We should give
88d6840002c37ba25effe5eb4bb89c4ae2e1d80945Mike Stump  // a user diagnostic in that case.  Better fix would be to change the
89d6840002c37ba25effe5eb4bb89c4ae2e1d80945Mike Stump  // API to size_t.
906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elements.push_back(llvm::ConstantInt::get(ulong,
916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                            blockInfo.BlockSize.getQuantity()));
92e5fee25e71266712522cff554f25c59b3078a429Mike Stump
936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Optional copy/dispose helpers.
946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockInfo.NeedsCopyDispose) {
95e5fee25e71266712522cff554f25c59b3078a429Mike Stump    // copy_func_helper_decl
966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    elements.push_back(buildCopyHelper(CGM, blockInfo));
97e5fee25e71266712522cff554f25c59b3078a429Mike Stump
98e5fee25e71266712522cff554f25c59b3078a429Mike Stump    // destroy_func_decl
996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    elements.push_back(buildDisposeHelper(CGM, blockInfo));
100e5fee25e71266712522cff554f25c59b3078a429Mike Stump  }
101e5fee25e71266712522cff554f25c59b3078a429Mike Stump
1026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
1036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  std::string typeAtEncoding =
1046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
1056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elements.push_back(llvm::ConstantExpr::getBitCast(
1066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                          CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
1072a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst
1086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // GC layout.
109c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian  if (C.getLangOpts().ObjC1) {
110c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian    if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
111c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian      elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
112c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian    else
113c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian      elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
114c46b43517a18c8f41934a38a3580bd477ab54265Fariborz Jahanian  }
1156b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  else
1166b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    elements.push_back(llvm::Constant::getNullValue(i8p));
117ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
118c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
1194de9fce48e42cc7ec1345c0fd21b3dbc5b9114c8Anders Carlsson
1206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::GlobalVariable *global =
1216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
1226b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             llvm::GlobalValue::InternalLinkage,
1236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             init, "__block_descriptor_tmp");
124ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump
1256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
1264de9fce48e42cc7ec1345c0fd21b3dbc5b9114c8Anders Carlsson}
1274de9fce48e42cc7ec1345c0fd21b3dbc5b9114c8Anders Carlsson
1286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/*
1296b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  Purely notional variadic template describing the layout of a block.
1306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
1326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  struct Block_literal {
1336b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Initialized to one of:
1346b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   extern void *_NSConcreteStackBlock[];
1356b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   extern void *_NSConcreteGlobalBlock[];
1366b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///
1376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// In theory, we could start one off malloc'ed by setting
1386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
1396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// this isa:
1406b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   extern void *_NSConcreteMallocBlock[];
1416b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    struct objc_class *isa;
1426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1436b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// These are the flags (with corresponding bit number) that the
1446b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// compiler is actually supposed to know about.
1456b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
1466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   descriptor provides copy and dispose helper functions
1476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
1486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   object with a nontrivial destructor or copy constructor
1496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
1506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   as global memory
1516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  29. BLOCK_USE_STRET - indicates that the block function
1526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   uses stret, which objc_msgSend needs to know about
1536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
1546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   @encoded signature string
1556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// And we're not supposed to manipulate these:
1566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
1576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   to malloc'ed memory
1586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///  27. BLOCK_IS_GC - indicates that the block has been moved to
1596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    ///   to GC-allocated memory
1606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Additionally, the bottom 16 bits are a reference count which
1616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// should be zero on the stack.
1626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    int flags;
1636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Reserved;  should be zero-initialized.
1656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    int reserved;
1666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Function pointer generated from block literal.
1686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    _ResultType (*invoke)(Block_literal *, _ParamTypes...);
1696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Block description metadata generated from block literal.
1716b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    struct Block_descriptor *block_descriptor;
1726b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Captured values follow.
1746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    _CapturesTypes captures...;
1756b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  };
1766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall */
1776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// The number of fields in a block header.
1796b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallconst unsigned BlockHeaderSize = 5;
1806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1816b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallnamespace {
1826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  /// A chunk of data that we actually have to capture in the block.
1836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  struct BlockLayoutChunk {
1846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    CharUnits Alignment;
1856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    CharUnits Size;
18690a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    Qualifiers::ObjCLifetime Lifetime;
1876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const BlockDecl::Capture *Capture; // null for 'this'
188ef6de3da8572607f786303c07150daa6e140ab19Jay Foad    llvm::Type *Type;
1896b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    BlockLayoutChunk(CharUnits align, CharUnits size,
19190a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian                     Qualifiers::ObjCLifetime lifetime,
1926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                     const BlockDecl::Capture *capture,
193ef6de3da8572607f786303c07150daa6e140ab19Jay Foad                     llvm::Type *type)
19490a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      : Alignment(align), Size(size), Lifetime(lifetime),
19590a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian        Capture(capture), Type(type) {}
1966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    /// Tell the block info that this chunk has the given field index.
1986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    void setIndex(CGBlockInfo &info, unsigned index) {
1996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      if (!Capture)
2006b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        info.CXXThisIndex = index;
2016b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      else
2026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        info.Captures[Capture->getVariable()]
2036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall          = CGBlockInfo::Capture::makeIndex(index);
2046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
2056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  };
2064de9fce48e42cc7ec1345c0fd21b3dbc5b9114c8Anders Carlsson
20790a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian  /// Order by 1) all __strong together 2) next, all byfref together 3) next,
20890a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian  /// all __weak together. Preserve descending alignment in all situations.
2096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
21090a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    CharUnits LeftValue, RightValue;
21190a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
21290a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    bool RightByref = right.Capture ? right.Capture->isByRef() : false;
21390a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian
21490a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    if (left.Lifetime == Qualifiers::OCL_Strong &&
21590a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian        left.Alignment >= right.Alignment)
21690a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      LeftValue = CharUnits::fromQuantity(64);
21790a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else if (LeftByref && left.Alignment >= right.Alignment)
21890a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      LeftValue = CharUnits::fromQuantity(32);
21990a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else if (left.Lifetime == Qualifiers::OCL_Weak &&
22090a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian             left.Alignment >= right.Alignment)
22190a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      LeftValue = CharUnits::fromQuantity(16);
22290a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else
22390a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      LeftValue = left.Alignment;
22490a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    if (right.Lifetime == Qualifiers::OCL_Strong &&
22590a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian        right.Alignment >= left.Alignment)
22690a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      RightValue = CharUnits::fromQuantity(64);
22790a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else if (RightByref && right.Alignment >= left.Alignment)
22890a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      RightValue = CharUnits::fromQuantity(32);
22990a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else if (right.Lifetime == Qualifiers::OCL_Weak &&
23090a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian             right.Alignment >= left.Alignment)
23190a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      RightValue = CharUnits::fromQuantity(16);
23290a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    else
23390a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      RightValue = right.Alignment;
23490a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian
23590a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      return LeftValue > RightValue;
2366b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
2376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
23800470a1c4c44c5ed26bad9a38b4d3904b02d7a28Mike Stump
239461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall/// Determines if the given type is safe for constant capture in C++.
240461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCallstatic bool isSafeForCXXConstantCapture(QualType type) {
241461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  const RecordType *recordType =
242461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall    type->getBaseElementTypeUnsafe()->getAs<RecordType>();
243461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall
244461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // Only records can be unsafe.
245461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  if (!recordType) return true;
246461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall
247461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
248461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall
249461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // Maintain semantics for classes with non-trivial dtors or copy ctors.
250461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  if (!record->hasTrivialDestructor()) return false;
251426391cd51af86f9d59eceb0fb1c42153eccbb9aRichard Smith  if (record->hasNonTrivialCopyConstructor()) return false;
252461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall
253461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // Otherwise, we just have to make sure there aren't any mutable
254461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // fields that might have changed since initialization.
2552bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor  return !record->hasMutableFields();
256461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall}
257461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall
2586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// It is illegal to modify a const object after initialization.
2596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Therefore, if a const object has a constant initializer, we don't
2606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// actually need to keep storage for it in the block; we'll just
2616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// rematerialize it at the start of the block function.  This is
2626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// acceptable because we make no promises about address stability of
2636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// captured variables.
2646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
2652d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith                                            CodeGenFunction *CGF,
2666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                            const VarDecl *var) {
2676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  QualType type = var->getType();
2686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
2696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // We can only do this if the variable is const.
2706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (!type.isConstQualified()) return 0;
2716b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
272461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // Furthermore, in C++ we have to worry about mutable fields:
273461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  // C++ [dcl.type.cv]p4:
274461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  //   Except that any class member declared mutable can be
275461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  //   modified, any attempt to modify a const object during its
276461c9c1bc39ed8cbe8311f396f7ee3839e9fda53John McCall  //   lifetime results in undefined behavior.
2774e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
2786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    return 0;
2796b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
2806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // If the variable doesn't have any initializer (shouldn't this be
2816b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // invalid?), it's not clear what we should do.  Maybe capture as
2826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // zero?
2836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const Expr *init = var->getInit();
2846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (!init) return 0;
2856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
2862d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  return CGM.EmitConstantInit(*var, CGF);
2876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
2885e530af5d51572a0ed5dbe50da54bd333840c63dDavid Chisnall
2896b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Get the low bit of a nonzero character count.  This is the
2906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// alignment of the nth byte if the 0th byte is universally aligned.
2916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic CharUnits getLowBit(CharUnits v) {
2926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
2936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
2945e530af5d51572a0ed5dbe50da54bd333840c63dDavid Chisnall
2956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
2965f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                             SmallVectorImpl<llvm::Type*> &elementTypes) {
2976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  ASTContext &C = CGM.getContext();
298e5fee25e71266712522cff554f25c59b3078a429Mike Stump
2996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // The header is basically a 'struct { void *; int; int; void *; void *; }'.
3006b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CharUnits ptrSize, ptrAlign, intSize, intAlign;
3016b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
3026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
303711c52bb20d0c69063b52a99826fb7d2835501f1John McCall
3046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Are there crazy embedded platforms where this isn't true?
3056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  assert(intSize <= ptrSize && "layout assumptions horribly violated");
3065e530af5d51572a0ed5dbe50da54bd333840c63dDavid Chisnall
3076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CharUnits headerSize = ptrSize;
3086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (2 * intSize < ptrAlign) headerSize += ptrSize;
3096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  else headerSize += 2 * intSize;
3106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  headerSize += 2 * ptrSize;
31100470a1c4c44c5ed26bad9a38b4d3904b02d7a28Mike Stump
3126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  info.BlockAlign = ptrAlign;
3136b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  info.BlockSize = headerSize;
3148a2b4b1c5b960710db95e9b296d9a600aee37c00Mike Stump
3156b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  assert(elementTypes.empty());
316ef6de3da8572607f786303c07150daa6e140ab19Jay Foad  llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
317ef6de3da8572607f786303c07150daa6e140ab19Jay Foad  llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
3186b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elementTypes.push_back(i8p);
3196b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elementTypes.push_back(intTy);
3206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elementTypes.push_back(intTy);
3216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elementTypes.push_back(i8p);
3226b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  elementTypes.push_back(CGM.getBlockDescriptorType());
3238a2b4b1c5b960710db95e9b296d9a600aee37c00Mike Stump
3246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  assert(elementTypes.size() == BlockHeaderSize);
3256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
3268a2b4b1c5b960710db95e9b296d9a600aee37c00Mike Stump
3276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Compute the layout of the given block.  Attempts to lay the block
3286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// out with minimal space requirements.
3292d6a5670465cb3f1d811695a9f23e372508240d2Richard Smithstatic void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
3302d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith                             CGBlockInfo &info) {
3316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  ASTContext &C = CGM.getContext();
3326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const BlockDecl *block = info.getBlockDecl();
3330892099dbc640720400a1d9decd2733a09d733e5Mike Stump
3345f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Type*, 8> elementTypes;
3356b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  initializeForBlockHeader(CGM, info, elementTypes);
33600470a1c4c44c5ed26bad9a38b4d3904b02d7a28Mike Stump
3376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (!block->hasCaptures()) {
3386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    info.StructureType =
3396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
3406b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    info.CanBeGlobal = true;
3416b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    return;
3426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
343f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian  else if (C.getLangOpts().ObjC1 &&
344f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian           CGM.getLangOpts().getGC() == LangOptions::NonGC)
345f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian    info.HasCapturedVariableLayout = true;
346f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian
3476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Collect the layout chunks.
3485f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<BlockLayoutChunk, 16> layout;
3496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  layout.reserve(block->capturesCXXThis() +
3506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                 (block->capture_end() - block->capture_begin()));
351ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
3526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CharUnits maxFieldAlign;
353ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
3546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // First, 'this'.
3556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (block->capturesCXXThis()) {
3566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const DeclContext *DC = block->getDeclContext();
3576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
3586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      ;
3597a614d8380297fcd2bc23986241905d97222948cRichard Smith    QualType thisType;
3607a614d8380297fcd2bc23986241905d97222948cRichard Smith    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
3617a614d8380297fcd2bc23986241905d97222948cRichard Smith      thisType = C.getPointerType(C.getRecordType(RD));
3627a614d8380297fcd2bc23986241905d97222948cRichard Smith    else
3637a614d8380297fcd2bc23986241905d97222948cRichard Smith      thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
364ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
365ef6de3da8572607f786303c07150daa6e140ab19Jay Foad    llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
3666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    std::pair<CharUnits,CharUnits> tinfo
3676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      = CGM.getContext().getTypeInfoInChars(thisType);
3686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
369ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
37090a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
37190a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian                                      Qualifiers::OCL_None,
37290a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian                                      0, llvmType));
3736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
374ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
3756b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Next, all the block captures.
3766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
3776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         ce = block->capture_end(); ci != ce; ++ci) {
3786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *variable = ci->getVariable();
379ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
3806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (ci->isByRef()) {
3816b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // We have to copy/dispose of the __block reference.
3826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      info.NeedsCopyDispose = true;
3836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
3846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // Just use void* instead of a pointer to the byref type.
3856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      QualType byRefPtrTy = C.VoidPtrTy;
3866b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
387ef6de3da8572607f786303c07150daa6e140ab19Jay Foad      llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
3886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      std::pair<CharUnits,CharUnits> tinfo
3896b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
3906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
3916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
3926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
39390a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian                                        Qualifiers::OCL_None,
3946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        &*ci, llvmType));
3956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      continue;
3966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
3976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
3986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Otherwise, build a layout chunk with the size and alignment of
3996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // the declaration.
4002d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith    if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
4016b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
4026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      continue;
4036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
4046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
405f85e193739c953358c865005855253af4f68a497John McCall    // If we have a lifetime qualifier, honor it for capture purposes.
406f85e193739c953358c865005855253af4f68a497John McCall    // That includes *not* copying it if it's __unsafe_unretained.
40790a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    Qualifiers::ObjCLifetime lifetime =
40890a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      variable->getType().getObjCLifetime();
40990a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    if (lifetime) {
410f85e193739c953358c865005855253af4f68a497John McCall      switch (lifetime) {
411f85e193739c953358c865005855253af4f68a497John McCall      case Qualifiers::OCL_None: llvm_unreachable("impossible");
412f85e193739c953358c865005855253af4f68a497John McCall      case Qualifiers::OCL_ExplicitNone:
413f85e193739c953358c865005855253af4f68a497John McCall      case Qualifiers::OCL_Autoreleasing:
414f85e193739c953358c865005855253af4f68a497John McCall        break;
415f85e193739c953358c865005855253af4f68a497John McCall
416f85e193739c953358c865005855253af4f68a497John McCall      case Qualifiers::OCL_Strong:
417f85e193739c953358c865005855253af4f68a497John McCall      case Qualifiers::OCL_Weak:
418f85e193739c953358c865005855253af4f68a497John McCall        info.NeedsCopyDispose = true;
419f85e193739c953358c865005855253af4f68a497John McCall      }
4206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
421f85e193739c953358c865005855253af4f68a497John McCall    // Block pointers require copy/dispose.  So do Objective-C pointers.
422f85e193739c953358c865005855253af4f68a497John McCall    } else if (variable->getType()->isObjCRetainableType()) {
4236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      info.NeedsCopyDispose = true;
42490a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      // used for mrr below.
42590a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian      lifetime = Qualifiers::OCL_Strong;
4266b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // So do types that require non-trivial copy construction.
4286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else if (ci->hasCopyExpr()) {
4296b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      info.NeedsCopyDispose = true;
4306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      info.HasCXXObject = true;
4316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // And so do types with destructors.
4334e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    } else if (CGM.getLangOpts().CPlusPlus) {
4346b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      if (const CXXRecordDecl *record =
4356b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall            variable->getType()->getAsCXXRecordDecl()) {
4366b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        if (!record->hasTrivialDestructor()) {
4376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall          info.HasCXXObject = true;
4386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall          info.NeedsCopyDispose = true;
439ea1471e0e967548c596a71469702f8846dbaf3c0John McCall        }
440f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall      }
4416b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
4426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
443c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian    QualType VT = variable->getType();
444d8c4551fa22a9c346e6a9e56333915197c97e394Fariborz Jahanian    CharUnits size = C.getTypeSizeInChars(VT);
445c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian    CharUnits align = C.getDeclAlign(variable);
446d8c4551fa22a9c346e6a9e56333915197c97e394Fariborz Jahanian
4476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    maxFieldAlign = std::max(maxFieldAlign, align);
4486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
449ef6de3da8572607f786303c07150daa6e140ab19Jay Foad    llvm::Type *llvmType =
450d8c4551fa22a9c346e6a9e56333915197c97e394Fariborz Jahanian      CGM.getTypes().ConvertTypeForMem(VT);
451d8c4551fa22a9c346e6a9e56333915197c97e394Fariborz Jahanian
45290a2d39d3082518566d5a22409a7bbba0d42f054Fariborz Jahanian    layout.push_back(BlockLayoutChunk(align, size, lifetime, &*ci, llvmType));
4536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
454ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
4556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // If that was everything, we're done here.
4566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (layout.empty()) {
4576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    info.StructureType =
4586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
4596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    info.CanBeGlobal = true;
4606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    return;
4616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
4626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Sort the layout by alignment.  We have to use a stable sort here
4646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // to get reproducible results.  There should probably be an
4656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // llvm::array_pod_stable_sort.
4666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  std::stable_sort(layout.begin(), layout.end());
467ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian
468ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian  // Needed for blocks layout info.
469ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian  info.BlockHeaderForcedGapOffset = info.BlockSize;
470ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian  info.BlockHeaderForcedGapSize = CharUnits::Zero();
471ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian
4726b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CharUnits &blockSize = info.BlockSize;
4736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
4746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4756b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Assuming that the first byte in the header is maximally aligned,
4766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // get the alignment of the first byte following the header.
4776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CharUnits endAlign = getLowBit(blockSize);
4786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4796b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // If the end of the header isn't satisfactorily aligned for the
4806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // maximum thing, look for things that are okay with the header-end
4816b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // alignment, and keep appending them until we get something that's
4826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // aligned right.  This algorithm is only guaranteed optimal if
4836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // that condition is satisfied at some point; otherwise we can get
4846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // things like:
4856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  //   header                 // next byte has alignment 4
4866b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  //   something_with_size_5; // next byte has alignment 1
4876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  //   something_with_alignment_8;
4886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // which has 7 bytes of padding, as opposed to the naive solution
4896b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // which might have less (?).
4906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (endAlign < maxFieldAlign) {
4915f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    SmallVectorImpl<BlockLayoutChunk>::iterator
4926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      li = layout.begin() + 1, le = layout.end();
4936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Look for something that the header end is already
4956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // satisfactorily aligned for.
4966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    for (; li != le && endAlign < li->Alignment; ++li)
4976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      ;
4986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
4996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // If we found something that's naturally aligned for the end of
5006b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // the header, keep adding things...
5016b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (li != le) {
5025f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
5036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      for (; li != le; ++li) {
5046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        assert(endAlign >= li->Alignment);
5056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        li->setIndex(info, elementTypes.size());
5076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        elementTypes.push_back(li->Type);
5086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        blockSize += li->Size;
5096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        endAlign = getLowBit(blockSize);
5106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5116b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        // ...until we get to the alignment of the maximum field.
512ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian        if (endAlign >= maxFieldAlign) {
513ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian          if (li == first) {
514ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian            // No user field was appended. So, a gap was added.
515ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian            // Save total gap size for use in block layout bit map.
516ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian            info.BlockHeaderForcedGapSize = li->Size;
517ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian          }
5186b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall          break;
519ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian        }
5208a2b4b1c5b960710db95e9b296d9a600aee37c00Mike Stump      }
5216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // Don't re-append everything we just appended.
5226b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      layout.erase(first, li);
5236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
5246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
5256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5266ea4841da1390b4f76d066f25333f11f6d8c5f40John McCall  assert(endAlign == getLowBit(blockSize));
527ff685c562c8fd5dfc6effec17377fde9dad6f271Fariborz Jahanian
5286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // At this point, we just have to add padding if the end align still
5296b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // isn't aligned right.
5306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (endAlign < maxFieldAlign) {
5316ea4841da1390b4f76d066f25333f11f6d8c5f40John McCall    CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
5326ea4841da1390b4f76d066f25333f11f6d8c5f40John McCall    CharUnits padding = newBlockSize - blockSize;
5336b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5345936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall    elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
5355936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall                                                padding.getQuantity()));
5366ea4841da1390b4f76d066f25333f11f6d8c5f40John McCall    blockSize = newBlockSize;
5376c803f7f46533c69e2f8a9a882af9ae3b7fffb6fJohn McCall    endAlign = getLowBit(blockSize); // might be > maxFieldAlign
5386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
5396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5406c803f7f46533c69e2f8a9a882af9ae3b7fffb6fJohn McCall  assert(endAlign >= maxFieldAlign);
5416ea4841da1390b4f76d066f25333f11f6d8c5f40John McCall  assert(endAlign == getLowBit(blockSize));
5426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Slam everything else on now.  This works because they have
5436b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // strictly decreasing alignment and we expect that size is always a
5446b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // multiple of alignment.
5455f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (SmallVectorImpl<BlockLayoutChunk>::iterator
5466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         li = layout.begin(), le = layout.end(); li != le; ++li) {
5476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    assert(endAlign >= li->Alignment);
5486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    li->setIndex(info, elementTypes.size());
5496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    elementTypes.push_back(li->Type);
5506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    blockSize += li->Size;
5516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    endAlign = getLowBit(blockSize);
5526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
5536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  info.StructureType =
5556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
5566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
5576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
5581a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// Enter the scope of a block.  This should be run at the entrance to
5591a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// a full-expression so that the block's cleanups are pushed at the
5601a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// right place in the stack.
5611a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallstatic void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
56238baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall  assert(CGF.HaveInsertPoint());
56338baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall
5641a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Allocate the block info and place it at the head of the list.
5651a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  CGBlockInfo &blockInfo =
5661a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    *new CGBlockInfo(block, CGF.CurFn->getName());
5671a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
5681a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  CGF.FirstBlockInfo = &blockInfo;
5691a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5701a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Compute information about the layout, etc., of this block,
5711a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // pushing cleanups as necessary.
5722d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  computeBlockInfo(CGF.CGM, &CGF, blockInfo);
5731a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5741a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Nothing else to do if it can be global.
5751a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  if (blockInfo.CanBeGlobal) return;
5761a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5771a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Make the allocation for the block.
5781a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo.Address =
5791a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGF.CreateTempAlloca(blockInfo.StructureType, "block");
5801a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
5811a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5821a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // If there are cleanups to emit, enter them (but inactive).
5831a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  if (!blockInfo.NeedsCopyDispose) return;
5841a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5851a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Walk through the captures (in order) and find the ones not
5861a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // captured by constant.
5871a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5881a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall         ce = block->capture_end(); ci != ce; ++ci) {
5891a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Ignore __block captures; there's nothing special in the
5901a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // on-stack block that we need to do for them.
5911a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (ci->isByRef()) continue;
5921a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5931a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Ignore variables that are constant-captured.
5941a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    const VarDecl *variable = ci->getVariable();
5951a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
5961a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (capture.isConstant()) continue;
5971a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
5981a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Ignore objects that aren't destructed.
5991a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    QualType::DestructionKind dtorKind =
6001a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      variable->getType().isDestructedType();
6011a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (dtorKind == QualType::DK_none) continue;
6021a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6031a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CodeGenFunction::Destroyer *destroyer;
6041a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6051a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Block captures count as local values and have imprecise semantics.
6061a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // They also can't be arrays, so need to worry about that.
6071a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (dtorKind == QualType::DK_objc_strong_lifetime) {
608516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne      destroyer = CodeGenFunction::destroyARCStrongImprecise;
6091a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    } else {
610516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne      destroyer = CGF.getDestroyer(dtorKind);
6111a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    }
6121a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6131a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // GEP down to the address.
6141a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
6151a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall                                                    capture.getIndex());
6161a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6176f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    // We can use that GEP as the dominating IP.
6186f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    if (!blockInfo.DominatingIP)
6196f103ba42cb69d50005a977c5ea583984ab63fc4John McCall      blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
6206f103ba42cb69d50005a977c5ea583984ab63fc4John McCall
6211a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CleanupKind cleanupKind = InactiveNormalCleanup;
6221a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
6231a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (useArrayEHCleanup)
6241a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      cleanupKind = InactiveNormalAndEHCleanup;
6251a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6261a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                    destroyer, useArrayEHCleanup);
6281a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6291a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Remember where that cleanup was.
6301a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    capture.setCleanup(CGF.EHStack.stable_begin());
6311a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  }
6321a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall}
6331a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6341a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// Enter a full-expression with a non-trivial number of objects to
6351a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// clean up.  This is in this file because, at the moment, the only
6361a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// kind of cleanup object is a BlockDecl*.
6371a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallvoid CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
6381a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  assert(E->getNumObjects() != 0);
6391a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
6401a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
6411a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall         i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
6421a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    enterBlockScope(*this, *i);
6431a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  }
6441a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall}
6451a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6461a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// Find the layout for the given block in a linked list and remove it.
6471a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallstatic CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
6481a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall                                           const BlockDecl *block) {
6491a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  while (true) {
6501a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    assert(head && *head);
6511a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGBlockInfo *cur = *head;
6521a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6531a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // If this is the block we're looking for, splice it out of the list.
6541a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    if (cur->getBlockDecl() == block) {
6551a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      *head = cur->NextBlockInfo;
6561a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      return cur;
6571a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    }
6581a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6591a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    head = &cur->NextBlockInfo;
6601a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  }
6611a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall}
6621a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6631a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall/// Destroy a chain of block layouts.
6641a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallvoid CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
6651a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  assert(head && "destroying an empty chain");
6661a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  do {
6671a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGBlockInfo *cur = head;
6681a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    head = cur->NextBlockInfo;
6691a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    delete cur;
6701a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  } while (head != 0);
6711a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall}
6721a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/// Emit a block literal expression in the current function.
6746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallllvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
6751a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // If the block has no captures, we won't have a pre-computed
6761a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // layout for it.
6771a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  if (!blockExpr->getBlockDecl()->hasCaptures()) {
6781a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
6792d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith    computeBlockInfo(CGM, this, blockInfo);
6801a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    blockInfo.BlockExpression = blockExpr;
6811a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    return EmitBlockLiteral(blockInfo);
6821a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  }
6836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
6841a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Find the block info for this block and take ownership of it.
6856f42b62b6194f53bcbc349f5d17388e1936535d7Dylan Noblesmith  OwningPtr<CGBlockInfo> blockInfo;
6861a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
6871a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall                                         blockExpr->getBlockDecl()));
6886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
6891a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo->BlockExpression = blockExpr;
6901a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  return EmitBlockLiteral(*blockInfo);
6911a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall}
6921a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall
6931a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCallllvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
6941a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  // Using the computed layout, generate the actual block function.
69523f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman  bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
6966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Constant *blockFn
6974904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
69864bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman                                                 CurFuncDecl, LocalDeclMap,
69923f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman                                                 isLambdaConv);
7005936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
7016b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // If there is nothing to capture, we can emit this as a global block.
7036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockInfo.CanBeGlobal)
7046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    return buildGlobalBlock(CGM, blockInfo, blockFn);
7056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Otherwise, we have to emit this as a local block.
7076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Constant *isa = CGM.getNSConcreteStackBlock();
7095936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
7106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7116b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Build the block descriptor.
7126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
7136b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7141a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  llvm::AllocaInst *blockAddr = blockInfo.Address;
7151a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  assert(blockAddr && "block has no address!");
7166b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7176b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Compute the initial on-stack block flags.
718d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  BlockFlags flags = BLOCK_HAS_SIGNATURE;
719f22ae6512dec60d9e526fe55b988f8d42ced5b57Fariborz Jahanian  if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
7206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
7216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
72264cd2328ef55735c910d3d51dd40eafc38d7a504John McCall  if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
7236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Initialize the block literal.
7256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
7261a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
7276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                      Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
7281a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
7296b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                      Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
7306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
7316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                       "block.invoke"));
7326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
7336b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                          "block.descriptor"));
7346b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7356b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Finally, capture all the values into the block.
7366b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
7376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // First, 'this'.
7396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockDecl->capturesCXXThis()) {
7406b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
7416b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                blockInfo.CXXThisIndex,
7426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                "block.captured-this.addr");
7436b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    Builder.CreateStore(LoadCXXThis(), addr);
7446b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
7456b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Next, captured variables.
7476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
7486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         ce = blockDecl->capture_end(); ci != ce; ++ci) {
7496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *variable = ci->getVariable();
7506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
7516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Ignore constant captures.
7536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (capture.isConstant()) continue;
7546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    QualType type = variable->getType();
7566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // This will be a [[type]]*, except that a byref entry will just be
7586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // an i8**.
7596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::Value *blockField =
7606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      Builder.CreateStructGEP(blockAddr, capture.getIndex(),
7616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                              "block.captured");
7626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Compute the address of the thing we're going to move into the
7646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // block literal.
7656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::Value *src;
76629a93f810ae5277446f610e8b6cdf0985febb989Douglas Gregor    if (BlockInfo && ci->isNested()) {
7676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // We need to use the capture from the enclosing block.
7686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      const CGBlockInfo::Capture &enclosingCapture =
7696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        BlockInfo->getCapture(variable);
7706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7716b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // This is a [[type]]*, except that a byref entry wil just be an i8**.
7726b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      src = Builder.CreateStructGEP(LoadBlockStruct(),
7736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                    enclosingCapture.getIndex(),
7746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                    "block.capture.addr");
77523f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman    } else if (blockDecl->isConversionFromLambda()) {
77664bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman      // The lambda capture in a lambda's conversion-to-block-pointer is
77723f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman      // special; we'll simply emit it directly.
77823f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman      src = 0;
7796b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else {
7800353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      // Just look it up in the locals map, which will give us back a
7810353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      // [[type]]*.  If that doesn't work, do the more elaborate DRE
7820353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      // emission.
7830353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      src = LocalDeclMap.lookup(variable);
7840353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      if (!src) {
7850353a7b2df9dc36784f9ec354c266f9c603053e1John McCall        DeclRefExpr declRef(const_cast<VarDecl*>(variable),
7860353a7b2df9dc36784f9ec354c266f9c603053e1John McCall                            /*refersToEnclosing*/ ci->isNested(), type,
7870353a7b2df9dc36784f9ec354c266f9c603053e1John McCall                            VK_LValue, SourceLocation());
7880353a7b2df9dc36784f9ec354c266f9c603053e1John McCall        src = EmitDeclRefLValue(&declRef).getAddress();
7890353a7b2df9dc36784f9ec354c266f9c603053e1John McCall      }
7906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
7916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
7926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // For byrefs, we just write the pointer to the byref struct into
7936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // the block field.  There's no need to chase the forwarding
7946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // pointer at this point, since we're building something that will
7956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // live a shorter life than the stack byref anyway.
7966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (ci->isByRef()) {
7975936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      // Get a void* that points to the byref struct.
7986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      if (ci->isNested())
7996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        src = Builder.CreateLoad(src, "byref.capture");
800ea1471e0e967548c596a71469702f8846dbaf3c0John McCall      else
8015936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall        src = Builder.CreateBitCast(src, VoidPtrTy);
8026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
8035936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      // Write that void* into the capture field.
8046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      Builder.CreateStore(src, blockField);
8056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
8066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // If we have a copy constructor, evaluate that into the block field.
8076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else if (const Expr *copyExpr = ci->getCopyExpr()) {
80823f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman      if (blockDecl->isConversionFromLambda()) {
80923f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        // If we have a lambda conversion, emit the expression
81023f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        // directly into the block instead.
81123f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        CharUnits Align = getContext().getTypeAlignInChars(type);
81223f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        AggValueSlot Slot =
81323f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman            AggValueSlot::forAddr(blockField, Align, Qualifiers(),
81423f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman                                  AggValueSlot::IsDestructed,
81523f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman                                  AggValueSlot::DoesNotNeedGCBarriers,
816649b4a1a9b5e6f768ca0cb84bd97b00f51083e15Chad Rosier                                  AggValueSlot::IsNotAliased);
81723f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        EmitAggExpr(copyExpr, Slot);
81823f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman      } else {
81923f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman        EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
82023f0267e2d56c0407f12e62df3561ecf75d74e6eEli Friedman      }
8216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
8226b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // If it's a reference variable, copy the reference into the block field.
823c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian    } else if (type->isReferenceType()) {
8246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
8256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
8266b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Otherwise, fake up a POD copy into the block field.
8276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else {
828f85e193739c953358c865005855253af4f68a497John McCall      // Fake up a new variable so that EmitScalarInit doesn't think
829f85e193739c953358c865005855253af4f68a497John McCall      // we're referring to the variable in its own initializer.
830f85e193739c953358c865005855253af4f68a497John McCall      ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
831c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian                                            /*name*/ 0, type);
832f85e193739c953358c865005855253af4f68a497John McCall
833bb699b07426be017056c2c549ac3ffb488cab6e3John McCall      // We use one of these or the other depending on whether the
834bb699b07426be017056c2c549ac3ffb488cab6e3John McCall      // reference is nested.
835f4b88a45902af1802a1cb42ba48b1c474474f228John McCall      DeclRefExpr declRef(const_cast<VarDecl*>(variable),
836f4b88a45902af1802a1cb42ba48b1c474474f228John McCall                          /*refersToEnclosing*/ ci->isNested(), type,
837f4b88a45902af1802a1cb42ba48b1c474474f228John McCall                          VK_LValue, SourceLocation());
838bb699b07426be017056c2c549ac3ffb488cab6e3John McCall
839c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian      ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
840f4b88a45902af1802a1cb42ba48b1c474474f228John McCall                           &declRef, VK_RValue);
841a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      EmitExprAsInit(&l2r, &blockFieldPseudoVar,
842c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian                     MakeAddrLValue(blockField, type,
8436da2c716017d5c8530ec99779524491ebc5dadb8Eli Friedman                                    getContext().getDeclAlign(variable)),
844df045200e0220f10bf03de05ca878949e0c40a5aJohn McCall                     /*captured by init*/ false);
845ea1471e0e967548c596a71469702f8846dbaf3c0John McCall    }
8466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
8471a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    // Activate the cleanup if layout pushed one.
848f85e193739c953358c865005855253af4f68a497John McCall    if (!ci->isByRef()) {
8491a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      EHScopeStack::stable_iterator cleanup = capture.getCleanup();
8501a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall      if (cleanup.isValid())
8516f103ba42cb69d50005a977c5ea583984ab63fc4John McCall        ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
852f85e193739c953358c865005855253af4f68a497John McCall    }
853e5fee25e71266712522cff554f25c59b3078a429Mike Stump  }
85400470a1c4c44c5ed26bad9a38b4d3904b02d7a28Mike Stump
8556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Cast to the converted block-pointer type, which happens (somewhat
8566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // unfortunately) to be a pointer to function type.
8576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Value *result =
8586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    Builder.CreateBitCast(blockAddr,
8596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                          ConvertType(blockInfo.getBlockExpr()->getType()));
860711c52bb20d0c69063b52a99826fb7d2835501f1John McCall
8616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return result;
862e5fee25e71266712522cff554f25c59b3078a429Mike Stump}
863e5fee25e71266712522cff554f25c59b3078a429Mike Stump
864e5fee25e71266712522cff554f25c59b3078a429Mike Stump
8659cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattnerllvm::Type *CodeGenModule::getBlockDescriptorType() {
866ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  if (BlockDescriptorType)
867ab695143861b520f5c9f8f982534a71d355396f1Mike Stump    return BlockDescriptorType;
868ab695143861b520f5c9f8f982534a71d355396f1Mike Stump
8699cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *UnsignedLongTy =
870ab695143861b520f5c9f8f982534a71d355396f1Mike Stump    getTypes().ConvertType(getContext().UnsignedLongTy);
871a5448544eea6663f8dce30a50343ef5125559794Mike Stump
872ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  // struct __block_descriptor {
873ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  //   unsigned long reserved;
874ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  //   unsigned long block_size;
8752a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //
8762a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //   // later, the following will be added
8772a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //
8782a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //   struct {
8792a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //     void (*copyHelper)();
8802a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //     void (*copyHelper)();
8812a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //   } helpers;                // !!! optional
8822a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //
8832a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //   const char *signature;   // the block signature
8842a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst  //   const char *layout;      // reserved
885ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  // };
8867650d95a1a616ea300f37126a8dfc93dc19a662aChris Lattner  BlockDescriptorType =
887c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner    llvm::StructType::create("struct.__block_descriptor",
888c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner                             UnsignedLongTy, UnsignedLongTy, NULL);
889ab695143861b520f5c9f8f982534a71d355396f1Mike Stump
8906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Now form a pointer to that.
8916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
892ab695143861b520f5c9f8f982534a71d355396f1Mike Stump  return BlockDescriptorType;
893acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson}
894acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
8959cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattnerllvm::Type *CodeGenModule::getGenericBlockLiteralType() {
8969b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump  if (GenericBlockLiteralType)
8979b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump    return GenericBlockLiteralType;
8989b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump
8999cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
900a5448544eea6663f8dce30a50343ef5125559794Mike Stump
9019b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump  // struct __block_literal_generic {
902bd65cac8de63d108a681035782a71d42954b03abMike Stump  //   void *__isa;
903bd65cac8de63d108a681035782a71d42954b03abMike Stump  //   int __flags;
904bd65cac8de63d108a681035782a71d42954b03abMike Stump  //   int __reserved;
905bd65cac8de63d108a681035782a71d42954b03abMike Stump  //   void (*__invoke)(void *);
906bd65cac8de63d108a681035782a71d42954b03abMike Stump  //   struct __block_descriptor *__descriptor;
9079b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump  // };
9089cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  GenericBlockLiteralType =
909c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner    llvm::StructType::create("struct.__block_literal_generic",
910c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner                             VoidPtrTy, IntTy, IntTy, VoidPtrTy,
911c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner                             BlockDescPtrTy, NULL);
912a5448544eea6663f8dce30a50343ef5125559794Mike Stump
9139b8a7977109604d573b49d517e98badbbb9d5ac7Mike Stump  return GenericBlockLiteralType;
914acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson}
915acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
916bd65cac8de63d108a681035782a71d42954b03abMike Stump
917a1736c0c750d4514a5d8fda36670addf1e4de54aAnders CarlssonRValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
918a1736c0c750d4514a5d8fda36670addf1e4de54aAnders Carlsson                                          ReturnValueSlot ReturnValue) {
919a5448544eea6663f8dce30a50343ef5125559794Mike Stump  const BlockPointerType *BPT =
9206217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    E->getCallee()->getType()->getAs<BlockPointerType>();
921a5448544eea6663f8dce30a50343ef5125559794Mike Stump
922acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
923acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
924acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // Get a pointer to the generic block literal.
9252acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *BlockLiteralTy =
92696e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
927acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
928acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // Bitcast the callee to a block literal.
929a5448544eea6663f8dce30a50343ef5125559794Mike Stump  llvm::Value *BlockLiteral =
930acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson    Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
931acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
932acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // Get the function pointer from the literal.
933578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer  llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
934acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson
935578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer  BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
936a5448544eea6663f8dce30a50343ef5125559794Mike Stump
937acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // Add the block literal.
938acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  CallArgList Args;
9390774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
940a5448544eea6663f8dce30a50343ef5125559794Mike Stump
941782f397c1459ef7d8b910c0fb6b95c5f1c19c14fAnders Carlsson  QualType FnType = BPT->getPointeeType();
942782f397c1459ef7d8b910c0fb6b95c5f1c19c14fAnders Carlsson
943acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // And the rest of the arguments.
944183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall  EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
945782f397c1459ef7d8b910c0fb6b95c5f1c19c14fAnders Carlsson               E->arg_begin(), E->arg_end());
946a5448544eea6663f8dce30a50343ef5125559794Mike Stump
9476e460ff03f984d34d6f3ba7f191380b823b6062fAnders Carlsson  // Load the function.
948578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer  llvm::Value *Func = Builder.CreateLoad(FuncPtr);
9496e460ff03f984d34d6f3ba7f191380b823b6062fAnders Carlsson
95064cd2328ef55735c910d3d51dd40eafc38d7a504John McCall  const FunctionType *FuncTy = FnType->castAs<FunctionType>();
951de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const CGFunctionInfo &FnInfo =
952e56bb36e8eea89bae7dfe6eb6ea0455af126bf4aJohn McCall    CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
9531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9546e460ff03f984d34d6f3ba7f191380b823b6062fAnders Carlsson  // Cast the function pointer to the right type.
955de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
9561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9572acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
9586e460ff03f984d34d6f3ba7f191380b823b6062fAnders Carlsson  Func = Builder.CreateBitCast(Func, BlockFTyPtr);
9591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
960acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson  // And call the block.
961a1736c0c750d4514a5d8fda36670addf1e4de54aAnders Carlsson  return EmitCall(FnInfo, Func, ReturnValue, Args);
962acfde805d644bc71dfeac54ddbc9f12cdae0bb02Anders Carlsson}
963d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson
9646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallllvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
9656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                 bool isByRef) {
9666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  assert(BlockInfo && "evaluating block ref without block information?");
9676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
968ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
9696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Handle constant captures.
9706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (capture.isConstant()) return LocalDeclMap[variable];
971ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
9726b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Value *addr =
9736b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
9746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                            "block.capture.addr");
975ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
9766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (isByRef) {
9776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // addr should be a void** right now.  Load, then cast the result
9786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // to byref*.
979dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump
9806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateLoad(addr);
9812acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::PointerType *byrefPointerType
9826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      = llvm::PointerType::get(BuildByRefType(variable), 0);
9836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateBitCast(addr, byrefPointerType,
9846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                 "byref.addr");
985ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump
9866b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Follow the forwarding pointer.
9876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
9886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
989ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
9906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Cast back to byref* and GEP over to the actual object.
9916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateBitCast(addr, byrefPointerType);
9926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
9936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                   variable->getNameAsString());
994ea1471e0e967548c596a71469702f8846dbaf3c0John McCall  }
995ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump
996c637d738897b1745af3bad7fc551f26b98da838cFariborz Jahanian  if (variable->getType()->isReferenceType())
9976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    addr = Builder.CreateLoad(addr, "ref.tmp");
998ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump
9996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return addr;
1000dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump}
1001dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump
100267a6448a8d52ae46d1cba4e474f9f6b3968d2ff9Mike Stumpllvm::Constant *
1003d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCallCodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
10045936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall                                    const char *name) {
10051a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
10061a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  blockInfo.BlockExpression = blockExpr;
1007a5448544eea6663f8dce30a50343ef5125559794Mike Stump
10086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Compute information about the layout, etc., of this block.
10092d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  computeBlockInfo(*this, 0, blockInfo);
10102a7eb28397148079cbc8e54e8a3871ef01c4f4bcBlaine Garst
10116b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Using that metadata, generate the actual block function.
10126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Constant *blockFn;
10136b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  {
10146b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1015d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1016d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall                                                           blockInfo,
101764bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman                                                           0, LocalDeclMap,
101864bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman                                                           false);
10196b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
10205936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1021a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1022d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  return buildGlobalBlock(*this, blockInfo, blockFn);
10236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall}
10245e530af5d51572a0ed5dbe50da54bd333840c63dDavid Chisnall
10256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallstatic llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
10266b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        const CGBlockInfo &blockInfo,
10276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        llvm::Constant *blockFn) {
10286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  assert(blockInfo.CanBeGlobal);
1029a5448544eea6663f8dce30a50343ef5125559794Mike Stump
10306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Generate the constants for the block literal initializer.
10316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Constant *fields[BlockHeaderSize];
1032a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1033d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson  // isa
10346b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  fields[0] = CGM.getNSConcreteGlobalBlock();
1035a5448544eea6663f8dce30a50343ef5125559794Mike Stump
10367edddb896e10d7ab494927842f7402583d9fa02dFariborz Jahanian  // __flags
103764cd2328ef55735c910d3d51dd40eafc38d7a504John McCall  BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
103864cd2328ef55735c910d3d51dd40eafc38d7a504John McCall  if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
103964cd2328ef55735c910d3d51dd40eafc38d7a504John McCall
10405936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1041a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1042d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson  // Reserved
10435936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1044a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1045d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson  // Function
10466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  fields[3] = blockFn;
1047a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1048d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson  // Descriptor
10496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  fields[4] = buildBlockDescriptor(CGM, blockInfo);
1050a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1051c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1052d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson
10536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::GlobalVariable *literal =
10546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    new llvm::GlobalVariable(CGM.getModule(),
10556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             init->getType(),
10566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             /*constant*/ true,
10576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             llvm::GlobalVariable::InternalLinkage,
10586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             init,
10596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                             "__block_literal_global");
10606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  literal->setAlignment(blockInfo.BlockAlign.getQuantity());
10616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
10626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Return a constant of the appropriately-casted type.
10632acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *requiredType =
10646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
10656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return llvm::ConstantExpr::getBitCast(literal, requiredType);
10664e7a1f7682d94811bd41fca8aefccc38f686db23Mike Stump}
10674e7a1f7682d94811bd41fca8aefccc38f686db23Mike Stump
106800470a1c4c44c5ed26bad9a38b4d3904b02d7a28Mike Stumpllvm::Function *
10696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallCodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
10706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                       const CGBlockInfo &blockInfo,
10716b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                       const Decl *outerFnDecl,
107264bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman                                       const DeclMapTy &ldm,
107364bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman                                       bool IsLambdaConversionToBlock) {
10746b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1075963dfbde17a28bc88ee1647bc85fd8407bfc9555Devang Patel
10766d1155be2aca28659a47fbe612222845811ff2a3Devang Patel  // Check if we should generate debug info for this block function.
1077a240df2ec1b374b3e9e7f760875ffb17cd64506fAlexey Samsonov  maybeInitializeDebugInfo();
10784904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian  CurGD = GD;
10794904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian
10806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  BlockInfo = &blockInfo;
10811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10827f28a9c37e67ae16396042ad9c085830969daf29Mike Stump  // Arrange for local static and local extern declarations to appear
10836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // to be local to this function as well, in case they're directly
10846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // referenced in a block.
10856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
10866b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *var = dyn_cast<VarDecl>(i->first);
10876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (var && !var->hasLocalStorage())
10886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      LocalDeclMap[var] = i->second;
10897f28a9c37e67ae16396042ad9c085830969daf29Mike Stump  }
10907f28a9c37e67ae16396042ad9c085830969daf29Mike Stump
10916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Begin building the function declaration.
1092a5448544eea6663f8dce30a50343ef5125559794Mike Stump
10936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Build the argument list.
10946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FunctionArgList args;
1095d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson
10966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // The first argument is the block pointer.  Just take it as a void*
10976b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // and cast it later.
10986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  QualType selfTy = getContext().VoidPtrTy;
1099ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump  IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1100ea26cb522e88fc86b0d1cae61dcefcfe4cc20231Mike Stump
11018178df3b39ab923ff5d24538812628abee33df79John McCall  ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
11028178df3b39ab923ff5d24538812628abee33df79John McCall                             SourceLocation(), II, selfTy);
1103d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&selfDecl);
11046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Now add the rest of the parameters.
11066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
11076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall       e = blockDecl->param_end(); i != e; ++i)
1108d26bc76c98006609002d9930f8840490e88ac5b5John McCall    args.push_back(*i);
11096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Create the function declaration.
1111de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
11126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const CGFunctionInfo &fnInfo =
1113de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1114de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              fnType->getExtInfo(),
1115de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              fnType->isVariadic());
111664cd2328ef55735c910d3d51dd40eafc38d7a504John McCall  if (CGM.ReturnTypeUsesSRet(fnInfo))
111764cd2328ef55735c910d3d51dd40eafc38d7a504John McCall    blockInfo.UsesStret = true;
111864cd2328ef55735c910d3d51dd40eafc38d7a504John McCall
1119de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
11206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  MangleBuffer name;
11226b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CGM.getBlockMangledName(GD, name, blockDecl);
11236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  llvm::Function *fn =
11246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
11256b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                           name.getString(), &CGM.getModule());
11266b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
11276b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Begin generating the function.
1129d26bc76c98006609002d9930f8840490e88ac5b5John McCall  StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
11303f4cb252832cf14f72d66ed707316d3759c8a689Devang Patel                blockInfo.getBlockExpr()->getBody()->getLocStart());
11316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
11326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11338178df3b39ab923ff5d24538812628abee33df79John McCall  // Okay.  Undo some of what StartFunction did.
11348178df3b39ab923ff5d24538812628abee33df79John McCall
11358178df3b39ab923ff5d24538812628abee33df79John McCall  // Pull the 'self' reference out of the local decl map.
11368178df3b39ab923ff5d24538812628abee33df79John McCall  llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
11378178df3b39ab923ff5d24538812628abee33df79John McCall  LocalDeclMap.erase(&selfDecl);
11386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  BlockPointer = Builder.CreateBitCast(blockAddr,
11396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                       blockInfo.StructureType->getPointerTo(),
11406b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                       "block");
1141a5448544eea6663f8dce30a50343ef5125559794Mike Stump
11426b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // If we have a C++ 'this' reference, go ahead and force it into
11436b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // existence now.
11446b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (blockDecl->capturesCXXThis()) {
11456b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
11466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                blockInfo.CXXThisIndex,
11476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                "block.captured-this");
11486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    CXXThisValue = Builder.CreateLoad(addr, "this");
11496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
1150a5448544eea6663f8dce30a50343ef5125559794Mike Stump
11516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
11526b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // appease it.
11536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  if (const ObjCMethodDecl *method
11546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
11556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *self = method->getSelfDecl();
11566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
11576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // There might not be a capture for 'self', but if there is...
11586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (blockInfo.Captures.count(self)) {
11596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1160836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl
11616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
11626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                      capture.getIndex(),
11636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                                      "block.captured-self");
1164836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl
1165836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      // At -O0 we generate an explicit alloca for self to facilitate debugging.
1166836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1167836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl	llvm::Value *load = Builder.CreateLoad(selfAddr);
1168836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl
1169836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl	// Allocate a stack slot for it, so we can generate debug info for it
1170836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl	llvm::AllocaInst *alloca = CreateTempAlloca(load->getType(),
1171836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl                                                   "block.captured-self.addr");
1172836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        unsigned align = getContext().getDeclAlign(self).getQuantity();
1173836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        alloca->setAlignment(align);
1174836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl	Builder.CreateAlignedStore(load, alloca, align);
1175836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        LocalDeclMap[self] = alloca;
1176836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      } else
1177836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        LocalDeclMap[self] = selfAddr;
11786b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
11796b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  }
1180a5448544eea6663f8dce30a50343ef5125559794Mike Stump
11816b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // Also force all the constant captures.
11826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
11836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         ce = blockDecl->capture_end(); ci != ce; ++ci) {
11846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *variable = ci->getVariable();
11856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
11866b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (!capture.isConstant()) continue;
1187d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson
11886b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    unsigned align = getContext().getDeclAlign(variable).getQuantity();
1189a5448544eea6663f8dce30a50343ef5125559794Mike Stump
11906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    llvm::AllocaInst *alloca =
11916b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      CreateMemTemp(variable->getType(), "block.captured-const");
11926b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    alloca->setAlignment(align);
1193a5448544eea6663f8dce30a50343ef5125559794Mike Stump
1194836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl    Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1195ea1471e0e967548c596a71469702f8846dbaf3c0John McCall
11966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    LocalDeclMap[variable] = alloca;
1197ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall  }
1198ee5042903d53fa7b0fbc1902d0ea07d57c7775b1John McCall
1199f4b88a45902af1802a1cb42ba48b1c474474f228John McCall  // Save a spot to insert the debug information for all the DeclRefExprs.
1200b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump  llvm::BasicBlock *entry = Builder.GetInsertBlock();
1201b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump  llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1202b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump  --entry_ptr;
1203b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump
120464bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman  if (IsLambdaConversionToBlock)
120564bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman    EmitLambdaBlockInvokeBody();
120664bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman  else
120764bee65a3436e3f0c352fcfe2130676f3502cffeEli Friedman    EmitStmt(blockDecl->getBody());
1208b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump
1209de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  // Remember where we were...
1210de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  llvm::BasicBlock *resume = Builder.GetInsertBlock();
1211b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump
1212de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  // Go back to the entry.
1213b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump  ++entry_ptr;
1214b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump  Builder.SetInsertPoint(entry, entry_ptr);
1215b289b3f324eb10d416b87080e39b315f6c17a695Mike Stump
1216f4b88a45902af1802a1cb42ba48b1c474474f228John McCall  // Emit debug information for all the DeclRefExprs.
12176b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // FIXME: also for 'this'
1218b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump  if (CGDebugInfo *DI = getDebugInfo()) {
12196b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
12206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall           ce = blockDecl->capture_end(); ci != ce; ++ci) {
12216b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      const VarDecl *variable = ci->getVariable();
122273fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher      DI->EmitLocation(Builder, variable->getLocation());
12236b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
12244cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor      if (CGM.getCodeGenOpts().getDebugInfo()
12254cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor            >= CodeGenOptions::LimitedDebugInfo) {
1226fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1227fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        if (capture.isConstant()) {
1228fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov          DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1229fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov                                        Builder);
1230fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov          continue;
1231fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        }
12326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1233fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1234fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov                                              Builder, blockInfo);
1235fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov      }
1236b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump    }
12373c7a0e1a75ebe13366a646a9eb8c4aa61e4728d3Manman Ren    // Recover location if it was changed in the above loop.
12383c7a0e1a75ebe13366a646a9eb8c4aa61e4728d3Manman Ren    DI->EmitLocation(Builder,
12393c7a0e1a75ebe13366a646a9eb8c4aa61e4728d3Manman Ren        cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1240b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump  }
12416b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1242de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  // And resume where we left off.
1243de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  if (resume == 0)
1244de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump    Builder.ClearInsertionPoint();
1245de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump  else
1246de8c5c77e27b6b0064c45d964ea8bcc2c853114dMike Stump    Builder.SetInsertPoint(resume);
1247b1a6e687967105bf1e18dfba196d0248e6700a4eMike Stump
12486b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1249d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson
12506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  return fn;
1251d5cab5435371b8cc74a9e05ebd40b5995ebad149Anders Carlsson}
1252a99038c0757a836c6faeeddaa5dfd249b32f6e9eMike Stump
12536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall/*
12546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    notes.push_back(HelperInfo());
12556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    HelperInfo &note = notes.back();
12566b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    note.index = capture.getIndex();
12576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
12586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    note.cxxbar_import = ci->getCopyExpr();
12596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
12606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (ci->isByRef()) {
12616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      note.flag = BLOCK_FIELD_IS_BYREF;
12626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      if (type.isObjCGCWeak())
12636b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall        note.flag |= BLOCK_FIELD_IS_WEAK;
12646b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else if (type->isBlockPointerType()) {
12656b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      note.flag = BLOCK_FIELD_IS_BLOCK;
12666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else {
12676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      note.flag = BLOCK_FIELD_IS_OBJECT;
12686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    }
12696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall */
1270a99038c0757a836c6faeeddaa5dfd249b32f6e9eMike Stump
1271dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump
1272b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Generate the copy-helper function for a block closure object:
1273b62faef5ec86c1931785ffa805ece9b491735894John McCall///   static void block_copy_helper(block_t *dst, block_t *src);
1274b62faef5ec86c1931785ffa805ece9b491735894John McCall/// The runtime will have previously initialized 'dst' by doing a
1275b62faef5ec86c1931785ffa805ece9b491735894John McCall/// bit-copy of 'src'.
1276b62faef5ec86c1931785ffa805ece9b491735894John McCall///
1277b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Note that this copies an entire block closure object to the heap;
1278b62faef5ec86c1931785ffa805ece9b491735894John McCall/// it should not be confused with a 'byref copy helper', which moves
1279b62faef5ec86c1931785ffa805ece9b491735894John McCall/// the contents of an individual __block variable to the heap.
12806b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallllvm::Constant *
1281d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCallCodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
12826b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  ASTContext &C = getContext();
12836b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
12846b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FunctionArgList args;
1285d26bc76c98006609002d9930f8840490e88ac5b5John McCall  ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1286d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&dstDecl);
1287d26bc76c98006609002d9930f8840490e88ac5b5John McCall  ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1288d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&srcDecl);
12891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1290a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  const CGFunctionInfo &FI =
1291de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1292de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              FunctionType::ExtInfo(),
1293de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              /*variadic*/ false);
1294a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
12956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // FIXME: it would be nice if these were mergeable with things with
12966b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  // identical semantics.
1297de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1298a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
1299a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  llvm::Function *Fn =
1300a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
13013cf7c5dc23569ae76bd4bddaed22f696233d8e44Benjamin Kramer                           "__copy_helper_block_", &CGM.getModule());
1302a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
1303a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  IdentifierInfo *II
1304a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump    = &CGM.getContext().Idents.get("__copy_helper_block_");
1305a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
130658dc5ca0841900b197de7733197196f435bf0cc3Devang Patel  // Check if we should generate debug info for this block helper function.
1307a240df2ec1b374b3e9e7f760875ffb17cd64506fAlexey Samsonov  maybeInitializeDebugInfo();
130858dc5ca0841900b197de7733197196f435bf0cc3Devang Patel
13096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FunctionDecl *FD = FunctionDecl::Create(C,
13106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                          C.getTranslationUnitDecl(),
1311ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                          SourceLocation(),
13126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                          SourceLocation(), II, C.VoidTy, 0,
1313d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_Static,
1314d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_None,
131516573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                          false,
1316e5bbebb4d14347700ff0b1838f14cae3b8a35c69Eric Christopher                                          false);
1317d26bc76c98006609002d9930f8840490e88ac5b5John McCall  StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
13180892099dbc640720400a1d9decd2733a09d733e5Mike Stump
13192acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
13206b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1321d26bc76c98006609002d9930f8840490e88ac5b5John McCall  llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1322d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  src = Builder.CreateLoad(src);
1323d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  src = Builder.CreateBitCast(src, structPtrTy, "block.source");
13246b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1325d26bc76c98006609002d9930f8840490e88ac5b5John McCall  llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1326d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  dst = Builder.CreateLoad(dst);
1327d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
13286b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13296b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
13306b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13316b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
13326b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         ce = blockDecl->capture_end(); ci != ce; ++ci) {
13336b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *variable = ci->getVariable();
13346b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    QualType type = variable->getType();
13356b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13366b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
13376b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (capture.isConstant()) continue;
13386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13396b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const Expr *copyExpr = ci->getCopyExpr();
1340f85e193739c953358c865005855253af4f68a497John McCall    BlockFieldFlags flags;
1341f85e193739c953358c865005855253af4f68a497John McCall
1342015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    bool useARCWeakCopy = false;
1343015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    bool useARCStrongCopy = false;
13446b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13456b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (copyExpr) {
13466b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      assert(!ci->isByRef());
13476b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      // don't bother computing flags
1348f85e193739c953358c865005855253af4f68a497John McCall
13496b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else if (ci->isByRef()) {
13506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      flags = BLOCK_FIELD_IS_BYREF;
1351f85e193739c953358c865005855253af4f68a497John McCall      if (type.isObjCGCWeak())
1352f85e193739c953358c865005855253af4f68a497John McCall        flags |= BLOCK_FIELD_IS_WEAK;
1353f85e193739c953358c865005855253af4f68a497John McCall
1354f85e193739c953358c865005855253af4f68a497John McCall    } else if (type->isObjCRetainableType()) {
13556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      flags = BLOCK_FIELD_IS_OBJECT;
1356015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      bool isBlockPointer = type->isBlockPointerType();
1357015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      if (isBlockPointer)
1358f85e193739c953358c865005855253af4f68a497John McCall        flags = BLOCK_FIELD_IS_BLOCK;
13596b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1360f85e193739c953358c865005855253af4f68a497John McCall      // Special rules for ARC captures:
13614e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().ObjCAutoRefCount) {
1362f85e193739c953358c865005855253af4f68a497John McCall        Qualifiers qs = type.getQualifiers();
1363f85e193739c953358c865005855253af4f68a497John McCall
1364015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // We need to register __weak direct captures with the runtime.
1365015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1366015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          useARCWeakCopy = true;
1367015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
1368015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // We need to retain the copied value for __strong direct captures.
1369015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1370015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          // If it's a block pointer, we have to copy the block and
1371015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          // assign that to the destination pointer, so we might as
1372015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          // well use _Block_object_assign.  Otherwise we can avoid that.
1373015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          if (!isBlockPointer)
1374015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall            useARCStrongCopy = true;
1375015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
1376015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // Otherwise the memcpy is fine.
1377015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        } else {
1378f85e193739c953358c865005855253af4f68a497John McCall          continue;
1379015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        }
1380f85e193739c953358c865005855253af4f68a497John McCall
1381015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      // Non-ARC captures of retainable pointers are strong and
1382015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      // therefore require a call to _Block_object_assign.
1383015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      } else {
1384015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // fall through
1385f85e193739c953358c865005855253af4f68a497John McCall      }
1386f85e193739c953358c865005855253af4f68a497John McCall    } else {
1387f85e193739c953358c865005855253af4f68a497John McCall      continue;
1388f85e193739c953358c865005855253af4f68a497John McCall    }
13896b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13906b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    unsigned index = capture.getIndex();
1391d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1392d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
13936b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
13946b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // If there's an explicit copy expression, we do that.
13956b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (copyExpr) {
1396d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall      EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1397015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    } else if (useARCWeakCopy) {
1398f85e193739c953358c865005855253af4f68a497John McCall      EmitARCCopyWeak(dstField, srcField);
13996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else {
14006b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1401015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      if (useARCStrongCopy) {
1402015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // At -O0, store null into the destination field (so that the
1403015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // storeStrong doesn't over-release) and then call storeStrong.
1404015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // This is a workaround to not having an initStrong call.
1405015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1406015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1407015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1408015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          Builder.CreateStore(null, dstField);
1409015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          EmitARCStoreStrongCall(dstField, srcValue, true);
1410015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
1411015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // With optimization enabled, take advantage of the fact that
1412015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // the blocks runtime guarantees a memcpy of the block data, and
1413015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // just emit a retain of the src field.
1414015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        } else {
1415015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          EmitARCRetainNonBlock(srcValue);
1416015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
1417015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          // We don't need this anymore, so kill it.  It's not quite
1418015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          // worth the annoyance to avoid creating it in the first place.
1419015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          cast<llvm::Instruction>(dstField)->eraseFromParent();
1420015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        }
1421015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      } else {
1422015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1423015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1424bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        llvm::Value *args[] = {
1425bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1426bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        };
1427bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall
1428bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        bool copyCanThrow = false;
1429bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        if (ci->isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1430bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          const Expr *copyExpr =
1431bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall            CGM.getContext().getBlockVarCopyInits(variable);
1432bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          if (copyExpr) {
1433bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall            copyCanThrow = true; // FIXME: reuse the noexcept logic
1434bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          }
1435bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        }
1436bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall
1437bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        if (copyCanThrow) {
1438bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1439bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        } else {
1440bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall          EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1441bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall        }
1442015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall      }
14430892099dbc640720400a1d9decd2733a09d733e5Mike Stump    }
14440892099dbc640720400a1d9decd2733a09d733e5Mike Stump  }
14450892099dbc640720400a1d9decd2733a09d733e5Mike Stump
1446d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  FinishFunction();
1447a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
14485936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1449dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump}
1450dab514fc30242c7afd6c03956e46136c400fb0d3Mike Stump
1451b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Generate the destroy-helper function for a block closure object:
1452b62faef5ec86c1931785ffa805ece9b491735894John McCall///   static void block_destroy_helper(block_t *theBlock);
1453b62faef5ec86c1931785ffa805ece9b491735894John McCall///
1454b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Note that this destroys a heap-allocated block closure object;
1455b62faef5ec86c1931785ffa805ece9b491735894John McCall/// it should not be confused with a 'byref destroy helper', which
1456b62faef5ec86c1931785ffa805ece9b491735894John McCall/// destroys the heap-allocated contents of an individual __block
1457b62faef5ec86c1931785ffa805ece9b491735894John McCall/// variable.
14586b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCallllvm::Constant *
1459d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCallCodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
14606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  ASTContext &C = getContext();
1461a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
14626b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FunctionArgList args;
1463d26bc76c98006609002d9930f8840490e88ac5b5John McCall  ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1464d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&srcDecl);
14651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1466a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  const CGFunctionInfo &FI =
1467de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1468de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              FunctionType::ExtInfo(),
1469de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                              /*variadic*/ false);
1470a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
14713899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // FIXME: We'd like to put these into a mergable by content, with
14723899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // internal linkage.
1473de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1474a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
1475a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  llvm::Function *Fn =
1476a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
14773cf7c5dc23569ae76bd4bddaed22f696233d8e44Benjamin Kramer                           "__destroy_helper_block_", &CGM.getModule());
1478a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
147958dc5ca0841900b197de7733197196f435bf0cc3Devang Patel  // Check if we should generate debug info for this block destroy function.
1480a240df2ec1b374b3e9e7f760875ffb17cd64506fAlexey Samsonov  maybeInitializeDebugInfo();
148158dc5ca0841900b197de7733197196f435bf0cc3Devang Patel
1482a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  IdentifierInfo *II
1483a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump    = &CGM.getContext().Idents.get("__destroy_helper_block_");
1484a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
14856b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1486ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                          SourceLocation(),
14876b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                          SourceLocation(), II, C.VoidTy, 0,
1488d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_Static,
1489d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_None,
1490e5bbebb4d14347700ff0b1838f14cae3b8a35c69Eric Christopher                                          false, false);
1491d26bc76c98006609002d9930f8840490e88ac5b5John McCall  StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
14921edf6b646ea161ce1193ba278ae88de82ff7114dMike Stump
14932acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1494b7477cf6cf6cf4f132ba7beff42684e59bed15f4Mike Stump
1495d26bc76c98006609002d9930f8840490e88ac5b5John McCall  llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1496d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  src = Builder.CreateLoad(src);
1497d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  src = Builder.CreateBitCast(src, structPtrTy, "block");
14986b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
14996b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
15006b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1501d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  CodeGenFunction::RunCleanupsScope cleanups(*this);
15026b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
15036b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
15046b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall         ce = blockDecl->capture_end(); ci != ce; ++ci) {
15056b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const VarDecl *variable = ci->getVariable();
15066b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    QualType type = variable->getType();
15076b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
15086b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
15096b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (capture.isConstant()) continue;
15106b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1511d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockFieldFlags flags;
15126b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    const CXXDestructorDecl *dtor = 0;
15136b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1514015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    bool useARCWeakDestroy = false;
1515015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    bool useARCStrongDestroy = false;
1516f85e193739c953358c865005855253af4f68a497John McCall
15176b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (ci->isByRef()) {
15186b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      flags = BLOCK_FIELD_IS_BYREF;
1519f85e193739c953358c865005855253af4f68a497John McCall      if (type.isObjCGCWeak())
1520f85e193739c953358c865005855253af4f68a497John McCall        flags |= BLOCK_FIELD_IS_WEAK;
1521f85e193739c953358c865005855253af4f68a497John McCall    } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1522f85e193739c953358c865005855253af4f68a497John McCall      if (record->hasTrivialDestructor())
1523f85e193739c953358c865005855253af4f68a497John McCall        continue;
1524f85e193739c953358c865005855253af4f68a497John McCall      dtor = record->getDestructor();
1525f85e193739c953358c865005855253af4f68a497John McCall    } else if (type->isObjCRetainableType()) {
15266b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      flags = BLOCK_FIELD_IS_OBJECT;
1527f85e193739c953358c865005855253af4f68a497John McCall      if (type->isBlockPointerType())
1528f85e193739c953358c865005855253af4f68a497John McCall        flags = BLOCK_FIELD_IS_BLOCK;
1529f85e193739c953358c865005855253af4f68a497John McCall
1530f85e193739c953358c865005855253af4f68a497John McCall      // Special rules for ARC captures.
15314e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().ObjCAutoRefCount) {
1532f85e193739c953358c865005855253af4f68a497John McCall        Qualifiers qs = type.getQualifiers();
1533f85e193739c953358c865005855253af4f68a497John McCall
1534f85e193739c953358c865005855253af4f68a497John McCall        // Don't generate special dispose logic for a captured object
1535f85e193739c953358c865005855253af4f68a497John McCall        // unless it's __strong or __weak.
1536f85e193739c953358c865005855253af4f68a497John McCall        if (!qs.hasStrongOrWeakObjCLifetime())
1537f85e193739c953358c865005855253af4f68a497John McCall          continue;
15386b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1539f85e193739c953358c865005855253af4f68a497John McCall        // Support __weak direct captures.
1540f85e193739c953358c865005855253af4f68a497John McCall        if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1541015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          useARCWeakDestroy = true;
1542015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
1543015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        // Tools really want us to use objc_storeStrong here.
1544015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall        else
1545015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall          useARCStrongDestroy = true;
1546f85e193739c953358c865005855253af4f68a497John McCall      }
1547f85e193739c953358c865005855253af4f68a497John McCall    } else {
1548f85e193739c953358c865005855253af4f68a497John McCall      continue;
1549f85e193739c953358c865005855253af4f68a497John McCall    }
15506b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
15516b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    unsigned index = capture.getIndex();
1552d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    llvm::Value *srcField = Builder.CreateStructGEP(src, index);
15536b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
15546b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // If there's an explicit copy expression, we do that.
15556b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    if (dtor) {
1556d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall      PushDestructorCleanup(dtor, srcField);
15576b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1558f85e193739c953358c865005855253af4f68a497John McCall    // If this is a __weak capture, emit the release directly.
1559015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    } else if (useARCWeakDestroy) {
1560f85e193739c953358c865005855253af4f68a497John McCall      EmitARCDestroyWeak(srcField);
1561f85e193739c953358c865005855253af4f68a497John McCall
1562015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    // Destroy strong objects with a call if requested.
1563015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall    } else if (useARCStrongDestroy) {
15645b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall      EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1565015f33b6741ffceba3a71ee2d71d46418a7dc34cJohn McCall
15666b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // Otherwise we call _Block_object_dispose.  It wouldn't be too
15676b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // hard to just emit this as a cleanup if we wanted to make sure
15686b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    // that things were done in reverse.
15696b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall    } else {
15706b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      llvm::Value *value = Builder.CreateLoad(srcField);
15715936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      value = Builder.CreateBitCast(value, VoidPtrTy);
15726b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall      BuildBlockRelease(value, flags);
15731edf6b646ea161ce1193ba278ae88de82ff7114dMike Stump    }
15741edf6b646ea161ce1193ba278ae88de82ff7114dMike Stump  }
15751edf6b646ea161ce1193ba278ae88de82ff7114dMike Stump
15766b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall  cleanups.ForceCleanup();
15776b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall
1578d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  FinishFunction();
1579a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
15805936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1581a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump}
1582a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump
1583f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallnamespace {
1584f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1585f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// Emits the copy/dispose helper functions for a __block object of id type.
1586f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallclass ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1587f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  BlockFieldFlags Flags;
1588f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1589f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallpublic:
1590f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1591f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    : ByrefHelpers(alignment), Flags(flags) {}
1592f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1593361701965ed119099d180d419ac25a0503fcc0feJohn McCall  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1594361701965ed119099d180d419ac25a0503fcc0feJohn McCall                llvm::Value *srcField) {
1595f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1596f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1597f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1598f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1599f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1600f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1601f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1602f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1603f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1604bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall
1605bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    llvm::Value *args[] = { destField, srcValue, flagsVal };
1606bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    CGF.EmitNounwindRuntimeCall(fn, args);
1607f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1608f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1609f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1610f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1611f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *value = CGF.Builder.CreateLoad(field);
1612f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1613f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1614f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1615f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1616f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void profileImpl(llvm::FoldingSetNodeID &id) const {
1617f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    id.AddInteger(Flags.getBitMask());
1618f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1619f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall};
1620f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1621f85e193739c953358c865005855253af4f68a497John McCall/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1622f85e193739c953358c865005855253af4f68a497John McCallclass ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1623f85e193739c953358c865005855253af4f68a497John McCallpublic:
1624f85e193739c953358c865005855253af4f68a497John McCall  ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1625f85e193739c953358c865005855253af4f68a497John McCall
1626f85e193739c953358c865005855253af4f68a497John McCall  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1627f85e193739c953358c865005855253af4f68a497John McCall                llvm::Value *srcField) {
1628f85e193739c953358c865005855253af4f68a497John McCall    CGF.EmitARCMoveWeak(destField, srcField);
1629f85e193739c953358c865005855253af4f68a497John McCall  }
1630f85e193739c953358c865005855253af4f68a497John McCall
1631f85e193739c953358c865005855253af4f68a497John McCall  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1632f85e193739c953358c865005855253af4f68a497John McCall    CGF.EmitARCDestroyWeak(field);
1633f85e193739c953358c865005855253af4f68a497John McCall  }
1634f85e193739c953358c865005855253af4f68a497John McCall
1635f85e193739c953358c865005855253af4f68a497John McCall  void profileImpl(llvm::FoldingSetNodeID &id) const {
1636f85e193739c953358c865005855253af4f68a497John McCall    // 0 is distinguishable from all pointers and byref flags
1637f85e193739c953358c865005855253af4f68a497John McCall    id.AddInteger(0);
1638f85e193739c953358c865005855253af4f68a497John McCall  }
1639f85e193739c953358c865005855253af4f68a497John McCall};
1640f85e193739c953358c865005855253af4f68a497John McCall
1641f85e193739c953358c865005855253af4f68a497John McCall/// Emits the copy/dispose helpers for an ARC __block __strong variable
1642f85e193739c953358c865005855253af4f68a497John McCall/// that's not of block-pointer type.
1643f85e193739c953358c865005855253af4f68a497John McCallclass ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1644f85e193739c953358c865005855253af4f68a497John McCallpublic:
1645f85e193739c953358c865005855253af4f68a497John McCall  ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1646f85e193739c953358c865005855253af4f68a497John McCall
1647f85e193739c953358c865005855253af4f68a497John McCall  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1648f85e193739c953358c865005855253af4f68a497John McCall                llvm::Value *srcField) {
1649f85e193739c953358c865005855253af4f68a497John McCall    // Do a "move" by copying the value and then zeroing out the old
1650f85e193739c953358c865005855253af4f68a497John McCall    // variable.
1651f85e193739c953358c865005855253af4f68a497John McCall
1652a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1653a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    value->setAlignment(Alignment.getQuantity());
1654a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1655f85e193739c953358c865005855253af4f68a497John McCall    llvm::Value *null =
1656f85e193739c953358c865005855253af4f68a497John McCall      llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1657a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
16587a77f1994bdbe67db361b851a0907cf49fddfd91Fariborz Jahanian    if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1659ba3c9ca16b3992248ec654ce9ec8c841c1c6d1e9Fariborz Jahanian      llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1660ba3c9ca16b3992248ec654ce9ec8c841c1c6d1e9Fariborz Jahanian      store->setAlignment(Alignment.getQuantity());
16617a77f1994bdbe67db361b851a0907cf49fddfd91Fariborz Jahanian      CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
16627a77f1994bdbe67db361b851a0907cf49fddfd91Fariborz Jahanian      CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
16637a77f1994bdbe67db361b851a0907cf49fddfd91Fariborz Jahanian      return;
16647a77f1994bdbe67db361b851a0907cf49fddfd91Fariborz Jahanian    }
1665a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1666a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    store->setAlignment(Alignment.getQuantity());
1667a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1668a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    store = CGF.Builder.CreateStore(null, srcField);
1669a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    store->setAlignment(Alignment.getQuantity());
1670f85e193739c953358c865005855253af4f68a497John McCall  }
1671f85e193739c953358c865005855253af4f68a497John McCall
1672f85e193739c953358c865005855253af4f68a497John McCall  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
16735b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall    CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1674f85e193739c953358c865005855253af4f68a497John McCall  }
1675f85e193739c953358c865005855253af4f68a497John McCall
1676f85e193739c953358c865005855253af4f68a497John McCall  void profileImpl(llvm::FoldingSetNodeID &id) const {
1677f85e193739c953358c865005855253af4f68a497John McCall    // 1 is distinguishable from all pointers and byref flags
1678f85e193739c953358c865005855253af4f68a497John McCall    id.AddInteger(1);
1679f85e193739c953358c865005855253af4f68a497John McCall  }
1680f85e193739c953358c865005855253af4f68a497John McCall};
1681f85e193739c953358c865005855253af4f68a497John McCall
1682a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall/// Emits the copy/dispose helpers for an ARC __block __strong
1683a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall/// variable that's of block-pointer type.
1684a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCallclass ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1685a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCallpublic:
1686a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1687a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1688a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1689a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall                llvm::Value *srcField) {
1690a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    // Do the copy with objc_retainBlock; that's all that
1691a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    // _Block_object_assign would do anyway, and we'd have to pass the
1692a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    // right arguments to make sure it doesn't get no-op'ed.
1693a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1694a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    oldValue->setAlignment(Alignment.getQuantity());
1695a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1696a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1697a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1698a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1699a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    store->setAlignment(Alignment.getQuantity());
1700a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  }
1701a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1702a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
17035b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall    CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1704a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  }
1705a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1706a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  void profileImpl(llvm::FoldingSetNodeID &id) const {
1707a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    // 2 is distinguishable from all pointers and byref flags
1708a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall    id.AddInteger(2);
1709a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall  }
1710a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall};
1711a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall
1712f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// Emits the copy/dispose helpers for a __block variable with a
1713f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// nontrivial copy constructor or destructor.
1714f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallclass CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1715f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  QualType VarType;
1716f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  const Expr *CopyExpr;
1717f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1718f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallpublic:
1719f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CXXByrefHelpers(CharUnits alignment, QualType type,
1720f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                  const Expr *copyExpr)
1721f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1722f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1723f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  bool needsCopy() const { return CopyExpr != 0; }
1724f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1725f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                llvm::Value *srcField) {
1726f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    if (!CopyExpr) return;
1727f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1728f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1729f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1730f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1731f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1732f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    CGF.PushDestructorCleanup(VarType, field);
1733f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    CGF.PopCleanupBlocks(cleanupDepth);
1734f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1735f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1736f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void profileImpl(llvm::FoldingSetNodeID &id) const {
1737f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1738f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1739f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall};
1740f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall} // end anonymous namespace
1741f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1742f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallstatic llvm::Constant *
1743f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallgenerateByrefCopyHelper(CodeGenFunction &CGF,
17442acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                        llvm::StructType &byrefType,
1745b62faef5ec86c1931785ffa805ece9b491735894John McCall                        unsigned valueFieldIndex,
1746f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                        CodeGenModule::ByrefHelpers &byrefInfo) {
1747f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ASTContext &Context = CGF.getContext();
1748f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1749f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  QualType R = Context.VoidTy;
175045031c08c608e548ac12caf0547f89574e994b96Mike Stump
1751d26bc76c98006609002d9930f8840490e88ac5b5John McCall  FunctionArgList args;
1752f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
1753d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&dst);
1754d26bc76c98006609002d9930f8840490e88ac5b5John McCall
1755f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1756d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&src);
17571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
175845031c08c608e548ac12caf0547f89574e994b96Mike Stump  const CGFunctionInfo &FI =
1759de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1760de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                                  FunctionType::ExtInfo(),
1761de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                                  /*variadic*/ false);
176245031c08c608e548ac12caf0547f89574e994b96Mike Stump
1763f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenTypes &Types = CGF.CGM.getTypes();
1764de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *LTy = Types.GetFunctionType(FI);
176545031c08c608e548ac12caf0547f89574e994b96Mike Stump
17663899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // FIXME: We'd like to put these into a mergable by content, with
17673899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // internal linkage.
176845031c08c608e548ac12caf0547f89574e994b96Mike Stump  llvm::Function *Fn =
176945031c08c608e548ac12caf0547f89574e994b96Mike Stump    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1770f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                           "__Block_byref_object_copy_", &CGF.CGM.getModule());
177145031c08c608e548ac12caf0547f89574e994b96Mike Stump
177245031c08c608e548ac12caf0547f89574e994b96Mike Stump  IdentifierInfo *II
1773f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    = &Context.Idents.get("__Block_byref_object_copy_");
177445031c08c608e548ac12caf0547f89574e994b96Mike Stump
1775f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  FunctionDecl *FD = FunctionDecl::Create(Context,
1776f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                          Context.getTranslationUnitDecl(),
1777ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                          SourceLocation(),
1778a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                          SourceLocation(), II, R, 0,
1779d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_Static,
1780d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_None,
1781b92bd4b3271b7892abe9fd8c74fb54a27ad702abEric Christopher                                          false, false);
1782f85e193739c953358c865005855253af4f68a497John McCall
178334b41f80aad3679c545a4ba9bca9c1a318d41844Alexey Samsonov  // Initialize debug info if necessary.
178434b41f80aad3679c545a4ba9bca9c1a318d41844Alexey Samsonov  CGF.maybeInitializeDebugInfo();
1785f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
178645031c08c608e548ac12caf0547f89574e994b96Mike Stump
1787f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (byrefInfo.needsCopy()) {
17882acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1789f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1790f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    // dst->x
1791f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1792f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    destField = CGF.Builder.CreateLoad(destField);
1793f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1794b62faef5ec86c1931785ffa805ece9b491735894John McCall    destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
1795f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1796f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    // src->x
1797f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1798f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    srcField = CGF.Builder.CreateLoad(srcField);
1799f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1800b62faef5ec86c1931785ffa805ece9b491735894John McCall    srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
1801f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1802f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    byrefInfo.emitCopy(CGF, destField, srcField);
1803f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1804f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1805f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CGF.FinishFunction();
1806f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1807f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
180845031c08c608e548ac12caf0547f89574e994b96Mike Stump}
180945031c08c608e548ac12caf0547f89574e994b96Mike Stump
1810f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// Build the copy helper for a __block variable.
1811f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallstatic llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
18122acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                            llvm::StructType &byrefType,
1813b62faef5ec86c1931785ffa805ece9b491735894John McCall                                            unsigned byrefValueIndex,
1814f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                            CodeGenModule::ByrefHelpers &info) {
1815f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenFunction CGF(CGM);
1816b62faef5ec86c1931785ffa805ece9b491735894John McCall  return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1817f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall}
1818f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1819f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// Generate code for a __block variable's dispose helper.
1820f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallstatic llvm::Constant *
1821f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallgenerateByrefDisposeHelper(CodeGenFunction &CGF,
18222acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                           llvm::StructType &byrefType,
1823b62faef5ec86c1931785ffa805ece9b491735894John McCall                           unsigned byrefValueIndex,
1824f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                           CodeGenModule::ByrefHelpers &byrefInfo) {
1825f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ASTContext &Context = CGF.getContext();
1826f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  QualType R = Context.VoidTy;
182745031c08c608e548ac12caf0547f89574e994b96Mike Stump
1828d26bc76c98006609002d9930f8840490e88ac5b5John McCall  FunctionArgList args;
1829f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1830d26bc76c98006609002d9930f8840490e88ac5b5John McCall  args.push_back(&src);
18311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
183245031c08c608e548ac12caf0547f89574e994b96Mike Stump  const CGFunctionInfo &FI =
1833de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1834de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                                  FunctionType::ExtInfo(),
1835de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                                  /*variadic*/ false);
183645031c08c608e548ac12caf0547f89574e994b96Mike Stump
1837f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenTypes &Types = CGF.CGM.getTypes();
1838de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *LTy = Types.GetFunctionType(FI);
183945031c08c608e548ac12caf0547f89574e994b96Mike Stump
18403899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // FIXME: We'd like to put these into a mergable by content, with
18413899a7fb9c7eeed19cc38d082921dd8b3d0d6624Mike Stump  // internal linkage.
184245031c08c608e548ac12caf0547f89574e994b96Mike Stump  llvm::Function *Fn =
184345031c08c608e548ac12caf0547f89574e994b96Mike Stump    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1844830937bc1100fba7682f7c32c40512085870f50cFariborz Jahanian                           "__Block_byref_object_dispose_",
1845f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                           &CGF.CGM.getModule());
184645031c08c608e548ac12caf0547f89574e994b96Mike Stump
184745031c08c608e548ac12caf0547f89574e994b96Mike Stump  IdentifierInfo *II
1848f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    = &Context.Idents.get("__Block_byref_object_dispose_");
184945031c08c608e548ac12caf0547f89574e994b96Mike Stump
1850f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  FunctionDecl *FD = FunctionDecl::Create(Context,
1851f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                          Context.getTranslationUnitDecl(),
1852ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                          SourceLocation(),
1853a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                          SourceLocation(), II, R, 0,
1854d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_Static,
1855d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_None,
1856b92bd4b3271b7892abe9fd8c74fb54a27ad702abEric Christopher                                          false, false);
185734b41f80aad3679c545a4ba9bca9c1a318d41844Alexey Samsonov  // Initialize debug info if necessary.
185834b41f80aad3679c545a4ba9bca9c1a318d41844Alexey Samsonov  CGF.maybeInitializeDebugInfo();
1859f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
18601851b68aaa6717783609f366f5d87bbd0030f189Mike Stump
1861f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (byrefInfo.needsDispose()) {
1862f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1863f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    V = CGF.Builder.CreateLoad(V);
1864f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1865b62faef5ec86c1931785ffa805ece9b491735894John McCall    V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
1866d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
1867f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    byrefInfo.emitDispose(CGF, V);
1868830937bc1100fba7682f7c32c40512085870f50cFariborz Jahanian  }
186945031c08c608e548ac12caf0547f89574e994b96Mike Stump
1870f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CGF.FinishFunction();
1871d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
1872f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
187345031c08c608e548ac12caf0547f89574e994b96Mike Stump}
187445031c08c608e548ac12caf0547f89574e994b96Mike Stump
1875f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall/// Build the dispose helper for a __block variable.
1876f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallstatic llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
18772acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                              llvm::StructType &byrefType,
1878b62faef5ec86c1931785ffa805ece9b491735894John McCall                                               unsigned byrefValueIndex,
1879f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                            CodeGenModule::ByrefHelpers &info) {
1880f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenFunction CGF(CGM);
1881b62faef5ec86c1931785ffa805ece9b491735894John McCall  return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
188245031c08c608e548ac12caf0547f89574e994b96Mike Stump}
188345031c08c608e548ac12caf0547f89574e994b96Mike Stump
1884b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Lazily build the copy and dispose helpers for a __block variable
1885b62faef5ec86c1931785ffa805ece9b491735894John McCall/// with the given information.
1886f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCalltemplate <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
18872acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                               llvm::StructType &byrefTy,
1888b62faef5ec86c1931785ffa805ece9b491735894John McCall                                               unsigned byrefValueIndex,
1889f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                               T &byrefInfo) {
1890f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  // Increase the field's alignment to be at least pointer alignment,
1891f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  // since the layout of the byref struct will guarantee at least that.
1892f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1893f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                              CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1894f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1895f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  llvm::FoldingSetNodeID id;
1896f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  byrefInfo.Profile(id);
1897f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1898f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  void *insertPos;
1899f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenModule::ByrefHelpers *node
1900f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1901f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (node) return static_cast<T*>(node);
1902f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1903b62faef5ec86c1931785ffa805ece9b491735894John McCall  byrefInfo.CopyHelper =
1904b62faef5ec86c1931785ffa805ece9b491735894John McCall    buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1905b62faef5ec86c1931785ffa805ece9b491735894John McCall  byrefInfo.DisposeHelper =
1906b62faef5ec86c1931785ffa805ece9b491735894John McCall    buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1907f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1908f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  T *copy = new (CGM.getContext()) T(byrefInfo);
1909f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1910f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  return copy;
1911f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall}
1912f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1913b62faef5ec86c1931785ffa805ece9b491735894John McCall/// Build the copy and dispose helpers for the given __block variable
1914b62faef5ec86c1931785ffa805ece9b491735894John McCall/// emission.  Places the helpers in the global cache.  Returns null
1915b62faef5ec86c1931785ffa805ece9b491735894John McCall/// if no helpers are required.
1916f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCallCodeGenModule::ByrefHelpers *
19172acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1918f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                                   const AutoVarEmission &emission) {
1919f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  const VarDecl &var = *emission.Variable;
1920f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  QualType type = var.getType();
1921f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1922b62faef5ec86c1931785ffa805ece9b491735894John McCall  unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1923b62faef5ec86c1931785ffa805ece9b491735894John McCall
1924f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1925f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1926f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    if (!copyExpr && record->hasTrivialDestructor()) return 0;
1927f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1928f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1929b62faef5ec86c1931785ffa805ece9b491735894John McCall    return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1930f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1931f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1932f85e193739c953358c865005855253af4f68a497John McCall  // Otherwise, if we don't have a retainable type, there's nothing to do.
1933f85e193739c953358c865005855253af4f68a497John McCall  // that the runtime does extra copies.
1934f85e193739c953358c865005855253af4f68a497John McCall  if (!type->isObjCRetainableType()) return 0;
1935f85e193739c953358c865005855253af4f68a497John McCall
1936f85e193739c953358c865005855253af4f68a497John McCall  Qualifiers qs = type.getQualifiers();
1937f85e193739c953358c865005855253af4f68a497John McCall
1938f85e193739c953358c865005855253af4f68a497John McCall  // If we have lifetime, that dominates.
1939f85e193739c953358c865005855253af4f68a497John McCall  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
19404e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    assert(getLangOpts().ObjCAutoRefCount);
1941f85e193739c953358c865005855253af4f68a497John McCall
1942f85e193739c953358c865005855253af4f68a497John McCall    switch (lifetime) {
1943f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_None: llvm_unreachable("impossible");
1944f85e193739c953358c865005855253af4f68a497John McCall
1945f85e193739c953358c865005855253af4f68a497John McCall    // These are just bits as far as the runtime is concerned.
1946f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_ExplicitNone:
1947f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Autoreleasing:
1948f85e193739c953358c865005855253af4f68a497John McCall      return 0;
1949f85e193739c953358c865005855253af4f68a497John McCall
1950f85e193739c953358c865005855253af4f68a497John McCall    // Tell the runtime that this is ARC __weak, called by the
1951f85e193739c953358c865005855253af4f68a497John McCall    // byref routines.
1952f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Weak: {
1953f85e193739c953358c865005855253af4f68a497John McCall      ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1954b62faef5ec86c1931785ffa805ece9b491735894John McCall      return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1955f85e193739c953358c865005855253af4f68a497John McCall    }
1956f85e193739c953358c865005855253af4f68a497John McCall
1957f85e193739c953358c865005855253af4f68a497John McCall    // ARC __strong __block variables need to be retained.
1958f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Strong:
1959a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall      // Block pointers need to be copied, and there's no direct
1960a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall      // transfer possible.
1961f85e193739c953358c865005855253af4f68a497John McCall      if (type->isBlockPointerType()) {
1962a59e4b7fca1d46afd8f315fa87fa8bf1a68df9cdJohn McCall        ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1963b62faef5ec86c1931785ffa805ece9b491735894John McCall        return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1964f85e193739c953358c865005855253af4f68a497John McCall
1965f85e193739c953358c865005855253af4f68a497John McCall      // Otherwise, we transfer ownership of the retain from the stack
1966f85e193739c953358c865005855253af4f68a497John McCall      // to the heap.
1967f85e193739c953358c865005855253af4f68a497John McCall      } else {
1968f85e193739c953358c865005855253af4f68a497John McCall        ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1969b62faef5ec86c1931785ffa805ece9b491735894John McCall        return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1970f85e193739c953358c865005855253af4f68a497John McCall      }
1971f85e193739c953358c865005855253af4f68a497John McCall    }
1972f85e193739c953358c865005855253af4f68a497John McCall    llvm_unreachable("fell out of lifetime switch!");
1973f85e193739c953358c865005855253af4f68a497John McCall  }
1974f85e193739c953358c865005855253af4f68a497John McCall
1975f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  BlockFieldFlags flags;
1976f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (type->isBlockPointerType()) {
1977f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    flags |= BLOCK_FIELD_IS_BLOCK;
1978f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  } else if (CGM.getContext().isObjCNSObjectType(type) ||
1979f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall             type->isObjCObjectPointerType()) {
1980f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    flags |= BLOCK_FIELD_IS_OBJECT;
1981f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  } else {
1982f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    return 0;
1983f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  }
1984f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1985f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (type.isObjCGCWeak())
1986f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    flags |= BLOCK_FIELD_IS_WEAK;
1987f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
1988f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1989b62faef5ec86c1931785ffa805ece9b491735894John McCall  return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
199045031c08c608e548ac12caf0547f89574e994b96Mike Stump}
199145031c08c608e548ac12caf0547f89574e994b96Mike Stump
19925af02db5a48476e0748f135369663080eae87c64John McCallunsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
19935af02db5a48476e0748f135369663080eae87c64John McCall  assert(ByRefValueInfo.count(VD) && "Did not find value!");
19945af02db5a48476e0748f135369663080eae87c64John McCall
19955af02db5a48476e0748f135369663080eae87c64John McCall  return ByRefValueInfo.find(VD)->second.second;
19965af02db5a48476e0748f135369663080eae87c64John McCall}
19975af02db5a48476e0748f135369663080eae87c64John McCall
19985af02db5a48476e0748f135369663080eae87c64John McCallllvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
19995af02db5a48476e0748f135369663080eae87c64John McCall                                                     const VarDecl *V) {
20005af02db5a48476e0748f135369663080eae87c64John McCall  llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
20015af02db5a48476e0748f135369663080eae87c64John McCall  Loc = Builder.CreateLoad(Loc);
20025af02db5a48476e0748f135369663080eae87c64John McCall  Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
20035af02db5a48476e0748f135369663080eae87c64John McCall                                V->getNameAsString());
20045af02db5a48476e0748f135369663080eae87c64John McCall  return Loc;
20055af02db5a48476e0748f135369663080eae87c64John McCall}
20065af02db5a48476e0748f135369663080eae87c64John McCall
20075af02db5a48476e0748f135369663080eae87c64John McCall/// BuildByRefType - This routine changes a __block variable declared as T x
20085af02db5a48476e0748f135369663080eae87c64John McCall///   into:
20095af02db5a48476e0748f135369663080eae87c64John McCall///
20105af02db5a48476e0748f135369663080eae87c64John McCall///      struct {
20115af02db5a48476e0748f135369663080eae87c64John McCall///        void *__isa;
20125af02db5a48476e0748f135369663080eae87c64John McCall///        void *__forwarding;
20135af02db5a48476e0748f135369663080eae87c64John McCall///        int32_t __flags;
20145af02db5a48476e0748f135369663080eae87c64John McCall///        int32_t __size;
20155af02db5a48476e0748f135369663080eae87c64John McCall///        void *__copy_helper;       // only if needed
20165af02db5a48476e0748f135369663080eae87c64John McCall///        void *__destroy_helper;    // only if needed
20173ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian///        void *__byref_variable_layout;// only if needed
20185af02db5a48476e0748f135369663080eae87c64John McCall///        char padding[X];           // only if needed
20195af02db5a48476e0748f135369663080eae87c64John McCall///        T x;
20205af02db5a48476e0748f135369663080eae87c64John McCall///      } x
20215af02db5a48476e0748f135369663080eae87c64John McCall///
20222acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattnerllvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
20232acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
20245af02db5a48476e0748f135369663080eae87c64John McCall  if (Info.first)
20255af02db5a48476e0748f135369663080eae87c64John McCall    return Info.first;
20265af02db5a48476e0748f135369663080eae87c64John McCall
20275af02db5a48476e0748f135369663080eae87c64John McCall  QualType Ty = D->getType();
20285af02db5a48476e0748f135369663080eae87c64John McCall
20295f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Type *, 8> types;
20305af02db5a48476e0748f135369663080eae87c64John McCall
20319cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::StructType *ByRefType =
2032c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner    llvm::StructType::create(getLLVMContext(),
2033c1c20114a401e503c07d68c47e0728bb063f35c8Chris Lattner                             "struct.__block_byref_" + D->getNameAsString());
20345af02db5a48476e0748f135369663080eae87c64John McCall
20355af02db5a48476e0748f135369663080eae87c64John McCall  // void *__isa;
20360774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  types.push_back(Int8PtrTy);
20375af02db5a48476e0748f135369663080eae87c64John McCall
20385af02db5a48476e0748f135369663080eae87c64John McCall  // void *__forwarding;
20399cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  types.push_back(llvm::PointerType::getUnqual(ByRefType));
20405af02db5a48476e0748f135369663080eae87c64John McCall
20415af02db5a48476e0748f135369663080eae87c64John McCall  // int32_t __flags;
20420774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  types.push_back(Int32Ty);
20435af02db5a48476e0748f135369663080eae87c64John McCall
20445af02db5a48476e0748f135369663080eae87c64John McCall  // int32_t __size;
20450774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  types.push_back(Int32Ty);
2046b15c8984ea300624fbbde385d3907667ce1043faFariborz Jahanian  // Note that this must match *exactly* the logic in buildByrefHelpers.
2047b15c8984ea300624fbbde385d3907667ce1043faFariborz Jahanian  bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
20485af02db5a48476e0748f135369663080eae87c64John McCall  if (HasCopyAndDispose) {
20495af02db5a48476e0748f135369663080eae87c64John McCall    /// void *__copy_helper;
20500774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    types.push_back(Int8PtrTy);
20515af02db5a48476e0748f135369663080eae87c64John McCall
20525af02db5a48476e0748f135369663080eae87c64John McCall    /// void *__destroy_helper;
20530774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    types.push_back(Int8PtrTy);
20545af02db5a48476e0748f135369663080eae87c64John McCall  }
20553ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  bool HasByrefExtendedLayout = false;
20563ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  Qualifiers::ObjCLifetime Lifetime;
20573ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
20583ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      HasByrefExtendedLayout)
20593ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    /// void *__byref_variable_layout;
20603ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    types.push_back(Int8PtrTy);
20615af02db5a48476e0748f135369663080eae87c64John McCall
20625af02db5a48476e0748f135369663080eae87c64John McCall  bool Packed = false;
20635af02db5a48476e0748f135369663080eae87c64John McCall  CharUnits Align = getContext().getDeclAlign(D);
20645af02db5a48476e0748f135369663080eae87c64John McCall  if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
20655af02db5a48476e0748f135369663080eae87c64John McCall    // We have to insert padding.
20665af02db5a48476e0748f135369663080eae87c64John McCall
20675af02db5a48476e0748f135369663080eae87c64John McCall    // The struct above has 2 32-bit integers.
20685af02db5a48476e0748f135369663080eae87c64John McCall    unsigned CurrentOffsetInBytes = 4 * 2;
20695af02db5a48476e0748f135369663080eae87c64John McCall
20703ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    // And either 2, 3, 4 or 5 pointers.
20713ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    unsigned noPointers = 2;
20723ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    if (HasCopyAndDispose)
20733ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      noPointers += 2;
20743ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    if (HasByrefExtendedLayout)
20753ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      noPointers += 1;
20763ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian
20773ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
20785af02db5a48476e0748f135369663080eae87c64John McCall
20795af02db5a48476e0748f135369663080eae87c64John McCall    // Align the offset.
20805af02db5a48476e0748f135369663080eae87c64John McCall    unsigned AlignedOffsetInBytes =
20815af02db5a48476e0748f135369663080eae87c64John McCall      llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
20825af02db5a48476e0748f135369663080eae87c64John McCall
20835af02db5a48476e0748f135369663080eae87c64John McCall    unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
20845af02db5a48476e0748f135369663080eae87c64John McCall    if (NumPaddingBytes > 0) {
20858b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner      llvm::Type *Ty = Int8Ty;
20865af02db5a48476e0748f135369663080eae87c64John McCall      // FIXME: We need a sema error for alignment larger than the minimum of
20870774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall      // the maximal stack alignment and the alignment of malloc on the system.
20885af02db5a48476e0748f135369663080eae87c64John McCall      if (NumPaddingBytes > 1)
20895af02db5a48476e0748f135369663080eae87c64John McCall        Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
20905af02db5a48476e0748f135369663080eae87c64John McCall
20910774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall      types.push_back(Ty);
20925af02db5a48476e0748f135369663080eae87c64John McCall
20935af02db5a48476e0748f135369663080eae87c64John McCall      // We want a packed struct.
20945af02db5a48476e0748f135369663080eae87c64John McCall      Packed = true;
20955af02db5a48476e0748f135369663080eae87c64John McCall    }
20965af02db5a48476e0748f135369663080eae87c64John McCall  }
20975af02db5a48476e0748f135369663080eae87c64John McCall
20985af02db5a48476e0748f135369663080eae87c64John McCall  // T x;
20990774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  types.push_back(ConvertTypeForMem(Ty));
21005af02db5a48476e0748f135369663080eae87c64John McCall
21019cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  ByRefType->setBody(types, Packed);
21025af02db5a48476e0748f135369663080eae87c64John McCall
21039cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  Info.first = ByRefType;
21045af02db5a48476e0748f135369663080eae87c64John McCall
21050774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Info.second = types.size() - 1;
21065af02db5a48476e0748f135369663080eae87c64John McCall
21075af02db5a48476e0748f135369663080eae87c64John McCall  return Info.first;
21085af02db5a48476e0748f135369663080eae87c64John McCall}
21095af02db5a48476e0748f135369663080eae87c64John McCall
21105af02db5a48476e0748f135369663080eae87c64John McCall/// Initialize the structural components of a __block variable, i.e.
21115af02db5a48476e0748f135369663080eae87c64John McCall/// everything but the actual object.
21125af02db5a48476e0748f135369663080eae87c64John McCallvoid CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2113f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  // Find the address of the local.
2114f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  llvm::Value *addr = emission.Address;
2115f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall
2116f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  // That's an alloca of the byref structure type.
21172acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *byrefType = cast<llvm::StructType>(
2118f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall                 cast<llvm::PointerType>(addr->getType())->getElementType());
21195af02db5a48476e0748f135369663080eae87c64John McCall
2120f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  // Build the byref helpers if necessary.  This is null if we don't need any.
2121f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CodeGenModule::ByrefHelpers *helpers =
2122f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    buildByrefHelpers(*byrefType, emission);
21235af02db5a48476e0748f135369663080eae87c64John McCall
21245af02db5a48476e0748f135369663080eae87c64John McCall  const VarDecl &D = *emission.Variable;
21255af02db5a48476e0748f135369663080eae87c64John McCall  QualType type = D.getType();
21265af02db5a48476e0748f135369663080eae87c64John McCall
21273ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  bool HasByrefExtendedLayout;
21283ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  Qualifiers::ObjCLifetime ByrefLifetime;
21293ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  bool ByRefHasLifetime =
21303ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
21313ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian
2132f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  llvm::Value *V;
21335af02db5a48476e0748f135369663080eae87c64John McCall
21345af02db5a48476e0748f135369663080eae87c64John McCall  // Initialize the 'isa', which is just 0 or 1.
21355af02db5a48476e0748f135369663080eae87c64John McCall  int isa = 0;
2136f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (type.isObjCGCWeak())
21375af02db5a48476e0748f135369663080eae87c64John McCall    isa = 1;
21385af02db5a48476e0748f135369663080eae87c64John McCall  V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
21395af02db5a48476e0748f135369663080eae87c64John McCall  Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
21405af02db5a48476e0748f135369663080eae87c64John McCall
21415af02db5a48476e0748f135369663080eae87c64John McCall  // Store the address of the variable into its own forwarding pointer.
21425af02db5a48476e0748f135369663080eae87c64John McCall  Builder.CreateStore(addr,
21435af02db5a48476e0748f135369663080eae87c64John McCall                      Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
21445af02db5a48476e0748f135369663080eae87c64John McCall
21455af02db5a48476e0748f135369663080eae87c64John McCall  // Blocks ABI:
21465af02db5a48476e0748f135369663080eae87c64John McCall  //   c) the flags field is set to either 0 if no helper functions are
21473ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
21485af02db5a48476e0748f135369663080eae87c64John McCall  BlockFlags flags;
21493ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
21503ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  if (ByRefHasLifetime) {
21513ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
21523ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      else switch (ByrefLifetime) {
21533ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        case Qualifiers::OCL_Strong:
21543ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          flags |= BLOCK_BYREF_LAYOUT_STRONG;
21553ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          break;
21563ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        case Qualifiers::OCL_Weak:
21573ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          flags |= BLOCK_BYREF_LAYOUT_WEAK;
21583ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          break;
21593ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        case Qualifiers::OCL_ExplicitNone:
21603ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
21613ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          break;
21623ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        case Qualifiers::OCL_None:
21633ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
21643ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian            flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
21653ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          break;
21663ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        default:
21673ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          break;
21683ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      }
21693ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
21703ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
21713ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
21723ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
21733ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      if (flags & BLOCK_BYREF_LAYOUT_MASK) {
21743ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
21753ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
21763ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
21773ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
21783ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          printf(" BLOCK_BYREF_LAYOUT_STRONG");
21793ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
21803ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          printf(" BLOCK_BYREF_LAYOUT_WEAK");
21813ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
21823ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
21833ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian        if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
21843ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian          printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
21853ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      }
21863ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian      printf("\n");
21873ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    }
21883ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  }
21893ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian
21905af02db5a48476e0748f135369663080eae87c64John McCall  Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
21915af02db5a48476e0748f135369663080eae87c64John McCall                      Builder.CreateStructGEP(addr, 2, "byref.flags"));
21925af02db5a48476e0748f135369663080eae87c64John McCall
2193f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2194f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
21955af02db5a48476e0748f135369663080eae87c64John McCall  Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
21965af02db5a48476e0748f135369663080eae87c64John McCall
2197f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall  if (helpers) {
21985af02db5a48476e0748f135369663080eae87c64John McCall    llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
2199f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    Builder.CreateStore(helpers->CopyHelper, copy_helper);
22005af02db5a48476e0748f135369663080eae87c64John McCall
22015af02db5a48476e0748f135369663080eae87c64John McCall    llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
2202f0c11f7e6848f023ced6a5b51399ba787c7d4d0bJohn McCall    Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
22035af02db5a48476e0748f135369663080eae87c64John McCall  }
22043ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  if (ByRefHasLifetime && HasByrefExtendedLayout) {
22053ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
22063ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
22073ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian                                                         "byref.layout");
22083ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    // cast destination to pointer to source type.
22093ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    llvm::Type *DesTy = ByrefLayoutInfo->getType();
22103ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    DesTy = DesTy->getPointerTo();
22113ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
22123ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian    Builder.CreateStore(ByrefLayoutInfo, BC);
22133ca23d7dc6cb61e6f363a58d9256d548199d120cFariborz Jahanian  }
22145af02db5a48476e0748f135369663080eae87c64John McCall}
22155af02db5a48476e0748f135369663080eae87c64John McCall
2216d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCallvoid CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2217673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  llvm::Value *F = CGM.getBlockObjectDispose();
2218bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  llvm::Value *args[] = {
2219bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    Builder.CreateBitCast(V, Int8PtrTy),
2220bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2221bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  };
2222bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2223797b6327571f9d7b1c45404a56ddcbf9b9298ae8Mike Stump}
22245af02db5a48476e0748f135369663080eae87c64John McCall
22255af02db5a48476e0748f135369663080eae87c64John McCallnamespace {
22265af02db5a48476e0748f135369663080eae87c64John McCall  struct CallBlockRelease : EHScopeStack::Cleanup {
22275af02db5a48476e0748f135369663080eae87c64John McCall    llvm::Value *Addr;
22285af02db5a48476e0748f135369663080eae87c64John McCall    CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
22295af02db5a48476e0748f135369663080eae87c64John McCall
2230ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
2231f85e193739c953358c865005855253af4f68a497John McCall      // Should we be passing FIELD_IS_WEAK here?
22325af02db5a48476e0748f135369663080eae87c64John McCall      CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
22335af02db5a48476e0748f135369663080eae87c64John McCall    }
22345af02db5a48476e0748f135369663080eae87c64John McCall  };
22355af02db5a48476e0748f135369663080eae87c64John McCall}
22365af02db5a48476e0748f135369663080eae87c64John McCall
22375af02db5a48476e0748f135369663080eae87c64John McCall/// Enter a cleanup to destroy a __block variable.  Note that this
22385af02db5a48476e0748f135369663080eae87c64John McCall/// cleanup should be a no-op if the variable hasn't left the stack
22395af02db5a48476e0748f135369663080eae87c64John McCall/// yet; if a cleanup is required for the variable itself, that needs
22405af02db5a48476e0748f135369663080eae87c64John McCall/// to be done externally.
22415af02db5a48476e0748f135369663080eae87c64John McCallvoid CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
22425af02db5a48476e0748f135369663080eae87c64John McCall  // We don't enter this cleanup if we're in pure-GC mode.
22434e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
22445af02db5a48476e0748f135369663080eae87c64John McCall    return;
22455af02db5a48476e0748f135369663080eae87c64John McCall
22465af02db5a48476e0748f135369663080eae87c64John McCall  EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
22475af02db5a48476e0748f135369663080eae87c64John McCall}
224813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
224913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall/// Adjust the declaration of something from the blocks API.
225013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCallstatic void configureBlocksRuntimeObject(CodeGenModule &CGM,
225113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall                                         llvm::Constant *C) {
22524e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
225313db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
225413db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
225513db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  if (GV->isDeclaration() &&
225613db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall      GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
225713db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
225813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall}
225913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
226013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCallllvm::Constant *CodeGenModule::getBlockObjectDispose() {
226113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  if (BlockObjectDispose)
226213db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    return BlockObjectDispose;
226313db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
226413db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  llvm::Type *args[] = { Int8PtrTy, Int32Ty };
226513db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  llvm::FunctionType *fty
226613db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    = llvm::FunctionType::get(VoidTy, args, false);
226713db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
226813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  configureBlocksRuntimeObject(*this, BlockObjectDispose);
226913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  return BlockObjectDispose;
227013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall}
227113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
227213db5cfc4e5f03eb70efe0d227b53b8280f16161John McCallllvm::Constant *CodeGenModule::getBlockObjectAssign() {
227313db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  if (BlockObjectAssign)
227413db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    return BlockObjectAssign;
227513db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
227613db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
227713db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  llvm::FunctionType *fty
227813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    = llvm::FunctionType::get(VoidTy, args, false);
227913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
228013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  configureBlocksRuntimeObject(*this, BlockObjectAssign);
228113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  return BlockObjectAssign;
228213db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall}
228313db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
228413db5cfc4e5f03eb70efe0d227b53b8280f16161John McCallllvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
228513db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  if (NSConcreteGlobalBlock)
228613db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    return NSConcreteGlobalBlock;
228713db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
228813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
228913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall                                                Int8PtrTy->getPointerTo(), 0);
229013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
229113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  return NSConcreteGlobalBlock;
229213db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall}
229313db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
229413db5cfc4e5f03eb70efe0d227b53b8280f16161John McCallllvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
229513db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  if (NSConcreteStackBlock)
229613db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall    return NSConcreteStackBlock;
229713db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall
229813db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
229913db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall                                               Int8PtrTy->getPointerTo(), 0);
230013db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
230113db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall  return NSConcreteStackBlock;
230213db5cfc4e5f03eb70efe0d227b53b8280f16161John McCall}
2303