[safestack] Sink unsafe address computation to each use.

This is a fix for PR27844.
When replacing uses of unsafe allocas, emit the new location
immediately after each use. Without this, the pointer stays live from
the function entry to the last use, while it's usually cheaper to
recalculate.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@272969 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Evgeniy Stepanov
2016-06-16 22:34:04 +00:00
parent fd0154041b
commit f268616d77
6 changed files with 97 additions and 20 deletions
+31 -8
View File
@@ -606,16 +606,39 @@ Value *SafeStack::moveStaticAllocasToUnsafeStack(
StaticOffset += Size;
StaticOffset = alignTo(StaticOffset, Align);
Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
ConstantInt::get(Int32Ty, -StaticOffset));
Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
if (AI->hasName() && isa<Instruction>(NewAI))
cast<Instruction>(NewAI)->takeName(AI);
// Replace alloc with the new location.
replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
replaceDbgValueForAlloca(AI, BasePointer, DIB, -StaticOffset);
AI->replaceAllUsesWith(NewAI);
// Replace uses of the alloca with the new location.
// Insert address calculation close to each use to work around PR27844.
std::string Name = std::string(AI->getName()) + ".unsafe";
while (!AI->use_empty()) {
Use &U = *AI->use_begin();
Instruction *User = cast<Instruction>(U.getUser());
Instruction *InsertBefore;
if (auto *PHI = dyn_cast<PHINode>(User))
InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
else
InsertBefore = User;
IRBuilder<> IRBUser(InsertBefore);
Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
ConstantInt::get(Int32Ty, -StaticOffset));
Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
if (auto *PHI = dyn_cast<PHINode>(User)) {
// PHI nodes may have multiple incoming edges from the same BB (why??),
// all must be updated at once with the same incoming value.
auto *BB = PHI->getIncomingBlock(U);
for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
if (PHI->getIncomingBlock(I) == BB)
PHI->setIncomingValue(I, Replacement);
} else {
U.set(Replacement);
}
}
AI->eraseFromParent();
}