blob: 82b8da3a1070b2601682977281d3c91ffcab555e [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Evgeniy Stepanov3333e662012-12-21 11:18:49 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000018#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +000019#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Analysis/Dominators.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000024#include "llvm/DIBuilder.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000025#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/GlobalAlias.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Operator.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000038#include "llvm/Support/CFG.h"
39#include "llvm/Support/Debug.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
41#include "llvm/Support/MathExtras.h"
Chris Lattner19f2dc42009-12-29 09:12:29 +000042#include "llvm/Support/ValueHandle.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +000046STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
47
Chris Lattner4d1e46e2002-05-07 18:07:59 +000048//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000049// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000050//
51
Frits van Bommel5649ba72011-05-22 16:24:18 +000052/// ConstantFoldTerminator - If a terminator instruction is predicated on a
53/// constant value, convert it into an unconditional branch to the constant
54/// destination. This is a nontrivial operation because the successors of this
55/// basic block must have their PHI nodes updated.
56/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
57/// conditions and indirectbr addresses this might make dead if
58/// DeleteDeadConditions is true.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000059bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
60 const TargetLibraryInfo *TLI) {
Chris Lattner76ae3442002-05-21 20:04:50 +000061 TerminatorInst *T = BB->getTerminator();
Devang Patel62fb3552011-05-18 17:26:46 +000062 IRBuilder<> Builder(T);
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattner4d1e46e2002-05-07 18:07:59 +000064 // Branch - See if we are conditional jumping on constant
65 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
66 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +000067 BasicBlock *Dest1 = BI->getSuccessor(0);
68 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000069
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000070 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000071 // Are we branching on constant?
72 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000073 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
74 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000075
Misha Brukmanfd939082005-04-21 23:48:37 +000076 //cerr << "Function: " << T->getParent()->getParent()
77 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000078 // << "\n\nTo: " << OldDest << endl;
79
80 // Let the basic block know that we are letting go of it. Based on this,
81 // it will adjust it's PHI nodes.
Jay Foad1a039022011-04-19 15:23:29 +000082 OldDest->removePredecessor(BB);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000083
Jay Foad8f9ffbd2011-01-07 20:25:56 +000084 // Replace the conditional branch with an unconditional one.
Devang Patel62fb3552011-05-18 17:26:46 +000085 Builder.CreateBr(Destination);
Jay Foad8f9ffbd2011-01-07 20:25:56 +000086 BI->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +000087 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +000088 }
Jakub Staszaka18c5742013-07-22 23:16:36 +000089
Chris Lattner0a4c6782009-11-01 03:40:38 +000090 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000091 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000092 // br bool %cond, label %Dest, label %Dest
93 // and changes it into: br label %Dest
94
95 // Let the basic block know that we are letting go of one copy of it.
96 assert(BI->getParent() && "Terminator not inserted in block!");
97 Dest1->removePredecessor(BI->getParent());
98
Jay Foad8f9ffbd2011-01-07 20:25:56 +000099 // Replace the conditional branch with an unconditional one.
Devang Patel62fb3552011-05-18 17:26:46 +0000100 Builder.CreateBr(Dest1);
Frits van Bommel5649ba72011-05-22 16:24:18 +0000101 Value *Cond = BI->getCondition();
Jay Foad8f9ffbd2011-01-07 20:25:56 +0000102 BI->eraseFromParent();
Frits van Bommel5649ba72011-05-22 16:24:18 +0000103 if (DeleteDeadConditions)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000104 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000105 return true;
106 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000107 return false;
108 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000109
Chris Lattner0a4c6782009-11-01 03:40:38 +0000110 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000111 // If we are switching on a constant, we can convert the switch into a
112 // single branch instruction!
113 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000114 BasicBlock *TheOnlyDest = SI->getDefaultDest();
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000115 BasicBlock *DefaultDest = TheOnlyDest;
Chris Lattner694e37f2003-08-17 19:41:53 +0000116
Chris Lattner0a4c6782009-11-01 03:40:38 +0000117 // Figure out which case it goes to.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000118 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000119 i != e; ++i) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000120 // Found case matching a constant operand?
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000121 if (i.getCaseValue() == CI) {
122 TheOnlyDest = i.getCaseSuccessor();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000123 break;
124 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000125
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000126 // Check to see if this branch is going to the same place as the default
127 // dest. If so, eliminate it as an explicit compare.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000128 if (i.getCaseSuccessor() == DefaultDest) {
Manman Renee99c7f2012-09-12 17:04:11 +0000129 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
130 // MD should have 2 + NumCases operands.
131 if (MD && MD->getNumOperands() == 2 + SI->getNumCases()) {
132 // Collect branch weights into a vector.
133 SmallVector<uint32_t, 8> Weights;
134 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
135 ++MD_i) {
136 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
137 assert(CI);
138 Weights.push_back(CI->getValue().getZExtValue());
139 }
140 // Merge weight of this case to the default weight.
141 unsigned idx = i.getCaseIndex();
142 Weights[0] += Weights[idx+1];
143 // Remove weight for this case.
144 std::swap(Weights[idx+1], Weights.back());
145 Weights.pop_back();
146 SI->setMetadata(LLVMContext::MD_prof,
147 MDBuilder(BB->getContext()).
148 createBranchWeights(Weights));
149 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000150 // Remove this entry.
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000151 DefaultDest->removePredecessor(SI->getParent());
152 SI->removeCase(i);
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000153 --i; --e;
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000154 continue;
155 }
156
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000157 // Otherwise, check to see if the switch only branches to one destination.
158 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
159 // destinations.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000160 if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000161 }
162
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000163 if (CI && !TheOnlyDest) {
164 // Branching on a constant, but not any of the cases, go to the default
165 // successor.
166 TheOnlyDest = SI->getDefaultDest();
167 }
168
169 // If we found a single destination that we can fold the switch into, do so
170 // now.
171 if (TheOnlyDest) {
Chris Lattner0a4c6782009-11-01 03:40:38 +0000172 // Insert the new branch.
Devang Patel62fb3552011-05-18 17:26:46 +0000173 Builder.CreateBr(TheOnlyDest);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000174 BasicBlock *BB = SI->getParent();
175
176 // Remove entries from PHI nodes which we no longer branch to...
177 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
178 // Found case matching a constant operand?
179 BasicBlock *Succ = SI->getSuccessor(i);
180 if (Succ == TheOnlyDest)
181 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
182 else
183 Succ->removePredecessor(BB);
184 }
185
Chris Lattner0a4c6782009-11-01 03:40:38 +0000186 // Delete the old switch.
Frits van Bommel5649ba72011-05-22 16:24:18 +0000187 Value *Cond = SI->getCondition();
188 SI->eraseFromParent();
189 if (DeleteDeadConditions)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000190 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000191 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +0000192 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000193
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +0000194 if (SI->getNumCases() == 1) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000195 // Otherwise, we can fold this switch into a conditional branch
196 // instruction if it has only one non-default destination.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000197 SwitchInst::CaseIt FirstCase = SI->case_begin();
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000198 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
199 FirstCase.getCaseValue(), "cond");
Devang Patel62fb3552011-05-18 17:26:46 +0000200
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000201 // Insert the new branch.
202 BranchInst *NewBr = Builder.CreateCondBr(Cond,
203 FirstCase.getCaseSuccessor(),
204 SI->getDefaultDest());
205 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
206 if (MD && MD->getNumOperands() == 3) {
207 ConstantInt *SICase = dyn_cast<ConstantInt>(MD->getOperand(2));
208 ConstantInt *SIDef = dyn_cast<ConstantInt>(MD->getOperand(1));
209 assert(SICase && SIDef);
210 // The TrueWeight should be the weight for the single case of SI.
211 NewBr->setMetadata(LLVMContext::MD_prof,
212 MDBuilder(BB->getContext()).
213 createBranchWeights(SICase->getValue().getZExtValue(),
214 SIDef->getValue().getZExtValue()));
Stepan Dyatkovskiya2067fb2012-05-23 08:18:26 +0000215 }
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000216
217 // Delete the old switch.
218 SI->eraseFromParent();
219 return true;
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000220 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000221 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000222 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000223
224 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
225 // indirectbr blockaddress(@F, @BB) -> br label @BB
226 if (BlockAddress *BA =
227 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
228 BasicBlock *TheOnlyDest = BA->getBasicBlock();
229 // Insert the new branch.
Devang Patel62fb3552011-05-18 17:26:46 +0000230 Builder.CreateBr(TheOnlyDest);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000231
Chris Lattner0a4c6782009-11-01 03:40:38 +0000232 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
233 if (IBI->getDestination(i) == TheOnlyDest)
234 TheOnlyDest = 0;
235 else
236 IBI->getDestination(i)->removePredecessor(IBI->getParent());
237 }
Frits van Bommel5649ba72011-05-22 16:24:18 +0000238 Value *Address = IBI->getAddress();
Chris Lattner0a4c6782009-11-01 03:40:38 +0000239 IBI->eraseFromParent();
Frits van Bommel5649ba72011-05-22 16:24:18 +0000240 if (DeleteDeadConditions)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000241 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000242
Chris Lattner0a4c6782009-11-01 03:40:38 +0000243 // If we didn't find our destination in the IBI successor list, then we
244 // have undefined behavior. Replace the unconditional branch with an
245 // 'unreachable' instruction.
246 if (TheOnlyDest) {
247 BB->getTerminator()->eraseFromParent();
248 new UnreachableInst(BB->getContext(), BB);
249 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000250
Chris Lattner0a4c6782009-11-01 03:40:38 +0000251 return true;
252 }
253 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000254
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000255 return false;
256}
257
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000258
259//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000260// Local dead code elimination.
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000261//
262
Chris Lattner3481f242008-11-27 22:57:53 +0000263/// isInstructionTriviallyDead - Return true if the result produced by the
264/// instruction is not used, and the instruction has no side effects.
265///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000266bool llvm::isInstructionTriviallyDead(Instruction *I,
267 const TargetLibraryInfo *TLI) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000268 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000269
Bill Wendling187b1922011-08-15 20:10:51 +0000270 // We don't want the landingpad instruction removed by anything this general.
271 if (isa<LandingPadInst>(I))
272 return false;
273
Devang Patel9c5822a2011-03-18 23:28:02 +0000274 // We don't want debug info removed by anything this general, unless
275 // debug info is empty.
276 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
Nick Lewycky3e69c132011-08-02 21:19:27 +0000277 if (DDI->getAddress())
Devang Patel9c5822a2011-03-18 23:28:02 +0000278 return false;
Devang Patelb9946212011-03-21 22:04:45 +0000279 return true;
Nick Lewycky3e69c132011-08-02 21:19:27 +0000280 }
Devang Patelb9946212011-03-21 22:04:45 +0000281 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patel9c5822a2011-03-18 23:28:02 +0000282 if (DVI->getValue())
283 return false;
Devang Patelb9946212011-03-21 22:04:45 +0000284 return true;
Devang Patel9c5822a2011-03-18 23:28:02 +0000285 }
286
Duncan Sands7af1c782009-05-06 06:49:50 +0000287 if (!I->mayHaveSideEffects()) return true;
288
289 // Special case intrinsics that "may have side effects" but can be deleted
290 // when dead.
Nick Lewycky3e69c132011-08-02 21:19:27 +0000291 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner741c0ae2007-12-29 00:59:12 +0000292 // Safe to delete llvm.stacksave if dead.
293 if (II->getIntrinsicID() == Intrinsic::stacksave)
294 return true;
Nick Lewycky3e69c132011-08-02 21:19:27 +0000295
296 // Lifetime intrinsics are dead when their right-hand is undef.
297 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
298 II->getIntrinsicID() == Intrinsic::lifetime_end)
299 return isa<UndefValue>(II->getArgOperand(1));
300 }
Nick Lewycky4a3935c2011-10-24 04:35:36 +0000301
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000302 if (isAllocLikeFn(I, TLI)) return true;
Nick Lewycky4a3935c2011-10-24 04:35:36 +0000303
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000304 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewycky4a3935c2011-10-24 04:35:36 +0000305 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
306 return C->isNullValue() || isa<UndefValue>(C);
307
Chris Lattnerec710c52005-05-06 05:27:34 +0000308 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000309}
310
Chris Lattner3481f242008-11-27 22:57:53 +0000311/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
312/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000313/// trivially dead, delete them too, recursively. Return true if any
314/// instructions were deleted.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000315bool
316llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
317 const TargetLibraryInfo *TLI) {
Chris Lattner3481f242008-11-27 22:57:53 +0000318 Instruction *I = dyn_cast<Instruction>(V);
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000319 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000320 return false;
Jakub Staszaka18c5742013-07-22 23:16:36 +0000321
Chris Lattner76057302008-11-28 01:20:46 +0000322 SmallVector<Instruction*, 16> DeadInsts;
323 DeadInsts.push_back(I);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000324
Dan Gohman321a8132010-01-05 16:27:25 +0000325 do {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000326 I = DeadInsts.pop_back_val();
Chris Lattner28721772008-11-28 00:58:15 +0000327
Chris Lattner76057302008-11-28 01:20:46 +0000328 // Null out all of the instruction's operands to see if any operand becomes
329 // dead as we go.
330 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
331 Value *OpV = I->getOperand(i);
332 I->setOperand(i, 0);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000333
Chris Lattner76057302008-11-28 01:20:46 +0000334 if (!OpV->use_empty()) continue;
Jakub Staszaka18c5742013-07-22 23:16:36 +0000335
Chris Lattner76057302008-11-28 01:20:46 +0000336 // If the operand is an instruction that became dead as we nulled out the
337 // operand, and if it is 'trivially' dead, delete it in a future loop
338 // iteration.
339 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000340 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattner76057302008-11-28 01:20:46 +0000341 DeadInsts.push_back(OpI);
342 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000343
Chris Lattner76057302008-11-28 01:20:46 +0000344 I->eraseFromParent();
Dan Gohman321a8132010-01-05 16:27:25 +0000345 } while (!DeadInsts.empty());
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000346
347 return true;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000348}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000349
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000350/// areAllUsesEqual - Check whether the uses of a value are all the same.
351/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000352/// true when there are no uses or multiple uses that all refer to the same
353/// value.
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000354static bool areAllUsesEqual(Instruction *I) {
355 Value::use_iterator UI = I->use_begin();
356 Value::use_iterator UE = I->use_end();
357 if (UI == UE)
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000358 return true;
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000359
360 User *TheUse = *UI;
361 for (++UI; UI != UE; ++UI) {
362 if (*UI != TheUse)
363 return false;
364 }
365 return true;
366}
367
Dan Gohmanafc36a92009-05-02 18:29:22 +0000368/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
369/// dead PHI node, due to being a def-use chain of single-use nodes that
370/// either forms a cycle or is terminated by a trivially dead instruction,
371/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sands2cfbf012011-02-21 17:32:05 +0000372/// too, recursively. Return true if a change was made.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000373bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
374 const TargetLibraryInfo *TLI) {
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000375 SmallPtrSet<Instruction*, 4> Visited;
376 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
377 I = cast<Instruction>(*I->use_begin())) {
378 if (I->use_empty())
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000379 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewyckyeff5e692011-02-20 18:05:56 +0000380
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000381 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanafc36a92009-05-02 18:29:22 +0000382 // won't prove fruitful.
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000383 if (!Visited.insert(I)) {
384 // Break the cycle and delete the instruction and its operands.
385 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000386 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sands2cfbf012011-02-21 17:32:05 +0000387 return true;
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000388 }
389 }
390 return false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000391}
Chris Lattner3481f242008-11-27 22:57:53 +0000392
Chris Lattnere234a302010-01-12 19:40:54 +0000393/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
394/// simplify any instructions in it and recursively delete dead instructions.
395///
396/// This returns true if it changed the code, note that it can delete
397/// instructions in other blocks as well in this block.
Micah Villmow3574eca2012-10-08 16:38:25 +0000398bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000399 const TargetLibraryInfo *TLI) {
Chris Lattnere234a302010-01-12 19:40:54 +0000400 bool MadeChange = false;
Chandler Carruthacdae3e2012-03-25 03:29:25 +0000401
402#ifndef NDEBUG
403 // In debug builds, ensure that the terminator of the block is never replaced
404 // or deleted by these simplifications. The idea of simplification is that it
405 // cannot introduce new instructions, and there is no way to replace the
406 // terminator of a block without introducing a new instruction.
407 AssertingVH<Instruction> TerminatorVH(--BB->end());
408#endif
409
Chandler Carruth858cd1c2012-03-24 23:03:27 +0000410 for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
411 assert(!BI->isTerminator());
Chris Lattnere234a302010-01-12 19:40:54 +0000412 Instruction *Inst = BI++;
Chandler Carruth6b980542012-03-24 21:11:24 +0000413
414 WeakVH BIHandle(BI);
Benjamin Kramerd7215202013-09-24 16:37:40 +0000415 if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
Chris Lattnere234a302010-01-12 19:40:54 +0000416 MadeChange = true;
Chris Lattner35a939b2010-07-15 06:06:04 +0000417 if (BIHandle != BI)
Chris Lattnere234a302010-01-12 19:40:54 +0000418 BI = BB->begin();
419 continue;
420 }
Eli Friedman71ad2c92011-04-02 22:45:17 +0000421
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000422 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
Eli Friedman71ad2c92011-04-02 22:45:17 +0000423 if (BIHandle != BI)
424 BI = BB->begin();
Chris Lattnere234a302010-01-12 19:40:54 +0000425 }
426 return MadeChange;
427}
428
Chris Lattnerb29714a2008-11-27 07:43:12 +0000429//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000430// Control Flow Graph Restructuring.
Chris Lattnerb29714a2008-11-27 07:43:12 +0000431//
432
Chris Lattner40d8c282009-11-10 22:26:15 +0000433
434/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
435/// method is called when we're about to delete Pred as a predecessor of BB. If
436/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
437///
438/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
439/// nodes that collapse into identity values. For example, if we have:
440/// x = phi(1, 0, 0, 0)
441/// y = and x, z
442///
443/// .. and delete the predecessor corresponding to the '1', this will attempt to
444/// recursively fold the and to 0.
445void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
Micah Villmow3574eca2012-10-08 16:38:25 +0000446 DataLayout *TD) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000447 // This only adjusts blocks with PHI nodes.
448 if (!isa<PHINode>(BB->begin()))
449 return;
Jakub Staszaka18c5742013-07-22 23:16:36 +0000450
Chris Lattner40d8c282009-11-10 22:26:15 +0000451 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
452 // them down. This will leave us with single entry phi nodes and other phis
453 // that can be removed.
454 BB->removePredecessor(Pred, true);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000455
Chris Lattner40d8c282009-11-10 22:26:15 +0000456 WeakVH PhiIt = &BB->front();
457 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
458 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattner35a939b2010-07-15 06:06:04 +0000459 Value *OldPhiIt = PhiIt;
Chandler Carruth6b980542012-03-24 21:11:24 +0000460
461 if (!recursivelySimplifyInstruction(PN, TD))
462 continue;
463
Chris Lattner40d8c282009-11-10 22:26:15 +0000464 // If recursive simplification ended up deleting the next PHI node we would
465 // iterate to, then our iterator is invalid, restart scanning from the top
466 // of the block.
Chris Lattner35a939b2010-07-15 06:06:04 +0000467 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner40d8c282009-11-10 22:26:15 +0000468 }
469}
470
471
Chris Lattnerb29714a2008-11-27 07:43:12 +0000472/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
473/// predecessor is known to have one successor (DestBB!). Eliminate the edge
474/// between them, moving the instructions in the predecessor into DestBB and
475/// deleting the predecessor block.
476///
Andreas Neustifterad809812009-09-16 09:26:52 +0000477void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
Chris Lattnerb29714a2008-11-27 07:43:12 +0000478 // If BB has single-entry PHI nodes, fold them.
479 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
480 Value *NewVal = PN->getIncomingValue(0);
481 // Replace self referencing PHI with undef, it must be dead.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000482 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattnerb29714a2008-11-27 07:43:12 +0000483 PN->replaceAllUsesWith(NewVal);
484 PN->eraseFromParent();
485 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000486
Chris Lattnerb29714a2008-11-27 07:43:12 +0000487 BasicBlock *PredBB = DestBB->getSinglePredecessor();
488 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszaka18c5742013-07-22 23:16:36 +0000489
Chris Lattner37914c82010-02-15 20:47:49 +0000490 // Zap anything that took the address of DestBB. Not doing this will give the
491 // address an invalid value.
492 if (DestBB->hasAddressTaken()) {
493 BlockAddress *BA = BlockAddress::get(DestBB);
494 Constant *Replacement =
495 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
496 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
497 BA->getType()));
498 BA->destroyConstant();
499 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000500
Chris Lattnerb29714a2008-11-27 07:43:12 +0000501 // Anything that branched to PredBB now branches to DestBB.
502 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000503
Jay Foad95c3e482011-06-23 09:09:15 +0000504 // Splice all the instructions from PredBB to DestBB.
505 PredBB->getTerminator()->eraseFromParent();
Bill Wendling3e033f22013-10-21 04:09:17 +0000506 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Jay Foad95c3e482011-06-23 09:09:15 +0000507
Andreas Neustifterad809812009-09-16 09:26:52 +0000508 if (P) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000509 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
510 if (DT) {
511 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
512 DT->changeImmediateDominator(DestBB, PredBBIDom);
513 DT->eraseNode(PredBB);
514 }
Andreas Neustifterad809812009-09-16 09:26:52 +0000515 }
Chris Lattnerb29714a2008-11-27 07:43:12 +0000516 // Nuke BB.
517 PredBB->eraseFromParent();
518}
Devang Patel4afc90d2009-02-10 07:00:59 +0000519
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000520/// CanMergeValues - Return true if we can choose one of these values to use
521/// in place of the other. Note that we will always choose the non-undef
522/// value to keep.
523static bool CanMergeValues(Value *First, Value *Second) {
524 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
525}
526
Chris Lattnerdce94d92009-11-10 05:59:26 +0000527/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
Mark Lacey1b6e10f2013-08-14 22:11:42 +0000528/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
Chris Lattnerdce94d92009-11-10 05:59:26 +0000529///
530/// Assumption: Succ is the single successor for BB.
531///
532static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
533 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
534
Jakub Staszaka18c5742013-07-22 23:16:36 +0000535 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000536 << Succ->getName() << "\n");
537 // Shortcut, if there is only a single predecessor it must be BB and merging
538 // is always safe
539 if (Succ->getSinglePredecessor()) return true;
540
541 // Make a list of the predecessors of BB
Benjamin Kramer88c09142011-12-06 16:14:29 +0000542 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnerdce94d92009-11-10 05:59:26 +0000543
Chris Lattnerdce94d92009-11-10 05:59:26 +0000544 // Look at all the phi nodes in Succ, to see if they present a conflict when
545 // merging these blocks
546 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
547 PHINode *PN = cast<PHINode>(I);
548
549 // If the incoming value from BB is again a PHINode in
550 // BB which has the same incoming value for *PI as PN does, we can
551 // merge the phi nodes and then the blocks can still be merged
552 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
553 if (BBPN && BBPN->getParent() == BB) {
Benjamin Kramer88c09142011-12-06 16:14:29 +0000554 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
555 BasicBlock *IBB = PN->getIncomingBlock(PI);
556 if (BBPreds.count(IBB) &&
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000557 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
558 PN->getIncomingValue(PI))) {
Jakub Staszaka18c5742013-07-22 23:16:36 +0000559 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
560 << Succ->getName() << " is conflicting with "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000561 << BBPN->getName() << " with regard to common predecessor "
Benjamin Kramer88c09142011-12-06 16:14:29 +0000562 << IBB->getName() << "\n");
Chris Lattnerdce94d92009-11-10 05:59:26 +0000563 return false;
564 }
565 }
566 } else {
567 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramer88c09142011-12-06 16:14:29 +0000568 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnerdce94d92009-11-10 05:59:26 +0000569 // See if the incoming value for the common predecessor is equal to the
570 // one for BB, in which case this phi node will not prevent the merging
571 // of the block.
Benjamin Kramer88c09142011-12-06 16:14:29 +0000572 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000573 if (BBPreds.count(IBB) &&
574 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Jakub Staszaka18c5742013-07-22 23:16:36 +0000575 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000576 << Succ->getName() << " is conflicting with regard to common "
Benjamin Kramer88c09142011-12-06 16:14:29 +0000577 << "predecessor " << IBB->getName() << "\n");
Chris Lattnerdce94d92009-11-10 05:59:26 +0000578 return false;
579 }
580 }
581 }
582 }
583
584 return true;
585}
586
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000587typedef SmallVector<BasicBlock *, 16> PredBlockVector;
588typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
589
590/// \brief Determines the value to use as the phi node input for a block.
591///
592/// Select between \p OldVal any value that we know flows from \p BB
593/// to a particular phi on the basis of which one (if either) is not
594/// undef. Update IncomingValues based on the selected value.
595///
596/// \param OldVal The value we are considering selecting.
597/// \param BB The block that the value flows in from.
598/// \param IncomingValues A map from block-to-value for other phi inputs
599/// that we have examined.
600///
601/// \returns the selected value.
602static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
603 IncomingValueMap &IncomingValues) {
604 if (!isa<UndefValue>(OldVal)) {
605 assert((!IncomingValues.count(BB) ||
606 IncomingValues.find(BB)->second == OldVal) &&
607 "Expected OldVal to match incoming value from BB!");
608
609 IncomingValues.insert(std::make_pair(BB, OldVal));
610 return OldVal;
611 }
612
613 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
614 if (It != IncomingValues.end()) return It->second;
615
616 return OldVal;
617}
618
619/// \brief Create a map from block to value for the operands of a
620/// given phi.
621///
622/// Create a map from block to value for each non-undef value flowing
623/// into \p PN.
624///
625/// \param PN The phi we are collecting the map for.
626/// \param IncomingValues [out] The map from block to value for this phi.
627static void gatherIncomingValuesToPhi(PHINode *PN,
628 IncomingValueMap &IncomingValues) {
629 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
630 BasicBlock *BB = PN->getIncomingBlock(i);
631 Value *V = PN->getIncomingValue(i);
632
633 if (!isa<UndefValue>(V))
634 IncomingValues.insert(std::make_pair(BB, V));
635 }
636}
637
638/// \brief Replace the incoming undef values to a phi with the values
639/// from a block-to-value map.
640///
641/// \param PN The phi we are replacing the undefs in.
642/// \param IncomingValues A map from block to value.
643static void replaceUndefValuesInPhi(PHINode *PN,
644 const IncomingValueMap &IncomingValues) {
645 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
646 Value *V = PN->getIncomingValue(i);
647
648 if (!isa<UndefValue>(V)) continue;
649
650 BasicBlock *BB = PN->getIncomingBlock(i);
651 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
652 if (It == IncomingValues.end()) continue;
653
654 PN->setIncomingValue(i, It->second);
655 }
656}
657
658/// \brief Replace a value flowing from a block to a phi with
659/// potentially multiple instances of that value flowing from the
660/// block's predecessors to the phi.
661///
662/// \param BB The block with the value flowing into the phi.
663/// \param BBPreds The predecessors of BB.
664/// \param PN The phi that we are updating.
665static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
666 const PredBlockVector &BBPreds,
667 PHINode *PN) {
668 Value *OldVal = PN->removeIncomingValue(BB, false);
669 assert(OldVal && "No entry in PHI for Pred BB!");
670
671 IncomingValueMap IncomingValues;
672
673 // We are merging two blocks - BB, and the block containing PN - and
674 // as a result we need to redirect edges from the predecessors of BB
675 // to go to the block containing PN, and update PN
676 // accordingly. Since we allow merging blocks in the case where the
677 // predecessor and successor blocks both share some predecessors,
678 // and where some of those common predecessors might have undef
679 // values flowing into PN, we want to rewrite those values to be
680 // consistent with the non-undef values.
681
682 gatherIncomingValuesToPhi(PN, IncomingValues);
683
684 // If this incoming value is one of the PHI nodes in BB, the new entries
685 // in the PHI node are the entries from the old PHI.
686 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
687 PHINode *OldValPN = cast<PHINode>(OldVal);
688 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
689 // Note that, since we are merging phi nodes and BB and Succ might
690 // have common predecessors, we could end up with a phi node with
691 // identical incoming branches. This will be cleaned up later (and
692 // will trigger asserts if we try to clean it up now, without also
693 // simplifying the corresponding conditional branch).
694 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
695 Value *PredVal = OldValPN->getIncomingValue(i);
696 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
697 IncomingValues);
698
699 // And add a new incoming value for this predecessor for the
700 // newly retargeted branch.
701 PN->addIncoming(Selected, PredBB);
702 }
703 } else {
704 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
705 // Update existing incoming values in PN for this
706 // predecessor of BB.
707 BasicBlock *PredBB = BBPreds[i];
708 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
709 IncomingValues);
710
711 // And add a new incoming value for this predecessor for the
712 // newly retargeted branch.
713 PN->addIncoming(Selected, PredBB);
714 }
715 }
716
717 replaceUndefValuesInPhi(PN, IncomingValues);
718}
719
Chris Lattnerdce94d92009-11-10 05:59:26 +0000720/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
721/// unconditional branch, and contains no instructions other than PHI nodes,
Rafael Espindola77a2c372011-06-30 20:14:24 +0000722/// potential side-effect free intrinsics and the branch. If possible,
723/// eliminate BB by rewriting all the predecessors to branch to the successor
724/// block and return true. If we can't transform, return false.
Chris Lattnerdce94d92009-11-10 05:59:26 +0000725bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
Dan Gohmane2c6d132010-08-14 00:29:42 +0000726 assert(BB != &BB->getParent()->getEntryBlock() &&
727 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
728
Chris Lattnerdce94d92009-11-10 05:59:26 +0000729 // We can't eliminate infinite loops.
730 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
731 if (BB == Succ) return false;
Jakub Staszaka18c5742013-07-22 23:16:36 +0000732
Chris Lattnerdce94d92009-11-10 05:59:26 +0000733 // Check to see if merging these blocks would cause conflicts for any of the
734 // phi nodes in BB or Succ. If not, we can safely merge.
735 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
736
737 // Check for cases where Succ has multiple predecessors and a PHI node in BB
738 // has uses which will not disappear when the PHI nodes are merged. It is
739 // possible to handle such cases, but difficult: it requires checking whether
740 // BB dominates Succ, which is non-trivial to calculate in the case where
741 // Succ has multiple predecessors. Also, it requires checking whether
Alexey Samsonov3a199992012-12-24 08:52:53 +0000742 // constructing the necessary self-referential PHI node doesn't introduce any
Chris Lattnerdce94d92009-11-10 05:59:26 +0000743 // conflicts; this isn't too difficult, but the previous code for doing this
744 // was incorrect.
745 //
746 // Note that if this check finds a live use, BB dominates Succ, so BB is
747 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
748 // folding the branch isn't profitable in that case anyway.
749 if (!Succ->getSinglePredecessor()) {
750 BasicBlock::iterator BBI = BB->begin();
751 while (isa<PHINode>(*BBI)) {
752 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
753 UI != E; ++UI) {
754 if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
755 if (PN->getIncomingBlock(UI) != BB)
756 return false;
757 } else {
758 return false;
759 }
760 }
761 ++BBI;
762 }
763 }
764
David Greenefae77062010-01-05 01:26:57 +0000765 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000766
Chris Lattnerdce94d92009-11-10 05:59:26 +0000767 if (isa<PHINode>(Succ->begin())) {
768 // If there is more than one pred of succ, and there are PHI nodes in
769 // the successor, then we need to add incoming edges for the PHI nodes
770 //
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000771 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
Jakub Staszaka18c5742013-07-22 23:16:36 +0000772
Chris Lattnerdce94d92009-11-10 05:59:26 +0000773 // Loop over all of the PHI nodes in the successor of BB.
774 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
775 PHINode *PN = cast<PHINode>(I);
Duncan Sandsc48b55a2013-07-11 08:28:20 +0000776
777 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
Chris Lattnerdce94d92009-11-10 05:59:26 +0000778 }
779 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000780
Rafael Espindola77a2c372011-06-30 20:14:24 +0000781 if (Succ->getSinglePredecessor()) {
782 // BB is the only predecessor of Succ, so Succ will end up with exactly
783 // the same predecessors BB had.
784
785 // Copy over any phi, debug or lifetime instruction.
786 BB->getTerminator()->eraseFromParent();
787 Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
788 } else {
789 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattnerdce94d92009-11-10 05:59:26 +0000790 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
791 assert(PN->use_empty() && "There shouldn't be any uses here!");
792 PN->eraseFromParent();
793 }
794 }
Jakub Staszaka18c5742013-07-22 23:16:36 +0000795
Chris Lattnerdce94d92009-11-10 05:59:26 +0000796 // Everything that jumped to BB now goes to Succ.
797 BB->replaceAllUsesWith(Succ);
798 if (!Succ->hasName()) Succ->takeName(BB);
799 BB->eraseFromParent(); // Delete the old basic block.
800 return true;
801}
802
Jim Grosbach43a82412009-12-02 17:06:45 +0000803/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
804/// nodes in this block. This doesn't try to be clever about PHI nodes
805/// which differ only in the order of the incoming values, but instcombine
806/// orders them so it usually won't matter.
807///
808bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
809 bool Changed = false;
810
811 // This implementation doesn't currently consider undef operands
Nick Lewycky89991d42011-06-28 03:57:31 +0000812 // specially. Theoretically, two phis which are identical except for
Jim Grosbach43a82412009-12-02 17:06:45 +0000813 // one having an undef where the other doesn't could be collapsed.
814
815 // Map from PHI hash values to PHI nodes. If multiple PHIs have
816 // the same hash value, the element is the first PHI in the
817 // linked list in CollisionMap.
818 DenseMap<uintptr_t, PHINode *> HashMap;
819
820 // Maintain linked lists of PHI nodes with common hash values.
821 DenseMap<PHINode *, PHINode *> CollisionMap;
822
823 // Examine each PHI.
824 for (BasicBlock::iterator I = BB->begin();
825 PHINode *PN = dyn_cast<PHINode>(I++); ) {
826 // Compute a hash value on the operands. Instcombine will likely have sorted
827 // them, which helps expose duplicates, but we have to check all the
828 // operands to be safe in case instcombine hasn't run.
829 uintptr_t Hash = 0;
Jay Foad95c3e482011-06-23 09:09:15 +0000830 // This hash algorithm is quite weak as hash functions go, but it seems
831 // to do a good enough job for this particular purpose, and is very quick.
Jim Grosbach43a82412009-12-02 17:06:45 +0000832 for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
Jim Grosbach43a82412009-12-02 17:06:45 +0000833 Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
834 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
835 }
Jay Foad95c3e482011-06-23 09:09:15 +0000836 for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
837 I != E; ++I) {
838 Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
839 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
840 }
Jakob Stoklund Olesen2bc2a082011-03-04 02:48:56 +0000841 // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
842 Hash >>= 1;
Jim Grosbach43a82412009-12-02 17:06:45 +0000843 // If we've never seen this hash value before, it's a unique PHI.
844 std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
845 HashMap.insert(std::make_pair(Hash, PN));
846 if (Pair.second) continue;
847 // Otherwise it's either a duplicate or a hash collision.
848 for (PHINode *OtherPN = Pair.first->second; ; ) {
849 if (OtherPN->isIdenticalTo(PN)) {
850 // A duplicate. Replace this PHI with its duplicate.
851 PN->replaceAllUsesWith(OtherPN);
852 PN->eraseFromParent();
853 Changed = true;
854 break;
855 }
856 // A non-duplicate hash collision.
857 DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
858 if (I == CollisionMap.end()) {
859 // Set this PHI to be the head of the linked list of colliding PHIs.
860 PHINode *Old = Pair.first->second;
861 Pair.first->second = PN;
862 CollisionMap[PN] = Old;
863 break;
864 }
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000865 // Proceed to the next PHI in the list.
Jim Grosbach43a82412009-12-02 17:06:45 +0000866 OtherPN = I->second;
867 }
868 }
869
870 return Changed;
871}
Chris Lattner687140c2010-12-25 20:37:57 +0000872
873/// enforceKnownAlignment - If the specified pointer points to an object that
874/// we control, modify the object's alignment to PrefAlign. This isn't
875/// often possible though. If alignment is important, a more reliable approach
876/// is to simply align all global variables and allocation instructions to
877/// their preferred alignment from the beginning.
878///
Benjamin Kramer19282362010-12-30 22:34:44 +0000879static unsigned enforceKnownAlignment(Value *V, unsigned Align,
Micah Villmow3574eca2012-10-08 16:38:25 +0000880 unsigned PrefAlign, const DataLayout *TD) {
Eli Friedmanb53c7932011-06-15 21:08:25 +0000881 V = V->stripPointerCasts();
Chris Lattner687140c2010-12-25 20:37:57 +0000882
Eli Friedmanb53c7932011-06-15 21:08:25 +0000883 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Lang Hamesbb5b3f32011-10-10 23:42:08 +0000884 // If the preferred alignment is greater than the natural stack alignment
885 // then don't round up. This avoids dynamic stack realignment.
886 if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
887 return Align;
Chris Lattner687140c2010-12-25 20:37:57 +0000888 // If there is a requested alignment and if this is an alloca, round up.
889 if (AI->getAlignment() >= PrefAlign)
890 return AI->getAlignment();
891 AI->setAlignment(PrefAlign);
892 return PrefAlign;
893 }
Chris Lattner687140c2010-12-25 20:37:57 +0000894
895 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
896 // If there is a large requested alignment and we can, bump up the alignment
897 // of the global.
898 if (GV->isDeclaration()) return Align;
Duncan Sandsd3a38cc2011-11-29 18:26:38 +0000899 // If the memory we set aside for the global may not be the memory used by
900 // the final program then it is impossible for us to reliably enforce the
901 // preferred alignment.
902 if (GV->isWeakForLinker()) return Align;
Jakub Staszaka18c5742013-07-22 23:16:36 +0000903
Chris Lattner687140c2010-12-25 20:37:57 +0000904 if (GV->getAlignment() >= PrefAlign)
905 return GV->getAlignment();
906 // We can only increase the alignment of the global if it has no alignment
907 // specified or if it is not assigned a section. If it is assigned a
908 // section, the global could be densely packed with other objects in the
909 // section, increasing the alignment could cause padding issues.
910 if (!GV->hasSection() || GV->getAlignment() == 0)
911 GV->setAlignment(PrefAlign);
912 return GV->getAlignment();
913 }
914
915 return Align;
916}
917
918/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
919/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
920/// and it is more than the alignment of the ultimate object, see if we can
921/// increase the alignment of the ultimate object, making this check succeed.
922unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Matt Arsenault186f8f92013-08-01 22:42:18 +0000923 const DataLayout *DL) {
Chris Lattner687140c2010-12-25 20:37:57 +0000924 assert(V->getType()->isPointerTy() &&
925 "getOrEnforceKnownAlignment expects a pointer!");
Matt Arsenault186f8f92013-08-01 22:42:18 +0000926 unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
927
Chris Lattner687140c2010-12-25 20:37:57 +0000928 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Matt Arsenault186f8f92013-08-01 22:42:18 +0000929 ComputeMaskedBits(V, KnownZero, KnownOne, DL);
Chris Lattner687140c2010-12-25 20:37:57 +0000930 unsigned TrailZ = KnownZero.countTrailingOnes();
Jakub Staszaka18c5742013-07-22 23:16:36 +0000931
Matt Arsenault59a38782013-07-23 22:20:57 +0000932 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner687140c2010-12-25 20:37:57 +0000933 // those computed from a null pointer.
934 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszaka18c5742013-07-22 23:16:36 +0000935
Chris Lattner687140c2010-12-25 20:37:57 +0000936 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000937
Chris Lattner687140c2010-12-25 20:37:57 +0000938 // LLVM doesn't support alignments larger than this currently.
939 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000940
Chris Lattner687140c2010-12-25 20:37:57 +0000941 if (PrefAlign > Align)
Matt Arsenault186f8f92013-08-01 22:42:18 +0000942 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszaka18c5742013-07-22 23:16:36 +0000943
Chris Lattner687140c2010-12-25 20:37:57 +0000944 // We don't need to make any adjustment.
945 return Align;
946}
947
Devang Patel5ee20682011-03-17 21:58:19 +0000948///===---------------------------------------------------------------------===//
949/// Dbg Intrinsic utilities
950///
951
Adrian Prantl163da932013-04-26 17:48:33 +0000952/// See if there is a dbg.value intrinsic for DIVar before I.
953static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
954 // Since we can't guarantee that the original dbg.declare instrinsic
955 // is removed by LowerDbgDeclare(), we need to make sure that we are
956 // not inserting the same dbg.value intrinsic over and over.
957 llvm::BasicBlock::InstListType::iterator PrevI(I);
958 if (PrevI != I->getParent()->getInstList().begin()) {
959 --PrevI;
960 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
961 if (DVI->getValue() == I->getOperand(0) &&
962 DVI->getOffset() == 0 &&
963 DVI->getVariable() == DIVar)
964 return true;
965 }
966 return false;
967}
968
Adrian Prantl9d5d58a2013-04-26 18:10:50 +0000969/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Devang Patel5ee20682011-03-17 21:58:19 +0000970/// that has an associated llvm.dbg.decl intrinsic.
971bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
972 StoreInst *SI, DIBuilder &Builder) {
973 DIVariable DIVar(DDI->getVariable());
Manman Rencbafae62013-06-28 05:43:10 +0000974 assert((!DIVar || DIVar.isVariable()) &&
975 "Variable in DbgDeclareInst should be either null or a DIVariable.");
976 if (!DIVar)
Devang Patel5ee20682011-03-17 21:58:19 +0000977 return false;
978
Adrian Prantl163da932013-04-26 17:48:33 +0000979 if (LdStHasDebugValue(DIVar, SI))
980 return true;
981
Devang Patel227dfdb2011-05-16 21:24:05 +0000982 Instruction *DbgVal = NULL;
983 // If an argument is zero extended then use argument directly. The ZExt
984 // may be zapped by an optimization pass in future.
985 Argument *ExtendedArg = NULL;
986 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
987 ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
988 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
989 ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
990 if (ExtendedArg)
991 DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
992 else
993 DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
994
Devang Patel5ee20682011-03-17 21:58:19 +0000995 // Propagate any debug metadata from the store onto the dbg.value.
996 DebugLoc SIDL = SI->getDebugLoc();
997 if (!SIDL.isUnknown())
998 DbgVal->setDebugLoc(SIDL);
999 // Otherwise propagate debug metadata from dbg.declare.
1000 else
1001 DbgVal->setDebugLoc(DDI->getDebugLoc());
1002 return true;
1003}
1004
Adrian Prantl9d5d58a2013-04-26 18:10:50 +00001005/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Devang Patel36fae672011-03-18 23:45:43 +00001006/// that has an associated llvm.dbg.decl intrinsic.
1007bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1008 LoadInst *LI, DIBuilder &Builder) {
1009 DIVariable DIVar(DDI->getVariable());
Jakub Staszaka18c5742013-07-22 23:16:36 +00001010 assert((!DIVar || DIVar.isVariable()) &&
Manman Rencbafae62013-06-28 05:43:10 +00001011 "Variable in DbgDeclareInst should be either null or a DIVariable.");
1012 if (!DIVar)
Devang Patel36fae672011-03-18 23:45:43 +00001013 return false;
1014
Adrian Prantl163da932013-04-26 17:48:33 +00001015 if (LdStHasDebugValue(DIVar, LI))
1016 return true;
1017
Jakub Staszaka18c5742013-07-22 23:16:36 +00001018 Instruction *DbgVal =
Devang Patel36fae672011-03-18 23:45:43 +00001019 Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
1020 DIVar, LI);
Jakub Staszaka18c5742013-07-22 23:16:36 +00001021
Devang Patel36fae672011-03-18 23:45:43 +00001022 // Propagate any debug metadata from the store onto the dbg.value.
1023 DebugLoc LIDL = LI->getDebugLoc();
1024 if (!LIDL.isUnknown())
1025 DbgVal->setDebugLoc(LIDL);
1026 // Otherwise propagate debug metadata from dbg.declare.
1027 else
1028 DbgVal->setDebugLoc(DDI->getDebugLoc());
1029 return true;
1030}
1031
Devang Patel813c9a02011-03-17 22:18:16 +00001032/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1033/// of llvm.dbg.value intrinsics.
1034bool llvm::LowerDbgDeclare(Function &F) {
1035 DIBuilder DIB(*F.getParent());
1036 SmallVector<DbgDeclareInst *, 4> Dbgs;
1037 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1038 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
1039 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1040 Dbgs.push_back(DDI);
1041 }
1042 if (Dbgs.empty())
1043 return false;
1044
Craig Topper6227d5c2013-07-04 01:31:24 +00001045 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = Dbgs.begin(),
Devang Patel813c9a02011-03-17 22:18:16 +00001046 E = Dbgs.end(); I != E; ++I) {
1047 DbgDeclareInst *DDI = *I;
1048 if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
Adrian Prantl163da932013-04-26 17:48:33 +00001049 // We only remove the dbg.declare intrinsic if all uses are
1050 // converted to dbg.value intrinsics.
Devang Patel81ad03c2011-04-28 20:32:02 +00001051 bool RemoveDDI = true;
Devang Patel813c9a02011-03-17 22:18:16 +00001052 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1053 UI != E; ++UI)
1054 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
1055 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
Devang Patel36fae672011-03-18 23:45:43 +00001056 else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1057 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Devang Patel81ad03c2011-04-28 20:32:02 +00001058 else
1059 RemoveDDI = false;
1060 if (RemoveDDI)
1061 DDI->eraseFromParent();
Devang Patel813c9a02011-03-17 22:18:16 +00001062 }
Devang Patel813c9a02011-03-17 22:18:16 +00001063 }
1064 return true;
1065}
Cameron Zwarichc8279392011-05-24 03:10:43 +00001066
1067/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1068/// alloca 'V', if any.
1069DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1070 if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
1071 for (Value::use_iterator UI = DebugNode->use_begin(),
1072 E = DebugNode->use_end(); UI != E; ++UI)
1073 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1074 return DDI;
1075
1076 return 0;
1077}
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001078
1079bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1080 DIBuilder &Builder) {
1081 DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
1082 if (!DDI)
1083 return false;
1084 DIVariable DIVar(DDI->getVariable());
Jakub Staszaka18c5742013-07-22 23:16:36 +00001085 assert((!DIVar || DIVar.isVariable()) &&
Manman Rencbafae62013-06-28 05:43:10 +00001086 "Variable in DbgDeclareInst should be either null or a DIVariable.");
1087 if (!DIVar)
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001088 return false;
1089
1090 // Create a copy of the original DIDescriptor for user variable, appending
1091 // "deref" operation to a list of address elements, as new llvm.dbg.declare
1092 // will take a value storing address of the memory for variable, not
1093 // alloca itself.
1094 Type *Int64Ty = Type::getInt64Ty(AI->getContext());
1095 SmallVector<Value*, 4> NewDIVarAddress;
1096 if (DIVar.hasComplexAddress()) {
1097 for (unsigned i = 0, n = DIVar.getNumAddrElements(); i < n; ++i) {
1098 NewDIVarAddress.push_back(
1099 ConstantInt::get(Int64Ty, DIVar.getAddrElement(i)));
1100 }
1101 }
1102 NewDIVarAddress.push_back(ConstantInt::get(Int64Ty, DIBuilder::OpDeref));
1103 DIVariable NewDIVar = Builder.createComplexVariable(
1104 DIVar.getTag(), DIVar.getContext(), DIVar.getName(),
1105 DIVar.getFile(), DIVar.getLineNumber(), DIVar.getType(),
1106 NewDIVarAddress, DIVar.getArgNumber());
1107
1108 // Insert llvm.dbg.declare in the same basic block as the original alloca,
1109 // and remove old llvm.dbg.declare.
1110 BasicBlock *BB = AI->getParent();
1111 Builder.insertDeclare(NewAllocaAddress, NewDIVar, BB);
1112 DDI->eraseFromParent();
1113 return true;
1114}
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001115
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001116/// changeToUnreachable - Insert an unreachable instruction before the specified
1117/// instruction, making it and the rest of the code in the block dead.
1118static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
1119 BasicBlock *BB = I->getParent();
1120 // Loop over all of the successors, removing BB's entry from any PHI
1121 // nodes.
1122 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1123 (*SI)->removePredecessor(BB);
1124
1125 // Insert a call to llvm.trap right before this. This turns the undefined
1126 // behavior into a hard fail instead of falling through into random code.
1127 if (UseLLVMTrap) {
1128 Function *TrapFn =
1129 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1130 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1131 CallTrap->setDebugLoc(I->getDebugLoc());
1132 }
1133 new UnreachableInst(I->getContext(), I);
1134
1135 // All instructions after this are dead.
1136 BasicBlock::iterator BBI = I, BBE = BB->end();
1137 while (BBI != BBE) {
1138 if (!BBI->use_empty())
1139 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1140 BB->getInstList().erase(BBI++);
1141 }
1142}
1143
1144/// changeToCall - Convert the specified invoke into a normal call.
1145static void changeToCall(InvokeInst *II) {
1146 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
1147 CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
1148 NewCall->takeName(II);
1149 NewCall->setCallingConv(II->getCallingConv());
1150 NewCall->setAttributes(II->getAttributes());
1151 NewCall->setDebugLoc(II->getDebugLoc());
1152 II->replaceAllUsesWith(NewCall);
1153
1154 // Follow the call by a branch to the normal destination.
1155 BranchInst::Create(II->getNormalDest(), II);
1156
1157 // Update PHI nodes in the unwind destination
1158 II->getUnwindDest()->removePredecessor(II->getParent());
1159 II->eraseFromParent();
1160}
1161
1162static bool markAliveBlocks(BasicBlock *BB,
1163 SmallPtrSet<BasicBlock*, 128> &Reachable) {
1164
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001165 SmallVector<BasicBlock*, 128> Worklist;
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001166 Worklist.push_back(BB);
1167 Reachable.insert(BB);
1168 bool Changed = false;
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001169 do {
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001170 BB = Worklist.pop_back_val();
1171
1172 // Do a quick scan of the basic block, turning any obviously unreachable
1173 // instructions into LLVM unreachable insts. The instruction combining pass
1174 // canonicalizes unreachable insts into stores to null or undef.
1175 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
1176 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
1177 if (CI->doesNotReturn()) {
1178 // If we found a call to a no-return function, insert an unreachable
1179 // instruction after it. Make sure there isn't *already* one there
1180 // though.
1181 ++BBI;
1182 if (!isa<UnreachableInst>(BBI)) {
1183 // Don't insert a call to llvm.trap right before the unreachable.
1184 changeToUnreachable(BBI, false);
1185 Changed = true;
1186 }
1187 break;
1188 }
1189 }
1190
1191 // Store to undef and store to null are undefined and used to signal that
1192 // they should be changed to unreachable by passes that can't modify the
1193 // CFG.
1194 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
1195 // Don't touch volatile stores.
1196 if (SI->isVolatile()) continue;
1197
1198 Value *Ptr = SI->getOperand(1);
1199
1200 if (isa<UndefValue>(Ptr) ||
1201 (isa<ConstantPointerNull>(Ptr) &&
1202 SI->getPointerAddressSpace() == 0)) {
1203 changeToUnreachable(SI, true);
1204 Changed = true;
1205 break;
1206 }
1207 }
1208 }
1209
1210 // Turn invokes that call 'nounwind' functions into ordinary calls.
1211 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
1212 Value *Callee = II->getCalledValue();
1213 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1214 changeToUnreachable(II, true);
1215 Changed = true;
1216 } else if (II->doesNotThrow()) {
1217 if (II->use_empty() && II->onlyReadsMemory()) {
1218 // jump to the normal destination branch.
1219 BranchInst::Create(II->getNormalDest(), II);
1220 II->getUnwindDest()->removePredecessor(II->getParent());
1221 II->eraseFromParent();
1222 } else
1223 changeToCall(II);
1224 Changed = true;
1225 }
1226 }
1227
1228 Changed |= ConstantFoldTerminator(BB, true);
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001229 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1230 if (Reachable.insert(*SI))
1231 Worklist.push_back(*SI);
1232 } while (!Worklist.empty());
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001233 return Changed;
1234}
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001235
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001236/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1237/// if they are in a dead cycle. Return true if a change was made, false
1238/// otherwise.
1239bool llvm::removeUnreachableBlocks(Function &F) {
1240 SmallPtrSet<BasicBlock*, 128> Reachable;
1241 bool Changed = markAliveBlocks(F.begin(), Reachable);
1242
1243 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001244 if (Reachable.size() == F.size())
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001245 return Changed;
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001246
1247 assert(Reachable.size() < F.size());
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001248 NumRemoved += F.size()-Reachable.size();
1249
1250 // Loop over all of the basic blocks that are not reachable, dropping all of
1251 // their internal references...
1252 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1253 if (Reachable.count(BB))
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001254 continue;
1255
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001256 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001257 if (Reachable.count(*SI))
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001258 (*SI)->removePredecessor(BB);
1259 BB->dropAllReferences();
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001260 }
Evgeniy Stepanov7541cd32013-03-22 08:43:04 +00001261
Peter Collingbourne4f96b7e2013-08-12 22:38:43 +00001262 for (Function::iterator I = ++F.begin(); I != F.end();)
Evgeniy Stepanov7541cd32013-03-22 08:43:04 +00001263 if (!Reachable.count(I))
1264 I = F.getBasicBlockList().erase(I);
1265 else
1266 ++I;
1267
Evgeniy Stepanov3333e662012-12-21 11:18:49 +00001268 return true;
1269}