#include "CGDebugInfo.h"
#include "CodeGenFunction.h"
#include "CGObjCRuntime.h"
#include "CodeGenModule.h"
#include "CGBlocks.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/Module.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Target/TargetData.h"
#include <algorithm>
using namespace clang;
using namespace CodeGen;
CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
: Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
DominatingIP(0) {
if (!name.empty() && name[0] == '\01')
name = name.substr(1);
}
CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
const CGBlockInfo &blockInfo,
llvm::Constant *blockFn);
static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
}
static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
}
static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
ASTContext &C = CGM.getContext();
llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
SmallVector<llvm::Constant*, 6> elements;
elements.push_back(llvm::ConstantInt::get(ulong, 0));
elements.push_back(llvm::ConstantInt::get(ulong,
blockInfo.BlockSize.getQuantity()));
if (blockInfo.NeedsCopyDispose) {
elements.push_back(buildCopyHelper(CGM, blockInfo));
elements.push_back(buildDisposeHelper(CGM, blockInfo));
}
std::string typeAtEncoding =
CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
elements.push_back(llvm::ConstantExpr::getBitCast(
CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
if (C.getLangOptions().ObjC1)
elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
else
elements.push_back(llvm::Constant::getNullValue(i8p));
llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
llvm::GlobalVariable *global =
new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
llvm::GlobalValue::InternalLinkage,
init, "__block_descriptor_tmp");
return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
}
const unsigned BlockHeaderSize = 5;
namespace {
struct BlockLayoutChunk {
CharUnits Alignment;
CharUnits Size;
const BlockDecl::Capture *Capture; llvm::Type *Type;
BlockLayoutChunk(CharUnits align, CharUnits size,
const BlockDecl::Capture *capture,
llvm::Type *type)
: Alignment(align), Size(size), Capture(capture), Type(type) {}
void setIndex(CGBlockInfo &info, unsigned index) {
if (!Capture)
info.CXXThisIndex = index;
else
info.Captures[Capture->getVariable()]
= CGBlockInfo::Capture::makeIndex(index);
}
};
bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
return left.Alignment > right.Alignment;
}
}
static bool isSafeForCXXConstantCapture(QualType type) {
const RecordType *recordType =
type->getBaseElementTypeUnsafe()->getAs<RecordType>();
if (!recordType) return true;
const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
if (!record->hasTrivialDestructor()) return false;
if (!record->hasTrivialCopyConstructor()) return false;
return !record->hasMutableFields();
}
static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
CodeGenFunction *CGF,
const VarDecl *var) {
QualType type = var->getType();
if (!type.isConstQualified()) return 0;
if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
return 0;
const Expr *init = var->getInit();
if (!init) return 0;
return CGM.EmitConstantInit(*var, CGF);
}
static CharUnits getLowBit(CharUnits v) {
return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
}
static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
SmallVectorImpl<llvm::Type*> &elementTypes) {
ASTContext &C = CGM.getContext();
CharUnits ptrSize, ptrAlign, intSize, intAlign;
llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
assert(intSize <= ptrSize && "layout assumptions horribly violated");
CharUnits headerSize = ptrSize;
if (2 * intSize < ptrAlign) headerSize += ptrSize;
else headerSize += 2 * intSize;
headerSize += 2 * ptrSize;
info.BlockAlign = ptrAlign;
info.BlockSize = headerSize;
assert(elementTypes.empty());
llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
elementTypes.push_back(i8p);
elementTypes.push_back(intTy);
elementTypes.push_back(intTy);
elementTypes.push_back(i8p);
elementTypes.push_back(CGM.getBlockDescriptorType());
assert(elementTypes.size() == BlockHeaderSize);
}
static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
CGBlockInfo &info) {
ASTContext &C = CGM.getContext();
const BlockDecl *block = info.getBlockDecl();
SmallVector<llvm::Type*, 8> elementTypes;
initializeForBlockHeader(CGM, info, elementTypes);
if (!block->hasCaptures()) {
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
info.CanBeGlobal = true;
return;
}
SmallVector<BlockLayoutChunk, 16> layout;
layout.reserve(block->capturesCXXThis() +
(block->capture_end() - block->capture_begin()));
CharUnits maxFieldAlign;
if (block->capturesCXXThis()) {
const DeclContext *DC = block->getDeclContext();
for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
;
QualType thisType;
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
thisType = C.getPointerType(C.getRecordType(RD));
else
thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
std::pair<CharUnits,CharUnits> tinfo
= CGM.getContext().getTypeInfoInChars(thisType);
maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
}
for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
ce = block->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
if (ci->isByRef()) {
info.NeedsCopyDispose = true;
QualType byRefPtrTy = C.VoidPtrTy;
llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
std::pair<CharUnits,CharUnits> tinfo
= CGM.getContext().getTypeInfoInChars(byRefPtrTy);
maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
&*ci, llvmType));
continue;
}
if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
continue;
}
if (Qualifiers::ObjCLifetime lifetime
= variable->getType().getObjCLifetime()) {
switch (lifetime) {
case Qualifiers::OCL_None: llvm_unreachable("impossible");
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
break;
case Qualifiers::OCL_Strong:
case Qualifiers::OCL_Weak:
info.NeedsCopyDispose = true;
}
} else if (variable->getType()->isObjCRetainableType()) {
info.NeedsCopyDispose = true;
} else if (ci->hasCopyExpr()) {
info.NeedsCopyDispose = true;
info.HasCXXObject = true;
} else if (CGM.getLangOptions().CPlusPlus) {
if (const CXXRecordDecl *record =
variable->getType()->getAsCXXRecordDecl()) {
if (!record->hasTrivialDestructor()) {
info.HasCXXObject = true;
info.NeedsCopyDispose = true;
}
}
}
QualType VT = variable->getType();
CharUnits size = C.getTypeSizeInChars(VT);
CharUnits align = C.getDeclAlign(variable);
maxFieldAlign = std::max(maxFieldAlign, align);
llvm::Type *llvmType =
CGM.getTypes().ConvertTypeForMem(VT);
layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
}
if (layout.empty()) {
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
info.CanBeGlobal = true;
return;
}
std::stable_sort(layout.begin(), layout.end());
CharUnits &blockSize = info.BlockSize;
info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
CharUnits endAlign = getLowBit(blockSize);
if (endAlign < maxFieldAlign) {
SmallVectorImpl<BlockLayoutChunk>::iterator
li = layout.begin() + 1, le = layout.end();
for (; li != le && endAlign < li->Alignment; ++li)
;
if (li != le) {
SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
for (; li != le; ++li) {
assert(endAlign >= li->Alignment);
li->setIndex(info, elementTypes.size());
elementTypes.push_back(li->Type);
blockSize += li->Size;
endAlign = getLowBit(blockSize);
if (endAlign >= maxFieldAlign)
break;
}
layout.erase(first, li);
}
}
if (endAlign < maxFieldAlign) {
CharUnits padding = maxFieldAlign - endAlign;
elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
padding.getQuantity()));
blockSize += padding;
endAlign = getLowBit(blockSize);
assert(endAlign >= maxFieldAlign);
}
for (SmallVectorImpl<BlockLayoutChunk>::iterator
li = layout.begin(), le = layout.end(); li != le; ++li) {
assert(endAlign >= li->Alignment);
li->setIndex(info, elementTypes.size());
elementTypes.push_back(li->Type);
blockSize += li->Size;
endAlign = getLowBit(blockSize);
}
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
}
static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
CGBlockInfo &blockInfo =
*new CGBlockInfo(block, CGF.CurFn->getName());
blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
CGF.FirstBlockInfo = &blockInfo;
computeBlockInfo(CGF.CGM, &CGF, blockInfo);
if (blockInfo.CanBeGlobal) return;
blockInfo.Address =
CGF.CreateTempAlloca(blockInfo.StructureType, "block");
blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
if (!blockInfo.NeedsCopyDispose) return;
for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
ce = block->capture_end(); ci != ce; ++ci) {
if (ci->isByRef()) continue;
const VarDecl *variable = ci->getVariable();
CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
QualType::DestructionKind dtorKind =
variable->getType().isDestructedType();
if (dtorKind == QualType::DK_none) continue;
CodeGenFunction::Destroyer *destroyer;
if (dtorKind == QualType::DK_objc_strong_lifetime) {
destroyer = CodeGenFunction::destroyARCStrongImprecise;
} else {
destroyer = CGF.getDestroyer(dtorKind);
}
llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
capture.getIndex());
if (!blockInfo.DominatingIP)
blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
CleanupKind cleanupKind = InactiveNormalCleanup;
bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
if (useArrayEHCleanup)
cleanupKind = InactiveNormalAndEHCleanup;
CGF.pushDestroy(cleanupKind, addr, variable->getType(),
destroyer, useArrayEHCleanup);
capture.setCleanup(CGF.EHStack.stable_begin());
}
}
void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
assert(E->getNumObjects() != 0);
ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
enterBlockScope(*this, *i);
}
}
static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
const BlockDecl *block) {
while (true) {
assert(head && *head);
CGBlockInfo *cur = *head;
if (cur->getBlockDecl() == block) {
*head = cur->NextBlockInfo;
return cur;
}
head = &cur->NextBlockInfo;
}
}
void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
assert(head && "destroying an empty chain");
do {
CGBlockInfo *cur = head;
head = cur->NextBlockInfo;
delete cur;
} while (head != 0);
}
llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
if (!blockExpr->getBlockDecl()->hasCaptures()) {
CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
computeBlockInfo(CGM, this, blockInfo);
blockInfo.BlockExpression = blockExpr;
return EmitBlockLiteral(blockInfo);
}
OwningPtr<CGBlockInfo> blockInfo;
blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
blockExpr->getBlockDecl()));
blockInfo->BlockExpression = blockExpr;
return EmitBlockLiteral(*blockInfo);
}
llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
llvm::Constant *blockFn
= CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
CurFuncDecl, LocalDeclMap,
isLambdaConv);
blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
if (blockInfo.CanBeGlobal)
return buildGlobalBlock(CGM, blockInfo, blockFn);
llvm::Constant *isa = CGM.getNSConcreteStackBlock();
isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
llvm::AllocaInst *blockAddr = blockInfo.Address;
assert(blockAddr && "block has no address!");
BlockFlags flags = BLOCK_HAS_SIGNATURE;
if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
"block.invoke"));
Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
"block.descriptor"));
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
if (blockDecl->capturesCXXThis()) {
llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
blockInfo.CXXThisIndex,
"block.captured-this.addr");
Builder.CreateStore(LoadCXXThis(), addr);
}
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
QualType type = variable->getType();
llvm::Value *blockField =
Builder.CreateStructGEP(blockAddr, capture.getIndex(),
"block.captured");
llvm::Value *src;
if (ci->isNested()) {
const CGBlockInfo::Capture &enclosingCapture =
BlockInfo->getCapture(variable);
src = Builder.CreateStructGEP(LoadBlockStruct(),
enclosingCapture.getIndex(),
"block.capture.addr");
} else if (blockDecl->isConversionFromLambda()) {
src = 0;
} else {
src = LocalDeclMap[variable];
}
if (ci->isByRef()) {
if (ci->isNested())
src = Builder.CreateLoad(src, "byref.capture");
else
src = Builder.CreateBitCast(src, VoidPtrTy);
Builder.CreateStore(src, blockField);
} else if (const Expr *copyExpr = ci->getCopyExpr()) {
if (blockDecl->isConversionFromLambda()) {
CharUnits Align = getContext().getTypeAlignInChars(type);
AggValueSlot Slot =
AggValueSlot::forAddr(blockField, Align, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
EmitAggExpr(copyExpr, Slot);
} else {
EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
}
} else if (type->isReferenceType()) {
Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
} else {
ImplicitParamDecl blockFieldPseudoVar( 0, SourceLocation(),
0, type);
DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
SourceLocation());
BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
VK_LValue, SourceLocation(), false);
Expr *declRef =
(ci->isNested() ? static_cast<Expr*>(&nested) : ¬Nested);
ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
declRef, VK_RValue);
EmitExprAsInit(&l2r, &blockFieldPseudoVar,
MakeAddrLValue(blockField, type,
getContext().getDeclAlign(variable)),
false);
}
if (!ci->isByRef()) {
EHScopeStack::stable_iterator cleanup = capture.getCleanup();
if (cleanup.isValid())
ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
}
}
llvm::Value *result =
Builder.CreateBitCast(blockAddr,
ConvertType(blockInfo.getBlockExpr()->getType()));
return result;
}
llvm::Type *CodeGenModule::getBlockDescriptorType() {
if (BlockDescriptorType)
return BlockDescriptorType;
llvm::Type *UnsignedLongTy =
getTypes().ConvertType(getContext().UnsignedLongTy);
BlockDescriptorType =
llvm::StructType::create("struct.__block_descriptor",
UnsignedLongTy, UnsignedLongTy, NULL);
BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
return BlockDescriptorType;
}
llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
if (GenericBlockLiteralType)
return GenericBlockLiteralType;
llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
GenericBlockLiteralType =
llvm::StructType::create("struct.__block_literal_generic",
VoidPtrTy, IntTy, IntTy, VoidPtrTy,
BlockDescPtrTy, NULL);
return GenericBlockLiteralType;
}
RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
ReturnValueSlot ReturnValue) {
const BlockPointerType *BPT =
E->getCallee()->getType()->getAs<BlockPointerType>();
llvm::Value *Callee = EmitScalarExpr(E->getCallee());
llvm::Type *BlockLiteralTy =
llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
llvm::Value *BlockLiteral =
Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
CallArgList Args;
Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
QualType FnType = BPT->getPointeeType();
EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
E->arg_begin(), E->arg_end());
llvm::Value *Func = Builder.CreateLoad(FuncPtr);
const FunctionType *FuncTy = FnType->castAs<FunctionType>();
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeFunctionCall(Args, FuncTy);
llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Func = Builder.CreateBitCast(Func, BlockFTyPtr);
return EmitCall(FnInfo, Func, ReturnValue, Args);
}
llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
bool isByRef) {
assert(BlockInfo && "evaluating block ref without block information?");
const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
if (capture.isConstant()) return LocalDeclMap[variable];
llvm::Value *addr =
Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
"block.capture.addr");
if (isByRef) {
addr = Builder.CreateLoad(addr);
llvm::PointerType *byrefPointerType
= llvm::PointerType::get(BuildByRefType(variable), 0);
addr = Builder.CreateBitCast(addr, byrefPointerType,
"byref.addr");
addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
addr = Builder.CreateBitCast(addr, byrefPointerType);
addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
variable->getNameAsString());
}
if (variable->getType()->isReferenceType())
addr = Builder.CreateLoad(addr, "ref.tmp");
return addr;
}
llvm::Constant *
CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
const char *name) {
CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
blockInfo.BlockExpression = blockExpr;
computeBlockInfo(*this, 0, blockInfo);
llvm::Constant *blockFn;
{
llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
blockInfo,
0, LocalDeclMap,
false);
}
blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
return buildGlobalBlock(*this, blockInfo, blockFn);
}
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
const CGBlockInfo &blockInfo,
llvm::Constant *blockFn) {
assert(blockInfo.CanBeGlobal);
llvm::Constant *fields[BlockHeaderSize];
fields[0] = CGM.getNSConcreteGlobalBlock();
BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
fields[3] = blockFn;
fields[4] = buildBlockDescriptor(CGM, blockInfo);
llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
llvm::GlobalVariable *literal =
new llvm::GlobalVariable(CGM.getModule(),
init->getType(),
true,
llvm::GlobalVariable::InternalLinkage,
init,
"__block_literal_global");
literal->setAlignment(blockInfo.BlockAlign.getQuantity());
llvm::Type *requiredType =
CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
return llvm::ConstantExpr::getBitCast(literal, requiredType);
}
llvm::Function *
CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
const CGBlockInfo &blockInfo,
const Decl *outerFnDecl,
const DeclMapTy &ldm,
bool IsLambdaConversionToBlock) {
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
if (CGM.getModuleDebugInfo())
DebugInfo = CGM.getModuleDebugInfo();
BlockInfo = &blockInfo;
for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
const VarDecl *var = dyn_cast<VarDecl>(i->first);
if (var && !var->hasLocalStorage())
LocalDeclMap[var] = i->second;
}
FunctionArgList args;
QualType selfTy = getContext().VoidPtrTy;
IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
SourceLocation(), II, selfTy);
args.push_back(&selfDecl);
for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
e = blockDecl->param_end(); i != e; ++i)
args.push_back(*i);
const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
const CGFunctionInfo &fnInfo =
CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
fnType->getExtInfo(),
fnType->isVariadic());
if (CGM.ReturnTypeUsesSRet(fnInfo))
blockInfo.UsesStret = true;
llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
MangleBuffer name;
CGM.getBlockMangledName(GD, name, blockDecl);
llvm::Function *fn =
llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
name.getString(), &CGM.getModule());
CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
blockInfo.getBlockExpr()->getBody()->getLocStart());
CurFuncDecl = outerFnDecl;
llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
LocalDeclMap.erase(&selfDecl);
BlockPointer = Builder.CreateBitCast(blockAddr,
blockInfo.StructureType->getPointerTo(),
"block");
if (blockDecl->capturesCXXThis()) {
llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
blockInfo.CXXThisIndex,
"block.captured-this");
CXXThisValue = Builder.CreateLoad(addr, "this");
}
if (const ObjCMethodDecl *method
= dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
const VarDecl *self = method->getSelfDecl();
if (blockInfo.Captures.count(self)) {
const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
capture.getIndex(),
"block.captured-self");
LocalDeclMap[self] = selfAddr;
}
}
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (!capture.isConstant()) continue;
unsigned align = getContext().getDeclAlign(variable).getQuantity();
llvm::AllocaInst *alloca =
CreateMemTemp(variable->getType(), "block.captured-const");
alloca->setAlignment(align);
Builder.CreateStore(capture.getConstant(), alloca, align);
LocalDeclMap[variable] = alloca;
}
llvm::BasicBlock *entry = Builder.GetInsertBlock();
llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
--entry_ptr;
if (IsLambdaConversionToBlock)
EmitLambdaBlockInvokeBody();
else
EmitStmt(blockDecl->getBody());
llvm::BasicBlock *resume = Builder.GetInsertBlock();
++entry_ptr;
Builder.SetInsertPoint(entry, entry_ptr);
if (CGDebugInfo *DI = getDebugInfo()) {
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
DI->EmitLocation(Builder, variable->getLocation());
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) {
DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
Builder);
continue;
}
DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
Builder, blockInfo);
}
}
if (resume == 0)
Builder.ClearInsertionPoint();
else
Builder.SetInsertPoint(resume);
FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
return fn;
}
llvm::Constant *
CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
ASTContext &C = getContext();
FunctionArgList args;
ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
args.push_back(&dstDecl);
ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
args.push_back(&srcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
FunctionType::ExtInfo(),
false);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__copy_helper_block_", &CGM.getModule());
IdentifierInfo *II
= &CGM.getContext().Idents.get("__copy_helper_block_");
if (CGM.getModuleDebugInfo())
DebugInfo = CGM.getModuleDebugInfo();
FunctionDecl *FD = FunctionDecl::Create(C,
C.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, C.VoidTy, 0,
SC_Static,
SC_None,
false,
true);
StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
src = Builder.CreateLoad(src);
src = Builder.CreateBitCast(src, structPtrTy, "block.source");
llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
dst = Builder.CreateLoad(dst);
dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
QualType type = variable->getType();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
const Expr *copyExpr = ci->getCopyExpr();
BlockFieldFlags flags;
bool isARCWeakCapture = false;
if (copyExpr) {
assert(!ci->isByRef());
} else if (ci->isByRef()) {
flags = BLOCK_FIELD_IS_BYREF;
if (type.isObjCGCWeak())
flags |= BLOCK_FIELD_IS_WEAK;
} else if (type->isObjCRetainableType()) {
flags = BLOCK_FIELD_IS_OBJECT;
if (type->isBlockPointerType())
flags = BLOCK_FIELD_IS_BLOCK;
if (getLangOptions().ObjCAutoRefCount) {
Qualifiers qs = type.getQualifiers();
if (!qs.hasStrongOrWeakObjCLifetime())
continue;
if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
isARCWeakCapture = true;
}
} else {
continue;
}
unsigned index = capture.getIndex();
llvm::Value *srcField = Builder.CreateStructGEP(src, index);
llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
if (copyExpr) {
EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
} else if (isARCWeakCapture) {
EmitARCCopyWeak(dstField, srcField);
} else {
llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
}
}
FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
}
llvm::Constant *
CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
ASTContext &C = getContext();
FunctionArgList args;
ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
args.push_back(&srcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
FunctionType::ExtInfo(),
false);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__destroy_helper_block_", &CGM.getModule());
if (CGM.getModuleDebugInfo())
DebugInfo = CGM.getModuleDebugInfo();
IdentifierInfo *II
= &CGM.getContext().Idents.get("__destroy_helper_block_");
FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, C.VoidTy, 0,
SC_Static,
SC_None,
false, true);
StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
src = Builder.CreateLoad(src);
src = Builder.CreateBitCast(src, structPtrTy, "block");
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
CodeGenFunction::RunCleanupsScope cleanups(*this);
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
QualType type = variable->getType();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
BlockFieldFlags flags;
const CXXDestructorDecl *dtor = 0;
bool isARCWeakCapture = false;
if (ci->isByRef()) {
flags = BLOCK_FIELD_IS_BYREF;
if (type.isObjCGCWeak())
flags |= BLOCK_FIELD_IS_WEAK;
} else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
if (record->hasTrivialDestructor())
continue;
dtor = record->getDestructor();
} else if (type->isObjCRetainableType()) {
flags = BLOCK_FIELD_IS_OBJECT;
if (type->isBlockPointerType())
flags = BLOCK_FIELD_IS_BLOCK;
if (getLangOptions().ObjCAutoRefCount) {
Qualifiers qs = type.getQualifiers();
if (!qs.hasStrongOrWeakObjCLifetime())
continue;
if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
isARCWeakCapture = true;
}
} else {
continue;
}
unsigned index = capture.getIndex();
llvm::Value *srcField = Builder.CreateStructGEP(src, index);
if (dtor) {
PushDestructorCleanup(dtor, srcField);
} else if (isARCWeakCapture) {
EmitARCDestroyWeak(srcField);
} else {
llvm::Value *value = Builder.CreateLoad(srcField);
value = Builder.CreateBitCast(value, VoidPtrTy);
BuildBlockRelease(value, flags);
}
}
cleanups.ForceCleanup();
FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
}
namespace {
class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
BlockFieldFlags Flags;
public:
ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
: ByrefHelpers(alignment), Flags(flags) {}
void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
llvm::Value *srcField) {
destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
}
void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
llvm::Value *value = CGF.Builder.CreateLoad(field);
CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
}
void profileImpl(llvm::FoldingSetNodeID &id) const {
id.AddInteger(Flags.getBitMask());
}
};
class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
public:
ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
llvm::Value *srcField) {
CGF.EmitARCMoveWeak(destField, srcField);
}
void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
CGF.EmitARCDestroyWeak(field);
}
void profileImpl(llvm::FoldingSetNodeID &id) const {
id.AddInteger(0);
}
};
class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
public:
ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
llvm::Value *srcField) {
llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
value->setAlignment(Alignment.getQuantity());
llvm::Value *null =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
store->setAlignment(Alignment.getQuantity());
store = CGF.Builder.CreateStore(null, srcField);
store->setAlignment(Alignment.getQuantity());
}
void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
value->setAlignment(Alignment.getQuantity());
CGF.EmitARCRelease(value, false);
}
void profileImpl(llvm::FoldingSetNodeID &id) const {
id.AddInteger(1);
}
};
class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
public:
ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
llvm::Value *srcField) {
llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
oldValue->setAlignment(Alignment.getQuantity());
llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, true);
llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
store->setAlignment(Alignment.getQuantity());
}
void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
value->setAlignment(Alignment.getQuantity());
CGF.EmitARCRelease(value, false);
}
void profileImpl(llvm::FoldingSetNodeID &id) const {
id.AddInteger(2);
}
};
class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
QualType VarType;
const Expr *CopyExpr;
public:
CXXByrefHelpers(CharUnits alignment, QualType type,
const Expr *copyExpr)
: ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
bool needsCopy() const { return CopyExpr != 0; }
void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
llvm::Value *srcField) {
if (!CopyExpr) return;
CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
}
void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
CGF.PushDestructorCleanup(VarType, field);
CGF.PopCleanupBlocks(cleanupDepth);
}
void profileImpl(llvm::FoldingSetNodeID &id) const {
id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
}
};
}
static llvm::Constant *
generateByrefCopyHelper(CodeGenFunction &CGF,
llvm::StructType &byrefType,
CodeGenModule::ByrefHelpers &byrefInfo) {
ASTContext &Context = CGF.getContext();
QualType R = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
args.push_back(&dst);
ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
args.push_back(&src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
FunctionType::ExtInfo(),
false);
CodeGenTypes &Types = CGF.CGM.getTypes();
llvm::FunctionType *LTy = Types.GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__Block_byref_object_copy_", &CGF.CGM.getModule());
IdentifierInfo *II
= &Context.Idents.get("__Block_byref_object_copy_");
FunctionDecl *FD = FunctionDecl::Create(Context,
Context.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, R, 0,
SC_Static,
SC_None,
false, true);
CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
if (byrefInfo.needsCopy()) {
llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
destField = CGF.Builder.CreateLoad(destField);
destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
srcField = CGF.Builder.CreateLoad(srcField);
srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
byrefInfo.emitCopy(CGF, destField, srcField);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
llvm::StructType &byrefType,
CodeGenModule::ByrefHelpers &info) {
CodeGenFunction CGF(CGM);
return generateByrefCopyHelper(CGF, byrefType, info);
}
static llvm::Constant *
generateByrefDisposeHelper(CodeGenFunction &CGF,
llvm::StructType &byrefType,
CodeGenModule::ByrefHelpers &byrefInfo) {
ASTContext &Context = CGF.getContext();
QualType R = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
args.push_back(&src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
FunctionType::ExtInfo(),
false);
CodeGenTypes &Types = CGF.CGM.getTypes();
llvm::FunctionType *LTy = Types.GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__Block_byref_object_dispose_",
&CGF.CGM.getModule());
IdentifierInfo *II
= &Context.Idents.get("__Block_byref_object_dispose_");
FunctionDecl *FD = FunctionDecl::Create(Context,
Context.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, R, 0,
SC_Static,
SC_None,
false, true);
CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
if (byrefInfo.needsDispose()) {
llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
V = CGF.Builder.CreateLoad(V);
V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
V = CGF.Builder.CreateStructGEP(V, 6, "x");
byrefInfo.emitDispose(CGF, V);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
llvm::StructType &byrefType,
CodeGenModule::ByrefHelpers &info) {
CodeGenFunction CGF(CGM);
return generateByrefDisposeHelper(CGF, byrefType, info);
}
template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
llvm::StructType &byrefTy,
T &byrefInfo) {
byrefInfo.Alignment = std::max(byrefInfo.Alignment,
CharUnits::fromQuantity(CGM.PointerAlignInBytes));
llvm::FoldingSetNodeID id;
byrefInfo.Profile(id);
void *insertPos;
CodeGenModule::ByrefHelpers *node
= CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
if (node) return static_cast<T*>(node);
byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
T *copy = new (CGM.getContext()) T(byrefInfo);
CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
return copy;
}
CodeGenModule::ByrefHelpers *
CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
const AutoVarEmission &emission) {
const VarDecl &var = *emission.Variable;
QualType type = var.getType();
if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
if (!copyExpr && record->hasTrivialDestructor()) return 0;
CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
}
if (!type->isObjCRetainableType()) return 0;
Qualifiers qs = type.getQualifiers();
if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
assert(getLangOptions().ObjCAutoRefCount);
switch (lifetime) {
case Qualifiers::OCL_None: llvm_unreachable("impossible");
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
return 0;
case Qualifiers::OCL_Weak: {
ARCWeakByrefHelpers byrefInfo(emission.Alignment);
return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
}
case Qualifiers::OCL_Strong:
if (type->isBlockPointerType()) {
ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
} else {
ARCStrongByrefHelpers byrefInfo(emission.Alignment);
return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
}
}
llvm_unreachable("fell out of lifetime switch!");
}
BlockFieldFlags flags;
if (type->isBlockPointerType()) {
flags |= BLOCK_FIELD_IS_BLOCK;
} else if (CGM.getContext().isObjCNSObjectType(type) ||
type->isObjCObjectPointerType()) {
flags |= BLOCK_FIELD_IS_OBJECT;
} else {
return 0;
}
if (type.isObjCGCWeak())
flags |= BLOCK_FIELD_IS_WEAK;
ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
}
unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
assert(ByRefValueInfo.count(VD) && "Did not find value!");
return ByRefValueInfo.find(VD)->second.second;
}
llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
const VarDecl *V) {
llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
Loc = Builder.CreateLoad(Loc);
Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
V->getNameAsString());
return Loc;
}
llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
if (Info.first)
return Info.first;
QualType Ty = D->getType();
SmallVector<llvm::Type *, 8> types;
llvm::StructType *ByRefType =
llvm::StructType::create(getLLVMContext(),
"struct.__block_byref_" + D->getNameAsString());
types.push_back(Int8PtrTy);
types.push_back(llvm::PointerType::getUnqual(ByRefType));
types.push_back(Int32Ty);
types.push_back(Int32Ty);
bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
if (HasCopyAndDispose) {
types.push_back(Int8PtrTy);
types.push_back(Int8PtrTy);
}
bool Packed = false;
CharUnits Align = getContext().getDeclAlign(D);
if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
unsigned CurrentOffsetInBytes = 4 * 2;
CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
unsigned AlignedOffsetInBytes =
llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
if (NumPaddingBytes > 0) {
llvm::Type *Ty = Int8Ty;
if (NumPaddingBytes > 1)
Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
types.push_back(Ty);
Packed = true;
}
}
types.push_back(ConvertTypeForMem(Ty));
ByRefType->setBody(types, Packed);
Info.first = ByRefType;
Info.second = types.size() - 1;
return Info.first;
}
void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
llvm::Value *addr = emission.Address;
llvm::StructType *byrefType = cast<llvm::StructType>(
cast<llvm::PointerType>(addr->getType())->getElementType());
CodeGenModule::ByrefHelpers *helpers =
buildByrefHelpers(*byrefType, emission);
const VarDecl &D = *emission.Variable;
QualType type = D.getType();
llvm::Value *V;
int isa = 0;
if (type.isObjCGCWeak())
isa = 1;
V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
Builder.CreateStore(addr,
Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
BlockFlags flags;
if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
Builder.CreateStructGEP(addr, 2, "byref.flags"));
CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
if (helpers) {
llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
Builder.CreateStore(helpers->CopyHelper, copy_helper);
llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
}
}
void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
llvm::Value *F = CGM.getBlockObjectDispose();
llvm::Value *N;
V = Builder.CreateBitCast(V, Int8PtrTy);
N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Builder.CreateCall2(F, V, N);
}
namespace {
struct CallBlockRelease : EHScopeStack::Cleanup {
llvm::Value *Addr;
CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
void Emit(CodeGenFunction &CGF, Flags flags) {
CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
}
};
}
void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
return;
EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
}
static void configureBlocksRuntimeObject(CodeGenModule &CGM,
llvm::Constant *C) {
if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
if (GV->isDeclaration() &&
GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
}
llvm::Constant *CodeGenModule::getBlockObjectDispose() {
if (BlockObjectDispose)
return BlockObjectDispose;
llvm::Type *args[] = { Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
configureBlocksRuntimeObject(*this, BlockObjectDispose);
return BlockObjectDispose;
}
llvm::Constant *CodeGenModule::getBlockObjectAssign() {
if (BlockObjectAssign)
return BlockObjectAssign;
llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
configureBlocksRuntimeObject(*this, BlockObjectAssign);
return BlockObjectAssign;
}
llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
if (NSConcreteGlobalBlock)
return NSConcreteGlobalBlock;
NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Int8PtrTy->getPointerTo(), 0);
configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
return NSConcreteGlobalBlock;
}
llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
if (NSConcreteStackBlock)
return NSConcreteStackBlock;
NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Int8PtrTy->getPointerTo(), 0);
configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
return NSConcreteStackBlock;
}