blob: e3a0917eb02bd2275477331f58372ca0a3521d9e [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ebc302004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000018#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000019#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000021#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000023#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
Chris Lattner3481f242008-11-27 22:57:53 +000025#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner4d1e46e2002-05-07 18:07:59 +000028//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000029// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030//
31
Chris Lattner4d1e46e2002-05-07 18:07:59 +000032// ConstantFoldTerminator - If a terminator instruction is predicated on a
33// constant value, convert it into an unconditional branch to the constant
34// destination.
35//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000036bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000037 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000038
Chris Lattner4d1e46e2002-05-07 18:07:59 +000039 // Branch - See if we are conditional jumping on constant
40 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
41 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
42 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
43 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
44
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000045 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000046 // Are we branching on constant?
47 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000048 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
49 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000050
Misha Brukmanfd939082005-04-21 23:48:37 +000051 //cerr << "Function: " << T->getParent()->getParent()
52 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000053 // << "\n\nTo: " << OldDest << endl;
54
55 // Let the basic block know that we are letting go of it. Based on this,
56 // it will adjust it's PHI nodes.
57 assert(BI->getParent() && "Terminator not inserted in block!");
58 OldDest->removePredecessor(BI->getParent());
59
60 // Set the unconditional destination, and change the insn to be an
61 // unconditional branch.
62 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000063 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +000064 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000065 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000066 // br bool %cond, label %Dest, label %Dest
67 // and changes it into: br label %Dest
68
69 // Let the basic block know that we are letting go of one copy of it.
70 assert(BI->getParent() && "Terminator not inserted in block!");
71 Dest1->removePredecessor(BI->getParent());
72
73 // Change a conditional branch to unconditional.
74 BI->setUnconditionalDest(Dest1);
75 return true;
76 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +000077 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
78 // If we are switching on a constant, we can convert the switch into a
79 // single branch instruction!
80 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
81 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +000082 BasicBlock *DefaultDest = TheOnlyDest;
83 assert(TheOnlyDest == SI->getDefaultDest() &&
84 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +000085
Chris Lattner10b1f5a2003-08-17 20:21:14 +000086 // Figure out which case it goes to...
87 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
88 // Found case matching a constant operand?
89 if (SI->getSuccessorValue(i) == CI) {
90 TheOnlyDest = SI->getSuccessor(i);
91 break;
92 }
Chris Lattner694e37f2003-08-17 19:41:53 +000093
Chris Lattner7d6c24c2003-08-23 23:18:19 +000094 // Check to see if this branch is going to the same place as the default
95 // dest. If so, eliminate it as an explicit compare.
96 if (SI->getSuccessor(i) == DefaultDest) {
97 // Remove this entry...
98 DefaultDest->removePredecessor(SI->getParent());
99 SI->removeCase(i);
100 --i; --e; // Don't skip an entry...
101 continue;
102 }
103
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000104 // Otherwise, check to see if the switch only branches to one destination.
105 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
106 // destinations.
107 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000108 }
109
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000110 if (CI && !TheOnlyDest) {
111 // Branching on a constant, but not any of the cases, go to the default
112 // successor.
113 TheOnlyDest = SI->getDefaultDest();
114 }
115
116 // If we found a single destination that we can fold the switch into, do so
117 // now.
118 if (TheOnlyDest) {
119 // Insert the new branch..
Gabor Greif051a9502008-04-06 20:25:17 +0000120 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000121 BasicBlock *BB = SI->getParent();
122
123 // Remove entries from PHI nodes which we no longer branch to...
124 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
125 // Found case matching a constant operand?
126 BasicBlock *Succ = SI->getSuccessor(i);
127 if (Succ == TheOnlyDest)
128 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
129 else
130 Succ->removePredecessor(BB);
131 }
132
133 // Delete the old switch...
134 BB->getInstList().erase(SI);
135 return true;
136 } else if (SI->getNumSuccessors() == 2) {
137 // Otherwise, we can fold this switch into a conditional branch
138 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000139 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
140 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000141 // Insert the new branch...
Gabor Greif051a9502008-04-06 20:25:17 +0000142 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000143
144 // Delete the old switch...
Dan Gohman1adec832008-06-21 22:08:46 +0000145 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000146 return true;
147 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000148 }
149 return false;
150}
151
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000152
153//===----------------------------------------------------------------------===//
154// Local dead code elimination...
155//
156
Chris Lattner3481f242008-11-27 22:57:53 +0000157/// isInstructionTriviallyDead - Return true if the result produced by the
158/// instruction is not used, and the instruction has no side effects.
159///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000160bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000161 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000162
Chris Lattner741c0ae2007-12-29 00:59:12 +0000163 if (!I->mayWriteToMemory())
164 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000165
Chris Lattner741c0ae2007-12-29 00:59:12 +0000166 // Special case intrinsics that "may write to memory" but can be deleted when
167 // dead.
168 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
169 // Safe to delete llvm.stacksave if dead.
170 if (II->getIntrinsicID() == Intrinsic::stacksave)
171 return true;
172
Chris Lattnerec710c52005-05-06 05:27:34 +0000173 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000174}
175
Chris Lattner3481f242008-11-27 22:57:53 +0000176/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
177/// trivially dead instruction, delete it. If that makes any of its operands
178/// trivially dead, delete them too, recursively.
179void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
180 Instruction *I = dyn_cast<Instruction>(V);
181 if (!I || !I->use_empty()) return;
182
183 SmallPtrSet<Instruction*, 16> Insts;
184 Insts.insert(I);
185
186 while (!Insts.empty()) {
187 I = *Insts.begin();
188 Insts.erase(I);
189 if (isInstructionTriviallyDead(I)) {
190 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
191 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
192 Insts.insert(U);
193 I->eraseFromParent();
194 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000195 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000196}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000197
Chris Lattner3481f242008-11-27 22:57:53 +0000198
Chris Lattnerb29714a2008-11-27 07:43:12 +0000199//===----------------------------------------------------------------------===//
200// Control Flow Graph Restructuring...
201//
202
203/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
204/// predecessor is known to have one successor (DestBB!). Eliminate the edge
205/// between them, moving the instructions in the predecessor into DestBB and
206/// deleting the predecessor block.
207///
208void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
209 // If BB has single-entry PHI nodes, fold them.
210 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
211 Value *NewVal = PN->getIncomingValue(0);
212 // Replace self referencing PHI with undef, it must be dead.
213 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
214 PN->replaceAllUsesWith(NewVal);
215 PN->eraseFromParent();
216 }
217
218 BasicBlock *PredBB = DestBB->getSinglePredecessor();
219 assert(PredBB && "Block doesn't have a single predecessor!");
220
221 // Splice all the instructions from PredBB to DestBB.
222 PredBB->getTerminator()->eraseFromParent();
223 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
224
225 // Anything that branched to PredBB now branches to DestBB.
226 PredBB->replaceAllUsesWith(DestBB);
227
228 // Nuke BB.
229 PredBB->eraseFromParent();
230}