Skip to content

Commit ad59a84

Browse files
dlei6gigcbot
authored andcommitted
Add return instruction to functions without it
LLVM does not legally require a return instruction in a function. However, return is needed by IGC BE to properly generate return code for control flow. This change will add a return (if it does not exist) as the last instruction of the function.
1 parent 4ef9485 commit ad59a84

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

IGC/AdaptorCommon/LegalizeFunctionSignatures.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ bool LegalizeFunctionSignatures::runOnModule(Module& M)
8080
{
8181
auto pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils();
8282

83+
// Add an unreachable return for functions without the return instruction
84+
FixNoReturn(M);
8385
// Creates a new function declaration with modified signature
8486
FixFunctionSignatures(M);
8587
// Transforms all callers of the old function to the new function
@@ -665,3 +667,34 @@ void LegalizeFunctionSignatures::FixCallInstruction(Module& M, CallInst* callIns
665667
callInst->eraseFromParent();
666668
}
667669
}
670+
671+
void LegalizeFunctionSignatures::FixNoReturn(Module& M)
672+
{
673+
for (auto& FI : M)
674+
{
675+
if (!FI.empty())
676+
{
677+
// Search each BB for the ReturnInst
678+
BasicBlock* lastBB = nullptr;
679+
bool hasRetInst = false;
680+
for (auto& BB : FI)
681+
{
682+
if (isa<ReturnInst>(BB.getTerminator()))
683+
{
684+
hasRetInst = true;
685+
break;
686+
}
687+
lastBB = &BB;
688+
}
689+
// Insert an unreachable ReturnInst in the last BB
690+
if (!hasRetInst)
691+
{
692+
IGCLLVM::IRBuilder<> builder(lastBB);
693+
ReturnInst* dummyRet = FI.getReturnType()->isVoidTy() ?
694+
builder.CreateRetVoid() :
695+
builder.CreateRet(UndefValue::get(FI.getReturnType()));
696+
dummyRet->moveAfter(lastBB->getTerminator());
697+
}
698+
}
699+
}
700+
}

IGC/AdaptorCommon/LegalizeFunctionSignatures.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class LegalizeFunctionSignatures : public llvm::ModulePass
4040
void FixFunctionBody(llvm::Module& M);
4141
void FixFunctionUsers(llvm::Module& M);
4242
void FixCallInstruction(llvm::Module& M, llvm::CallInst* callInst);
43+
void FixNoReturn(llvm::Module& M);
4344

4445
virtual llvm::StringRef getPassName() const
4546
{

0 commit comments

Comments
 (0)