Skip to content

Commit ce1b24c

Browse files
committed
[IRBuilder] Handle constexpr-bitcast for IRBuilder::CreateThreadLocalAddress
In case that opaque pointers not enabled, there may be some constexpr bitcast uses for thread local variables and the design of llvm allow people to sink constant arbitrarily. This breaks the assumption of IRBuilder::CreateThreadLocalAddress. This patch tries to handle the case.
1 parent d8602bc commit ce1b24c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

llvm/lib/IR/IRBuilder.cpp

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,19 @@ CallInst *IRBuilderBase::CreateInvariantStart(Value *Ptr, ConstantInt *Size) {
527527
}
528528

529529
CallInst *IRBuilderBase::CreateThreadLocalAddress(Value *Ptr) {
530-
assert(isa<GlobalValue>(Ptr) && cast<GlobalValue>(Ptr)->isThreadLocal() &&
530+
#ifndef NDEBUG
531+
// Handle specially for constexpr cast. This is possible when
532+
// opaque pointers not enabled since constant could be sinked
533+
// directly by the design of llvm. This could be eliminated
534+
// after we eliminate the abuse of constexpr.
535+
auto *V = Ptr;
536+
if (auto *CE = dyn_cast<ConstantExpr>(V))
537+
if (CE->isCast())
538+
V = CE->getOperand(0);
539+
540+
assert(isa<GlobalValue>(V) && cast<GlobalValue>(V)->isThreadLocal() &&
531541
"threadlocal_address only applies to thread local variables.");
542+
#endif
532543
return CreateIntrinsic(llvm::Intrinsic::threadlocal_address, {Ptr->getType()},
533544
{Ptr});
534545
}

llvm/unittests/IR/IRBuilderTest.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,21 @@ TEST_F(IRBuilderTest, CreateGlobalStringPtr) {
10091009
EXPECT_TRUE(String3->getType()->getPointerAddressSpace() == 2);
10101010
}
10111011

1012+
TEST_F(IRBuilderTest, CreateThreadLocalAddress) {
1013+
IRBuilder<> Builder(BB);
1014+
1015+
GlobalVariable *G = new GlobalVariable(*M, Builder.getInt64Ty(), /*isConstant*/true,
1016+
GlobalValue::ExternalLinkage, nullptr, "", nullptr,
1017+
GlobalValue::GeneralDynamicTLSModel);
1018+
1019+
Constant *CEBC = ConstantExpr::getBitCast(G, Builder.getInt8PtrTy());
1020+
// Tests that IRBuilder::CreateThreadLocalAddress wouldn't crash if its operand
1021+
// is BitCast ConstExpr. The case should be eliminated after we eliminate the
1022+
// abuse of constexpr.
1023+
CallInst *CI = Builder.CreateThreadLocalAddress(CEBC);
1024+
EXPECT_NE(CI, nullptr);
1025+
}
1026+
10121027
TEST_F(IRBuilderTest, DebugLoc) {
10131028
auto CalleeTy = FunctionType::get(Type::getVoidTy(Ctx),
10141029
/*isVarArg=*/false);

0 commit comments

Comments
 (0)