#include "CGBlocks.h"
#include "CGDebugInfo.h"
#include "CGObjCRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include <algorithm>
#include <cstdio>
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), HasCapturedVariableLayout(false),
LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
DominatingIP(nullptr) {
if (!name.empty() && name[0] == '\01')
name = name.substr(1);
}
BlockByrefHelpers::~BlockByrefHelpers() {}
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 = nullptr;
if (CGM.getLangOpts().OpenCL)
i8p =
llvm::Type::getInt8PtrTy(
CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
else
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).getPointer(), i8p));
if (C.getLangOpts().ObjC1) {
if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
else
elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(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;
Qualifiers::ObjCLifetime Lifetime;
const BlockDecl::Capture *Capture; llvm::Type *Type;
BlockLayoutChunk(CharUnits align, CharUnits size,
Qualifiers::ObjCLifetime lifetime,
const BlockDecl::Capture *capture,
llvm::Type *type)
: Alignment(align), Size(size), Lifetime(lifetime),
Capture(capture), Type(type) {}
void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
if (!Capture) {
info.CXXThisIndex = index;
info.CXXThisOffset = offset;
} else {
info.Captures.insert({Capture->getVariable(),
CGBlockInfo::Capture::makeIndex(index, offset)});
}
}
};
bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
if (left.Alignment != right.Alignment)
return left.Alignment > right.Alignment;
auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
if (chunk.Capture && chunk.Capture->isByRef())
return 1;
if (chunk.Lifetime == Qualifiers::OCL_Strong)
return 0;
if (chunk.Lifetime == Qualifiers::OCL_Weak)
return 2;
return 3;
};
return getPrefOrder(left) < getPrefOrder(right);
}
}
static bool isSafeForCXXConstantCapture(QualType type) {
const RecordType *recordType =
type->getBaseElementTypeUnsafe()->getAs<RecordType>();
if (!recordType) return true;
const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
if (!record->hasTrivialDestructor()) return false;
if (record->hasNonTrivialCopyConstructor()) return false;
return !record->hasMutableFields();
}
static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
CodeGenFunction *CGF,
const VarDecl *var) {
if (isa<ParmVarDecl>(var))
return nullptr;
QualType type = var->getType();
if (!type.isConstQualified()) return nullptr;
if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
return nullptr;
const Expr *init = var->getInit();
if (!init) return nullptr;
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) {
assert(CGM.getIntSize() <= CGM.getPointerSize());
assert(CGM.getIntAlign() <= CGM.getPointerAlign());
assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
info.BlockAlign = CGM.getPointerAlign();
info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
assert(elementTypes.empty());
elementTypes.push_back(CGM.VoidPtrTy);
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(CGM.VoidPtrTy);
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;
}
else if (C.getLangOpts().ObjC1 &&
CGM.getLangOpts().getGC() == LangOptions::NonGC)
info.HasCapturedVariableLayout = true;
SmallVector<BlockLayoutChunk, 16> layout;
layout.reserve(block->capturesCXXThis() +
(block->capture_end() - block->capture_begin()));
CharUnits maxFieldAlign;
if (block->capturesCXXThis()) {
assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
"Can't capture 'this' outside a method");
QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->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,
Qualifiers::OCL_None,
nullptr, llvmType));
}
for (const auto &CI : block->captures()) {
const VarDecl *variable = CI.getVariable();
if (CI.isByRef()) {
info.NeedsCopyDispose = true;
CharUnits align = CGM.getPointerAlign();
maxFieldAlign = std::max(maxFieldAlign, align);
layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
Qualifiers::OCL_None, &CI,
CGM.VoidPtrTy));
continue;
}
if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
continue;
}
Qualifiers::ObjCLifetime lifetime =
variable->getType().getObjCLifetime();
if (lifetime) {
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()) {
if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
lifetime = Qualifiers::OCL_ExplicitNone;
} else {
info.NeedsCopyDispose = true;
lifetime = Qualifiers::OCL_Strong;
}
} else if (CI.hasCopyExpr()) {
info.NeedsCopyDispose = true;
info.HasCXXObject = true;
} else if (CGM.getLangOpts().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, lifetime, &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());
info.BlockHeaderForcedGapOffset = info.BlockSize;
info.BlockHeaderForcedGapSize = CharUnits::Zero();
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(), blockSize);
elementTypes.push_back(li->Type);
blockSize += li->Size;
endAlign = getLowBit(blockSize);
if (endAlign >= maxFieldAlign) {
break;
}
}
layout.erase(first, li);
}
}
assert(endAlign == getLowBit(blockSize));
if (endAlign < maxFieldAlign) {
CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
CharUnits padding = newBlockSize - blockSize;
if (blockSize == info.BlockHeaderForcedGapOffset) {
info.BlockHeaderForcedGapSize = padding;
}
elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
padding.getQuantity()));
blockSize = newBlockSize;
endAlign = getLowBit(blockSize); }
assert(endAlign >= maxFieldAlign);
assert(endAlign == getLowBit(blockSize));
for (SmallVectorImpl<BlockLayoutChunk>::iterator
li = layout.begin(), le = layout.end(); li != le; ++li) {
if (endAlign < li->Alignment) {
CharUnits padding = li->Alignment - endAlign;
elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
padding.getQuantity()));
blockSize += padding;
endAlign = getLowBit(blockSize);
}
assert(endAlign >= li->Alignment);
li->setIndex(info, elementTypes.size(), blockSize);
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) {
assert(CGF.HaveInsertPoint());
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.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
blockInfo.BlockAlign, "block");
if (!blockInfo.NeedsCopyDispose) return;
for (const auto &CI : block->captures()) {
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);
}
Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
capture.getIndex(),
capture.getOffset());
if (!blockInfo.DominatingIP)
blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
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 != nullptr);
}
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);
}
std::unique_ptr<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, true).GenerateBlockFunction(CurGD, blockInfo,
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);
Address blockAddr = blockInfo.LocalAddress;
assert(blockAddr.isValid() && "block has no address!");
BlockFlags flags = BLOCK_HAS_SIGNATURE;
if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
auto projectField =
[&](unsigned index, CharUnits offset, const Twine &name) -> Address {
return Builder.CreateStructGEP(blockAddr, index, offset, name);
};
auto storeField =
[&](llvm::Value *value, unsigned index, CharUnits offset,
const Twine &name) {
Builder.CreateStore(value, projectField(index, offset, name));
};
{
unsigned index = 0;
CharUnits offset;
auto addHeaderField =
[&](llvm::Value *value, CharUnits size, const Twine &name) {
storeField(value, index, offset, name);
offset += size;
index++;
};
addHeaderField(isa, getPointerSize(), "block.isa");
addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
getIntSize(), "block.flags");
addHeaderField(llvm::ConstantInt::get(IntTy, 0),
getIntSize(), "block.reserved");
addHeaderField(blockFn, getPointerSize(), "block.invoke");
addHeaderField(descriptor, getPointerSize(), "block.descriptor");
}
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
if (blockDecl->capturesCXXThis()) {
Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
"block.captured-this.addr");
Builder.CreateStore(LoadCXXThis(), addr);
}
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
QualType type = variable->getType();
Address blockField =
projectField(capture.getIndex(), capture.getOffset(), "block.captured");
Address src = Address::invalid();
if (blockDecl->isConversionFromLambda()) {
src = Address::invalid();
} else if (CI.isByRef()) {
if (BlockInfo && CI.isNested()) {
const CGBlockInfo::Capture &enclosingCapture =
BlockInfo->getCapture(variable);
src = Builder.CreateStructGEP(LoadBlockStruct(),
enclosingCapture.getIndex(),
enclosingCapture.getOffset(),
"block.capture.addr");
} else {
auto I = LocalDeclMap.find(variable);
assert(I != LocalDeclMap.end());
src = I->second;
}
} else {
DeclRefExpr declRef(const_cast<VarDecl *>(variable),
CI.isNested(),
type.getNonReferenceType(), VK_LValue,
SourceLocation());
src = EmitDeclRefLValue(&declRef).getAddress();
};
if (CI.isByRef()) {
llvm::Value *byrefPointer;
if (CI.isNested())
byrefPointer = Builder.CreateLoad(src, "byref.capture");
else
byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
Builder.CreateStore(byrefPointer, blockField);
} else if (const Expr *copyExpr = CI.getCopyExpr()) {
if (blockDecl->isConversionFromLambda()) {
AggValueSlot Slot =
AggValueSlot::forAddr(blockField, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
EmitAggExpr(copyExpr, Slot);
} else {
EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
}
} else if (type->isReferenceType()) {
Builder.CreateStore(src.getPointer(), blockField);
} else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
type->isBlockPointerType()) {
llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
value = EmitARCRetainNonBlock(value);
Builder.CreateStore(value, blockField);
} else {
ImplicitParamDecl blockFieldPseudoVar(getContext(), nullptr,
SourceLocation(), nullptr,
type);
DeclRefExpr declRef(const_cast<VarDecl *>(variable),
CI.isNested(),
type, VK_LValue, SourceLocation());
ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
&declRef, VK_RValue);
EmitExprAsInit(&l2r, &blockFieldPseudoVar,
MakeAddrLValue(blockField, type, AlignmentSource::Decl),
false);
}
if (!CI.isByRef()) {
EHScopeStack::stable_iterator cleanup = capture.getCleanup();
if (cleanup.isValid())
ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
}
}
llvm::Value *result =
Builder.CreateBitCast(blockAddr.getPointer(),
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, nullptr);
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, nullptr);
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(CGM.getGenericBlockLiteralType(), 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->arguments());
llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
const FunctionType *FuncTy = FnType->castAs<FunctionType>();
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeBlockFunctionCall(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);
}
Address 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.find(variable)->second;
Address addr =
Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
capture.getOffset(), "block.capture.addr");
if (isByRef) {
auto &byrefInfo = getBlockByrefInfo(variable);
addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
addr = emitBlockByrefAddress(addr, byrefInfo, true,
variable->getName());
}
if (auto refType = variable->getType()->getAs<ReferenceType>()) {
addr = EmitLoadOfReference(addr, refType);
}
return addr;
}
llvm::Constant *
CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
const char *name) {
CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
blockInfo.BlockExpression = blockExpr;
computeBlockInfo(*this, nullptr, blockInfo);
llvm::Constant *blockFn;
{
CodeGenFunction::DeclMapTy LocalDeclMap;
blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
blockInfo,
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);
}
void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
unsigned argNum,
llvm::Value *arg) {
assert(BlockInfo && "not emitting prologue of block invocation function?!");
llvm::Value *localAddr = nullptr;
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
Builder.CreateStore(arg, alloc);
localAddr = Builder.CreateLoad(alloc);
}
if (CGDebugInfo *DI = getDebugInfo()) {
if (CGM.getCodeGenOpts().getDebugInfo() >=
codegenoptions::LimitedDebugInfo) {
DI->setLocation(D->getLocation());
DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
localAddr, Builder);
}
}
SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
ApplyDebugLocation Scope(*this, StartLoc);
BlockPointer = Builder.CreateBitCast(arg,
BlockInfo->StructureType->getPointerTo(),
"block");
}
Address CodeGenFunction::LoadBlockStruct() {
assert(BlockInfo && "not in a block invocation function!");
assert(BlockPointer && "no block pointer set!");
return Address(BlockPointer, BlockInfo->BlockAlign);
}
llvm::Function *
CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
const CGBlockInfo &blockInfo,
const DeclMapTy &ldm,
bool IsLambdaConversionToBlock) {
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
CurGD = GD;
CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
BlockInfo = &blockInfo;
for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
const auto *var = dyn_cast<VarDecl>(i->first);
if (var && !var->hasLocalStorage())
setAddrOfLocalVar(var, i->second);
}
FunctionArgList args;
QualType selfTy = getContext().VoidPtrTy;
IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
SourceLocation(), II, selfTy);
args.push_back(&selfDecl);
args.append(blockDecl->param_begin(), blockDecl->param_end());
const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
const CGFunctionInfo &fnInfo =
CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
blockInfo.UsesStret = true;
llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
StringRef name = CGM.getBlockMangledName(GD, blockDecl);
llvm::Function *fn = llvm::Function::Create(
fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
blockDecl->getLocation(),
blockInfo.getBlockExpr()->getBody()->getLocStart());
llvm::Value *BlockPointerDbgLoc = BlockPointer;
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Address Alloca = CreateTempAlloca(BlockPointer->getType(),
getPointerAlign(),
"block.addr");
auto NL = ApplyDebugLocation::CreateEmpty(*this);
Builder.CreateStore(BlockPointer, Alloca);
BlockPointerDbgLoc = Alloca.getPointer();
}
if (blockDecl->capturesCXXThis()) {
Address addr =
Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
blockInfo.CXXThisOffset, "block.captured-this");
CXXThisValue = Builder.CreateLoad(addr, "this");
}
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (!capture.isConstant()) continue;
CharUnits align = getContext().getDeclAlign(variable);
Address alloca =
CreateMemTemp(variable->getType(), align, "block.captured-const");
Builder.CreateStore(capture.getConstant(), alloca);
setAddrOfLocalVar(variable, alloca);
}
llvm::BasicBlock *entry = Builder.GetInsertBlock();
llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
--entry_ptr;
if (IsLambdaConversionToBlock)
EmitLambdaBlockInvokeBody();
else {
PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
incrementProfileCounter(blockDecl->getBody());
EmitStmt(blockDecl->getBody());
}
llvm::BasicBlock *resume = Builder.GetInsertBlock();
++entry_ptr;
Builder.SetInsertPoint(entry, entry_ptr);
if (CGDebugInfo *DI = getDebugInfo()) {
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
DI->EmitLocation(Builder, variable->getLocation());
if (CGM.getCodeGenOpts().getDebugInfo() >=
codegenoptions::LimitedDebugInfo) {
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) {
auto addr = LocalDeclMap.find(variable)->second;
DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Builder);
continue;
}
DI->EmitDeclareOfBlockDeclRefVariable(
variable, BlockPointerDbgLoc, Builder, blockInfo,
entry_ptr == entry->end() ? nullptr : &*entry_ptr);
}
}
DI->EmitLocation(Builder,
cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
}
if (resume == nullptr)
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(getContext(), nullptr, SourceLocation(), nullptr,
C.VoidPtrTy);
args.push_back(&dstDecl);
ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
C.VoidPtrTy);
args.push_back(&srcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
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_");
FunctionDecl *FD = FunctionDecl::Create(C,
C.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, C.VoidTy,
nullptr, SC_Static,
false,
false);
CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(FD, C.VoidTy, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Address src = GetAddrOfLocalVar(&srcDecl);
src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Address dst = GetAddrOfLocalVar(&dstDecl);
dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
for (const auto &CI : blockDecl->captures()) {
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 useARCWeakCopy = false;
bool useARCStrongCopy = 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;
bool isBlockPointer = type->isBlockPointerType();
if (isBlockPointer)
flags = BLOCK_FIELD_IS_BLOCK;
Qualifiers qs = type.getQualifiers();
if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
useARCWeakCopy = true;
} else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
if (!isBlockPointer)
useARCStrongCopy = true;
} else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
} else {
continue;
}
} else {
continue;
}
unsigned index = capture.getIndex();
Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
if (copyExpr) {
EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
} else if (useARCWeakCopy) {
EmitARCCopyWeak(dstField, srcField);
} else {
llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
if (useARCStrongCopy) {
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
auto *ty = cast<llvm::PointerType>(srcValue->getType());
llvm::Value *null = llvm::ConstantPointerNull::get(ty);
Builder.CreateStore(null, dstField);
EmitARCStoreStrongCall(dstField, srcValue, true);
} else {
EmitARCRetainNonBlock(srcValue);
cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
}
} else {
srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
llvm::Value *dstAddr =
Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
llvm::Value *args[] = {
dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
};
bool copyCanThrow = false;
if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
const Expr *copyExpr =
CGM.getContext().getBlockVarCopyInits(variable);
if (copyExpr) {
copyCanThrow = true; }
}
if (copyCanThrow) {
EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
} else {
EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
}
}
}
}
FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
}
llvm::Constant *
CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
ASTContext &C = getContext();
FunctionArgList args;
ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
C.VoidPtrTy);
args.push_back(&srcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__destroy_helper_block_", &CGM.getModule());
IdentifierInfo *II
= &CGM.getContext().Idents.get("__destroy_helper_block_");
FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
SourceLocation(),
SourceLocation(), II, C.VoidTy,
nullptr, SC_Static,
false, false);
CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(FD, C.VoidTy, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Address src = GetAddrOfLocalVar(&srcDecl);
src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
src = Builder.CreateBitCast(src, structPtrTy, "block");
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
CodeGenFunction::RunCleanupsScope cleanups(*this);
for (const auto &CI : blockDecl->captures()) {
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 = nullptr;
bool useARCWeakDestroy = false;
bool useARCStrongDestroy = 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;
Qualifiers qs = type.getQualifiers();
if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
useARCStrongDestroy = true;
} else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
useARCWeakDestroy = true;
} else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
} else {
continue;
}
} else {
continue;
}
Address srcField =
Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
if (dtor) {
PushDestructorCleanup(dtor, srcField);
} else if (useARCWeakDestroy) {
EmitARCDestroyWeak(srcField);
} else if (useARCStrongDestroy) {
EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
} 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 final : public BlockByrefHelpers {
BlockFieldFlags Flags;
public:
ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
: BlockByrefHelpers(alignment), Flags(flags) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
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();
llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
CGF.EmitNounwindRuntimeCall(fn, args);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
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 override {
id.AddInteger(Flags.getBitMask());
}
};
class ARCWeakByrefHelpers final : public BlockByrefHelpers {
public:
ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
CGF.EmitARCMoveWeak(destField, srcField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyWeak(field);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(0);
}
};
class ARCStrongByrefHelpers final : public BlockByrefHelpers {
public:
ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
llvm::Value *value = CGF.Builder.CreateLoad(srcField);
llvm::Value *null =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
CGF.Builder.CreateStore(null, destField);
CGF.EmitARCStoreStrongCall(destField, value, true);
CGF.EmitARCStoreStrongCall(srcField, null, true);
return;
}
CGF.Builder.CreateStore(value, destField);
CGF.Builder.CreateStore(null, srcField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(1);
}
};
class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
public:
ARCStrongBlockByrefHelpers(CharUnits alignment)
: BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, true);
CGF.Builder.CreateStore(copy, destField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(2);
}
};
class CXXByrefHelpers final : public BlockByrefHelpers {
QualType VarType;
const Expr *CopyExpr;
public:
CXXByrefHelpers(CharUnits alignment, QualType type,
const Expr *copyExpr)
: BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
bool needsCopy() const override { return CopyExpr != nullptr; }
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
if (!CopyExpr) return;
CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
CGF.PushDestructorCleanup(VarType, field);
CGF.PopCleanupBlocks(cleanupDepth);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
}
};
}
static llvm::Constant *
generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
ASTContext &Context = CGF.getContext();
QualType R = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Context.VoidPtrTy);
args.push_back(&dst);
ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Context.VoidPtrTy);
args.push_back(&src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
llvm::FunctionType *LTy = CGF.CGM.getTypes().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, nullptr,
SC_Static,
false, false);
CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
CGF.StartFunction(FD, R, Fn, FI, args);
if (generator.needsCopy()) {
llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Address destField = CGF.GetAddrOfLocalVar(&dst);
destField = Address(CGF.Builder.CreateLoad(destField),
byrefInfo.ByrefAlignment);
destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
"dest-object");
Address srcField = CGF.GetAddrOfLocalVar(&src);
srcField = Address(CGF.Builder.CreateLoad(srcField),
byrefInfo.ByrefAlignment);
srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
"src-object");
generator.emitCopy(CGF, destField, srcField);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
CodeGenFunction CGF(CGM);
return generateByrefCopyHelper(CGF, byrefInfo, generator);
}
static llvm::Constant *
generateByrefDisposeHelper(CodeGenFunction &CGF,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
ASTContext &Context = CGF.getContext();
QualType R = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Context.VoidPtrTy);
args.push_back(&src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
llvm::FunctionType *LTy = CGF.CGM.getTypes().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, nullptr,
SC_Static,
false, false);
CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
CGF.StartFunction(FD, R, Fn, FI, args);
if (generator.needsDispose()) {
Address addr = CGF.GetAddrOfLocalVar(&src);
addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
generator.emitDispose(CGF, addr);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
CodeGenFunction CGF(CGM);
return generateByrefDisposeHelper(CGF, byrefInfo, generator);
}
template <class T>
static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
T &&generator) {
llvm::FoldingSetNodeID id;
generator.Profile(id);
void *insertPos;
BlockByrefHelpers *node
= CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
if (node) return static_cast<T*>(node);
generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
T *copy = new (CGM.getContext()) T(std::move(generator));
CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
return copy;
}
BlockByrefHelpers *
CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
const AutoVarEmission &emission) {
const VarDecl &var = *emission.Variable;
QualType type = var.getType();
auto &byrefInfo = getBlockByrefInfo(&var);
CharUnits valueAlignment =
byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
return ::buildByrefHelpers(
CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
}
if (!type->isObjCRetainableType()) return nullptr;
Qualifiers qs = type.getQualifiers();
if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
switch (lifetime) {
case Qualifiers::OCL_None: llvm_unreachable("impossible");
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
return nullptr;
case Qualifiers::OCL_Weak:
return ::buildByrefHelpers(CGM, byrefInfo,
ARCWeakByrefHelpers(valueAlignment));
case Qualifiers::OCL_Strong:
if (type->isBlockPointerType()) {
return ::buildByrefHelpers(CGM, byrefInfo,
ARCStrongBlockByrefHelpers(valueAlignment));
} else {
return ::buildByrefHelpers(CGM, byrefInfo,
ARCStrongByrefHelpers(valueAlignment));
}
}
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 nullptr;
}
if (type.isObjCGCWeak())
flags |= BLOCK_FIELD_IS_WEAK;
return ::buildByrefHelpers(CGM, byrefInfo,
ObjectByrefHelpers(valueAlignment, flags));
}
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
const VarDecl *var,
bool followForward) {
auto &info = getBlockByrefInfo(var);
return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
}
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
const BlockByrefInfo &info,
bool followForward,
const llvm::Twine &name) {
if (followForward) {
Address forwardingAddr =
Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
}
return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
info.FieldOffset, name);
}
const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
auto it = BlockByrefInfos.find(D);
if (it != BlockByrefInfos.end())
return it->second;
llvm::StructType *byrefType =
llvm::StructType::create(getLLVMContext(),
"struct.__block_byref_" + D->getNameAsString());
QualType Ty = D->getType();
CharUnits size;
SmallVector<llvm::Type *, 8> types;
types.push_back(Int8PtrTy);
size += getPointerSize();
types.push_back(llvm::PointerType::getUnqual(byrefType));
size += getPointerSize();
types.push_back(Int32Ty);
size += CharUnits::fromQuantity(4);
types.push_back(Int32Ty);
size += CharUnits::fromQuantity(4);
bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
if (hasCopyAndDispose) {
types.push_back(Int8PtrTy);
size += getPointerSize();
types.push_back(Int8PtrTy);
size += getPointerSize();
}
bool HasByrefExtendedLayout = false;
Qualifiers::ObjCLifetime Lifetime;
if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
HasByrefExtendedLayout) {
types.push_back(Int8PtrTy);
size += CharUnits::fromQuantity(PointerSizeInBytes);
}
llvm::Type *varTy = ConvertTypeForMem(Ty);
bool packed = false;
CharUnits varAlign = getContext().getDeclAlign(D);
CharUnits varOffset = size.alignTo(varAlign);
if (varOffset != size) {
llvm::Type *paddingTy =
llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
types.push_back(paddingTy);
size = varOffset;
} else if (CGM.getDataLayout().getABITypeAlignment(varTy)
> varAlign.getQuantity()) {
packed = true;
}
types.push_back(varTy);
byrefType->setBody(types, packed);
BlockByrefInfo info;
info.Type = byrefType;
info.FieldIndex = types.size() - 1;
info.FieldOffset = varOffset;
info.ByrefAlignment = std::max(varAlign, getPointerAlign());
auto pair = BlockByrefInfos.insert({D, info});
assert(pair.second && "info was inserted recursively?");
return pair.first->second;
}
void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
Address addr = emission.Addr;
llvm::StructType *byrefType = cast<llvm::StructType>(
cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
unsigned nextHeaderIndex = 0;
CharUnits nextHeaderOffset;
auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
const Twine &name) {
auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
nextHeaderOffset, name);
Builder.CreateStore(value, fieldAddr);
nextHeaderIndex++;
nextHeaderOffset += fieldSize;
};
BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
const VarDecl &D = *emission.Variable;
QualType type = D.getType();
bool HasByrefExtendedLayout;
Qualifiers::ObjCLifetime ByrefLifetime;
bool ByRefHasLifetime =
getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
llvm::Value *V;
int isa = 0;
if (type.isObjCGCWeak())
isa = 1;
V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
storeHeaderField(V, getPointerSize(), "byref.isa");
storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
BlockFlags flags;
if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
if (ByRefHasLifetime) {
if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
else switch (ByrefLifetime) {
case Qualifiers::OCL_Strong:
flags |= BLOCK_BYREF_LAYOUT_STRONG;
break;
case Qualifiers::OCL_Weak:
flags |= BLOCK_BYREF_LAYOUT_WEAK;
break;
case Qualifiers::OCL_ExplicitNone:
flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
break;
case Qualifiers::OCL_None:
if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
break;
default:
break;
}
if (CGM.getLangOpts().ObjCGCBitmapPrint) {
printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
if (flags & BLOCK_BYREF_LAYOUT_MASK) {
BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
printf(" BLOCK_BYREF_LAYOUT_STRONG");
if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
printf(" BLOCK_BYREF_LAYOUT_WEAK");
if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
}
printf("\n");
}
}
storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
getIntSize(), "byref.flags");
CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
storeHeaderField(V, getIntSize(), "byref.size");
if (helpers) {
storeHeaderField(helpers->CopyHelper, getPointerSize(),
"byref.copyHelper");
storeHeaderField(helpers->DisposeHelper, getPointerSize(),
"byref.disposeHelper");
}
if (ByRefHasLifetime && HasByrefExtendedLayout) {
auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
}
}
void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
llvm::Value *F = CGM.getBlockObjectDispose();
llvm::Value *args[] = {
Builder.CreateBitCast(V, Int8PtrTy),
llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
};
EmitNounwindRuntimeCall(F, args); }
namespace {
struct CallBlockRelease final : EHScopeStack::Cleanup {
llvm::Value *Addr;
CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
}
};
}
void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
return;
EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
emission.Addr.getPointer());
}
static void configureBlocksRuntimeObject(CodeGenModule &CGM,
llvm::Constant *C) {
if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
if (GV->isDeclaration() && GV->hasExternalLinkage())
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(),
nullptr);
configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
return NSConcreteGlobalBlock;
}
llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
if (NSConcreteStackBlock)
return NSConcreteStackBlock;
NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Int8PtrTy->getPointerTo(),
nullptr);
configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
return NSConcreteStackBlock;
}