1 //===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass is used to ensure that functions have at most one return and one
10 // unreachable instruction in them.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Type.h"
19 #include "llvm/Transforms/Utils.h"
24 bool unifyUnreachableBlocks(Function
&F
) {
25 std::vector
<BasicBlock
*> UnreachableBlocks
;
27 for (BasicBlock
&I
: F
)
28 if (isa
<UnreachableInst
>(I
.getTerminator()))
29 UnreachableBlocks
.push_back(&I
);
31 if (UnreachableBlocks
.size() <= 1)
34 BasicBlock
*UnreachableBlock
=
35 BasicBlock::Create(F
.getContext(), "UnifiedUnreachableBlock", &F
);
36 new UnreachableInst(F
.getContext(), UnreachableBlock
);
38 for (BasicBlock
*BB
: UnreachableBlocks
) {
39 BB
->back().eraseFromParent(); // Remove the unreachable inst.
40 BranchInst::Create(UnreachableBlock
, BB
);
46 bool unifyReturnBlocks(Function
&F
) {
47 std::vector
<BasicBlock
*> ReturningBlocks
;
49 for (BasicBlock
&I
: F
)
50 if (isa
<ReturnInst
>(I
.getTerminator()))
51 ReturningBlocks
.push_back(&I
);
53 if (ReturningBlocks
.size() <= 1)
56 // Insert a new basic block into the function, add PHI nodes (if the function
57 // returns values), and convert all of the return instructions into
58 // unconditional branches.
59 BasicBlock
*NewRetBlock
= BasicBlock::Create(F
.getContext(),
60 "UnifiedReturnBlock", &F
);
62 PHINode
*PN
= nullptr;
63 if (F
.getReturnType()->isVoidTy()) {
64 ReturnInst::Create(F
.getContext(), nullptr, NewRetBlock
);
66 // If the function doesn't return void... add a PHI node to the block...
67 PN
= PHINode::Create(F
.getReturnType(), ReturningBlocks
.size(),
69 PN
->insertInto(NewRetBlock
, NewRetBlock
->end());
70 ReturnInst::Create(F
.getContext(), PN
, NewRetBlock
);
73 // Loop over all of the blocks, replacing the return instruction with an
74 // unconditional branch.
75 for (BasicBlock
*BB
: ReturningBlocks
) {
76 // Add an incoming element to the PHI node for every return instruction that
77 // is merging into this new block...
79 PN
->addIncoming(BB
->getTerminator()->getOperand(0), BB
);
81 BB
->back().eraseFromParent(); // Remove the return insn
82 BranchInst::Create(NewRetBlock
, BB
);
89 PreservedAnalyses
UnifyFunctionExitNodesPass::run(Function
&F
,
90 FunctionAnalysisManager
&AM
) {
92 Changed
|= unifyUnreachableBlocks(F
);
93 Changed
|= unifyReturnBlocks(F
);
94 return Changed
? PreservedAnalyses() : PreservedAnalyses::all();