blob: cc508a47de35e1bfd740a0617155848aa1ee2d6f [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 Lattner6cc8a932009-06-16 17:23:12 +000017#include "llvm/GlobalAlias.h"
Devang Patelc79e1182009-03-06 00:19:37 +000018#include "llvm/GlobalVariable.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000020#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000021#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000022#include "llvm/IntrinsicInst.h"
Jay Foad562b84b2011-04-11 09:35:34 +000023#include "llvm/Operator.h"
Chris Lattner19f2dc42009-12-29 09:12:29 +000024#include "llvm/ADT/DenseMap.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000025#include "llvm/ADT/SmallPtrSet.h"
Devang Patel5ee20682011-03-17 21:58:19 +000026#include "llvm/Analysis/DebugInfo.h"
27#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000028#include "llvm/Analysis/Dominators.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000029#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner40d8c282009-11-10 22:26:15 +000030#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000031#include "llvm/Analysis/ProfileInfo.h"
Chris Lattner687140c2010-12-25 20:37:57 +000032#include "llvm/Analysis/ValueTracking.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000033#include "llvm/Target/TargetData.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000034#include "llvm/Support/CFG.h"
35#include "llvm/Support/Debug.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
37#include "llvm/Support/MathExtras.h"
Chris Lattner19f2dc42009-12-29 09:12:29 +000038#include "llvm/Support/ValueHandle.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000039#include "llvm/Support/raw_ostream.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000040using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000041
Chris Lattner4d1e46e2002-05-07 18:07:59 +000042//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000043// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000044//
45
Chris Lattner4d1e46e2002-05-07 18:07:59 +000046// ConstantFoldTerminator - If a terminator instruction is predicated on a
47// constant value, convert it into an unconditional branch to the constant
48// destination.
49//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000050bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000051 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000052
Chris Lattner4d1e46e2002-05-07 18:07:59 +000053 // Branch - See if we are conditional jumping on constant
54 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
55 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +000056 BasicBlock *Dest1 = BI->getSuccessor(0);
57 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000058
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000059 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000060 // Are we branching on constant?
61 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000062 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
63 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000064
Misha Brukmanfd939082005-04-21 23:48:37 +000065 //cerr << "Function: " << T->getParent()->getParent()
66 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000067 // << "\n\nTo: " << OldDest << endl;
68
69 // Let the basic block know that we are letting go of it. Based on this,
70 // it will adjust it's PHI nodes.
71 assert(BI->getParent() && "Terminator not inserted in block!");
72 OldDest->removePredecessor(BI->getParent());
73
Jay Foad8f9ffbd2011-01-07 20:25:56 +000074 // Replace the conditional branch with an unconditional one.
75 BranchInst::Create(Destination, BI);
76 BI->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +000077 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +000078 }
79
80 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000081 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000082 // br bool %cond, label %Dest, label %Dest
83 // and changes it into: br label %Dest
84
85 // Let the basic block know that we are letting go of one copy of it.
86 assert(BI->getParent() && "Terminator not inserted in block!");
87 Dest1->removePredecessor(BI->getParent());
88
Jay Foad8f9ffbd2011-01-07 20:25:56 +000089 // Replace the conditional branch with an unconditional one.
90 BranchInst::Create(Dest1, BI);
91 BI->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +000092 return true;
93 }
Chris Lattner0a4c6782009-11-01 03:40:38 +000094 return false;
95 }
96
97 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +000098 // If we are switching on a constant, we can convert the switch into a
99 // single branch instruction!
100 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
101 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000102 BasicBlock *DefaultDest = TheOnlyDest;
103 assert(TheOnlyDest == SI->getDefaultDest() &&
104 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000105
Chris Lattner0a4c6782009-11-01 03:40:38 +0000106 // Figure out which case it goes to.
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000107 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
108 // Found case matching a constant operand?
109 if (SI->getSuccessorValue(i) == CI) {
110 TheOnlyDest = SI->getSuccessor(i);
111 break;
112 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000113
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000114 // Check to see if this branch is going to the same place as the default
115 // dest. If so, eliminate it as an explicit compare.
116 if (SI->getSuccessor(i) == DefaultDest) {
Chris Lattner0a4c6782009-11-01 03:40:38 +0000117 // Remove this entry.
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000118 DefaultDest->removePredecessor(SI->getParent());
119 SI->removeCase(i);
120 --i; --e; // Don't skip an entry...
121 continue;
122 }
123
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000124 // Otherwise, check to see if the switch only branches to one destination.
125 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
126 // destinations.
127 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000128 }
129
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000130 if (CI && !TheOnlyDest) {
131 // Branching on a constant, but not any of the cases, go to the default
132 // successor.
133 TheOnlyDest = SI->getDefaultDest();
134 }
135
136 // If we found a single destination that we can fold the switch into, do so
137 // now.
138 if (TheOnlyDest) {
Chris Lattner0a4c6782009-11-01 03:40:38 +0000139 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000140 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000141 BasicBlock *BB = SI->getParent();
142
143 // Remove entries from PHI nodes which we no longer branch to...
144 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
145 // Found case matching a constant operand?
146 BasicBlock *Succ = SI->getSuccessor(i);
147 if (Succ == TheOnlyDest)
148 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
149 else
150 Succ->removePredecessor(BB);
151 }
152
Chris Lattner0a4c6782009-11-01 03:40:38 +0000153 // Delete the old switch.
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000154 BB->getInstList().erase(SI);
155 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +0000156 }
157
158 if (SI->getNumSuccessors() == 2) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000159 // Otherwise, we can fold this switch into a conditional branch
160 // instruction if it has only one non-default destination.
Owen Anderson333c4002009-07-09 23:48:35 +0000161 Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
162 SI->getSuccessorValue(1), "cond");
Chris Lattner0a4c6782009-11-01 03:40:38 +0000163 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000164 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000165
Chris Lattner0a4c6782009-11-01 03:40:38 +0000166 // Delete the old switch.
Dan Gohman1adec832008-06-21 22:08:46 +0000167 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000168 return true;
169 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000170 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000171 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000172
173 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
174 // indirectbr blockaddress(@F, @BB) -> br label @BB
175 if (BlockAddress *BA =
176 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
177 BasicBlock *TheOnlyDest = BA->getBasicBlock();
178 // Insert the new branch.
179 BranchInst::Create(TheOnlyDest, IBI);
180
181 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
182 if (IBI->getDestination(i) == TheOnlyDest)
183 TheOnlyDest = 0;
184 else
185 IBI->getDestination(i)->removePredecessor(IBI->getParent());
186 }
187 IBI->eraseFromParent();
188
189 // If we didn't find our destination in the IBI successor list, then we
190 // have undefined behavior. Replace the unconditional branch with an
191 // 'unreachable' instruction.
192 if (TheOnlyDest) {
193 BB->getTerminator()->eraseFromParent();
194 new UnreachableInst(BB->getContext(), BB);
195 }
196
197 return true;
198 }
199 }
200
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000201 return false;
202}
203
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000204
205//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000206// Local dead code elimination.
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000207//
208
Chris Lattner3481f242008-11-27 22:57:53 +0000209/// isInstructionTriviallyDead - Return true if the result produced by the
210/// instruction is not used, and the instruction has no side effects.
211///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000212bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000213 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000214
Devang Patel9c5822a2011-03-18 23:28:02 +0000215 // We don't want debug info removed by anything this general, unless
216 // debug info is empty.
217 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
218 if (DDI->getAddress())
219 return false;
Devang Patelb9946212011-03-21 22:04:45 +0000220 return true;
221 }
222 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patel9c5822a2011-03-18 23:28:02 +0000223 if (DVI->getValue())
224 return false;
Devang Patelb9946212011-03-21 22:04:45 +0000225 return true;
Devang Patel9c5822a2011-03-18 23:28:02 +0000226 }
227
Duncan Sands7af1c782009-05-06 06:49:50 +0000228 if (!I->mayHaveSideEffects()) return true;
229
230 // Special case intrinsics that "may have side effects" but can be deleted
231 // when dead.
Chris Lattner741c0ae2007-12-29 00:59:12 +0000232 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
233 // Safe to delete llvm.stacksave if dead.
234 if (II->getIntrinsicID() == Intrinsic::stacksave)
235 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000236 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000237}
238
Chris Lattner3481f242008-11-27 22:57:53 +0000239/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
240/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000241/// trivially dead, delete them too, recursively. Return true if any
242/// instructions were deleted.
243bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
Chris Lattner3481f242008-11-27 22:57:53 +0000244 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000245 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000246 return false;
Chris Lattner3481f242008-11-27 22:57:53 +0000247
Chris Lattner76057302008-11-28 01:20:46 +0000248 SmallVector<Instruction*, 16> DeadInsts;
249 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000250
Dan Gohman321a8132010-01-05 16:27:25 +0000251 do {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000252 I = DeadInsts.pop_back_val();
Chris Lattner28721772008-11-28 00:58:15 +0000253
Chris Lattner76057302008-11-28 01:20:46 +0000254 // Null out all of the instruction's operands to see if any operand becomes
255 // dead as we go.
256 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
257 Value *OpV = I->getOperand(i);
258 I->setOperand(i, 0);
259
260 if (!OpV->use_empty()) continue;
261
262 // If the operand is an instruction that became dead as we nulled out the
263 // operand, and if it is 'trivially' dead, delete it in a future loop
264 // iteration.
265 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
266 if (isInstructionTriviallyDead(OpI))
267 DeadInsts.push_back(OpI);
268 }
269
270 I->eraseFromParent();
Dan Gohman321a8132010-01-05 16:27:25 +0000271 } while (!DeadInsts.empty());
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000272
273 return true;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000274}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000275
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000276/// areAllUsesEqual - Check whether the uses of a value are all the same.
277/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000278/// true when there are no uses or multiple uses that all refer to the same
279/// value.
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000280static bool areAllUsesEqual(Instruction *I) {
281 Value::use_iterator UI = I->use_begin();
282 Value::use_iterator UE = I->use_end();
283 if (UI == UE)
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000284 return true;
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000285
286 User *TheUse = *UI;
287 for (++UI; UI != UE; ++UI) {
288 if (*UI != TheUse)
289 return false;
290 }
291 return true;
292}
293
Dan Gohmanafc36a92009-05-02 18:29:22 +0000294/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
295/// dead PHI node, due to being a def-use chain of single-use nodes that
296/// either forms a cycle or is terminated by a trivially dead instruction,
297/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sands2cfbf012011-02-21 17:32:05 +0000298/// too, recursively. Return true if a change was made.
Nick Lewycky1a4021a2011-02-20 08:38:20 +0000299bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000300 SmallPtrSet<Instruction*, 4> Visited;
301 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
302 I = cast<Instruction>(*I->use_begin())) {
303 if (I->use_empty())
304 return RecursivelyDeleteTriviallyDeadInstructions(I);
Nick Lewyckyeff5e692011-02-20 18:05:56 +0000305
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000306 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanafc36a92009-05-02 18:29:22 +0000307 // won't prove fruitful.
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000308 if (!Visited.insert(I)) {
309 // Break the cycle and delete the instruction and its operands.
310 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Duncan Sands2cfbf012011-02-21 17:32:05 +0000311 (void)RecursivelyDeleteTriviallyDeadInstructions(I);
312 return true;
Duncan Sandsb4098ba2011-02-21 16:27:36 +0000313 }
314 }
315 return false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000316}
Chris Lattner3481f242008-11-27 22:57:53 +0000317
Chris Lattnere234a302010-01-12 19:40:54 +0000318/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
319/// simplify any instructions in it and recursively delete dead instructions.
320///
321/// This returns true if it changed the code, note that it can delete
322/// instructions in other blocks as well in this block.
323bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
324 bool MadeChange = false;
325 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
326 Instruction *Inst = BI++;
327
328 if (Value *V = SimplifyInstruction(Inst, TD)) {
329 WeakVH BIHandle(BI);
330 ReplaceAndSimplifyAllUses(Inst, V, TD);
331 MadeChange = true;
Chris Lattner35a939b2010-07-15 06:06:04 +0000332 if (BIHandle != BI)
Chris Lattnere234a302010-01-12 19:40:54 +0000333 BI = BB->begin();
334 continue;
335 }
Eli Friedman71ad2c92011-04-02 22:45:17 +0000336
Eli Friedmaneeb7f4c2011-04-04 00:37:38 +0000337 if (Inst->isTerminator())
338 break;
339
Eli Friedman71ad2c92011-04-02 22:45:17 +0000340 WeakVH BIHandle(BI);
Chris Lattnere234a302010-01-12 19:40:54 +0000341 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
Eli Friedman71ad2c92011-04-02 22:45:17 +0000342 if (BIHandle != BI)
343 BI = BB->begin();
Chris Lattnere234a302010-01-12 19:40:54 +0000344 }
345 return MadeChange;
346}
347
Chris Lattnerb29714a2008-11-27 07:43:12 +0000348//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000349// Control Flow Graph Restructuring.
Chris Lattnerb29714a2008-11-27 07:43:12 +0000350//
351
Chris Lattner40d8c282009-11-10 22:26:15 +0000352
353/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
354/// method is called when we're about to delete Pred as a predecessor of BB. If
355/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
356///
357/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
358/// nodes that collapse into identity values. For example, if we have:
359/// x = phi(1, 0, 0, 0)
360/// y = and x, z
361///
362/// .. and delete the predecessor corresponding to the '1', this will attempt to
363/// recursively fold the and to 0.
364void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
365 TargetData *TD) {
366 // This only adjusts blocks with PHI nodes.
367 if (!isa<PHINode>(BB->begin()))
368 return;
369
370 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
371 // them down. This will leave us with single entry phi nodes and other phis
372 // that can be removed.
373 BB->removePredecessor(Pred, true);
374
375 WeakVH PhiIt = &BB->front();
376 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
377 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Duncan Sands6ac33862010-11-17 04:12:05 +0000378
379 Value *PNV = SimplifyInstruction(PN, TD);
Chris Lattner40d8c282009-11-10 22:26:15 +0000380 if (PNV == 0) continue;
Duncan Sands6ac33862010-11-17 04:12:05 +0000381
Chris Lattner40d8c282009-11-10 22:26:15 +0000382 // If we're able to simplify the phi to a single value, substitute the new
383 // value into all of its uses.
Duncan Sands6ac33862010-11-17 04:12:05 +0000384 assert(PNV != PN && "SimplifyInstruction broken!");
Chris Lattner40d8c282009-11-10 22:26:15 +0000385
Chris Lattner35a939b2010-07-15 06:06:04 +0000386 Value *OldPhiIt = PhiIt;
Chris Lattner40d8c282009-11-10 22:26:15 +0000387 ReplaceAndSimplifyAllUses(PN, PNV, TD);
388
389 // If recursive simplification ended up deleting the next PHI node we would
390 // iterate to, then our iterator is invalid, restart scanning from the top
391 // of the block.
Chris Lattner35a939b2010-07-15 06:06:04 +0000392 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner40d8c282009-11-10 22:26:15 +0000393 }
394}
395
396
Chris Lattnerb29714a2008-11-27 07:43:12 +0000397/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
398/// predecessor is known to have one successor (DestBB!). Eliminate the edge
399/// between them, moving the instructions in the predecessor into DestBB and
400/// deleting the predecessor block.
401///
Andreas Neustifterad809812009-09-16 09:26:52 +0000402void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
Chris Lattnerb29714a2008-11-27 07:43:12 +0000403 // If BB has single-entry PHI nodes, fold them.
404 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
405 Value *NewVal = PN->getIncomingValue(0);
406 // Replace self referencing PHI with undef, it must be dead.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000407 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattnerb29714a2008-11-27 07:43:12 +0000408 PN->replaceAllUsesWith(NewVal);
409 PN->eraseFromParent();
410 }
411
412 BasicBlock *PredBB = DestBB->getSinglePredecessor();
413 assert(PredBB && "Block doesn't have a single predecessor!");
414
415 // Splice all the instructions from PredBB to DestBB.
416 PredBB->getTerminator()->eraseFromParent();
417 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Chris Lattner37914c82010-02-15 20:47:49 +0000418
419 // Zap anything that took the address of DestBB. Not doing this will give the
420 // address an invalid value.
421 if (DestBB->hasAddressTaken()) {
422 BlockAddress *BA = BlockAddress::get(DestBB);
423 Constant *Replacement =
424 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
425 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
426 BA->getType()));
427 BA->destroyConstant();
428 }
Chris Lattnerb29714a2008-11-27 07:43:12 +0000429
430 // Anything that branched to PredBB now branches to DestBB.
431 PredBB->replaceAllUsesWith(DestBB);
432
Andreas Neustifterad809812009-09-16 09:26:52 +0000433 if (P) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000434 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
435 if (DT) {
436 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
437 DT->changeImmediateDominator(DestBB, PredBBIDom);
438 DT->eraseNode(PredBB);
439 }
Andreas Neustifterad809812009-09-16 09:26:52 +0000440 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
441 if (PI) {
442 PI->replaceAllUses(PredBB, DestBB);
443 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
444 }
445 }
Chris Lattnerb29714a2008-11-27 07:43:12 +0000446 // Nuke BB.
447 PredBB->eraseFromParent();
448}
Devang Patel4afc90d2009-02-10 07:00:59 +0000449
Chris Lattnerdce94d92009-11-10 05:59:26 +0000450/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
451/// almost-empty BB ending in an unconditional branch to Succ, into succ.
452///
453/// Assumption: Succ is the single successor for BB.
454///
455static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
456 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
457
David Greenefae77062010-01-05 01:26:57 +0000458 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000459 << Succ->getName() << "\n");
460 // Shortcut, if there is only a single predecessor it must be BB and merging
461 // is always safe
462 if (Succ->getSinglePredecessor()) return true;
463
464 // Make a list of the predecessors of BB
465 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
466 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
467
468 // Use that list to make another list of common predecessors of BB and Succ
469 BlockSet CommonPreds;
470 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
Gabor Greiff1b28742010-07-12 10:49:54 +0000471 PI != PE; ++PI) {
472 BasicBlock *P = *PI;
473 if (BBPreds.count(P))
474 CommonPreds.insert(P);
475 }
Chris Lattnerdce94d92009-11-10 05:59:26 +0000476
477 // Shortcut, if there are no common predecessors, merging is always safe
478 if (CommonPreds.empty())
479 return true;
480
481 // Look at all the phi nodes in Succ, to see if they present a conflict when
482 // merging these blocks
483 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
484 PHINode *PN = cast<PHINode>(I);
485
486 // If the incoming value from BB is again a PHINode in
487 // BB which has the same incoming value for *PI as PN does, we can
488 // merge the phi nodes and then the blocks can still be merged
489 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
490 if (BBPN && BBPN->getParent() == BB) {
491 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
492 PI != PE; PI++) {
493 if (BBPN->getIncomingValueForBlock(*PI)
494 != PN->getIncomingValueForBlock(*PI)) {
David Greenefae77062010-01-05 01:26:57 +0000495 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000496 << Succ->getName() << " is conflicting with "
497 << BBPN->getName() << " with regard to common predecessor "
498 << (*PI)->getName() << "\n");
499 return false;
500 }
501 }
502 } else {
503 Value* Val = PN->getIncomingValueForBlock(BB);
504 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
505 PI != PE; PI++) {
506 // See if the incoming value for the common predecessor is equal to the
507 // one for BB, in which case this phi node will not prevent the merging
508 // of the block.
509 if (Val != PN->getIncomingValueForBlock(*PI)) {
David Greenefae77062010-01-05 01:26:57 +0000510 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000511 << Succ->getName() << " is conflicting with regard to common "
512 << "predecessor " << (*PI)->getName() << "\n");
513 return false;
514 }
515 }
516 }
517 }
518
519 return true;
520}
521
522/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
523/// unconditional branch, and contains no instructions other than PHI nodes,
524/// potential debug intrinsics and the branch. If possible, eliminate BB by
525/// rewriting all the predecessors to branch to the successor block and return
526/// true. If we can't transform, return false.
527bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
Dan Gohmane2c6d132010-08-14 00:29:42 +0000528 assert(BB != &BB->getParent()->getEntryBlock() &&
529 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
530
Chris Lattnerdce94d92009-11-10 05:59:26 +0000531 // We can't eliminate infinite loops.
532 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
533 if (BB == Succ) return false;
534
535 // Check to see if merging these blocks would cause conflicts for any of the
536 // phi nodes in BB or Succ. If not, we can safely merge.
537 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
538
539 // Check for cases where Succ has multiple predecessors and a PHI node in BB
540 // has uses which will not disappear when the PHI nodes are merged. It is
541 // possible to handle such cases, but difficult: it requires checking whether
542 // BB dominates Succ, which is non-trivial to calculate in the case where
543 // Succ has multiple predecessors. Also, it requires checking whether
544 // constructing the necessary self-referential PHI node doesn't intoduce any
545 // conflicts; this isn't too difficult, but the previous code for doing this
546 // was incorrect.
547 //
548 // Note that if this check finds a live use, BB dominates Succ, so BB is
549 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
550 // folding the branch isn't profitable in that case anyway.
551 if (!Succ->getSinglePredecessor()) {
552 BasicBlock::iterator BBI = BB->begin();
553 while (isa<PHINode>(*BBI)) {
554 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
555 UI != E; ++UI) {
556 if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
557 if (PN->getIncomingBlock(UI) != BB)
558 return false;
559 } else {
560 return false;
561 }
562 }
563 ++BBI;
564 }
565 }
566
David Greenefae77062010-01-05 01:26:57 +0000567 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Chris Lattnerdce94d92009-11-10 05:59:26 +0000568
569 if (isa<PHINode>(Succ->begin())) {
570 // If there is more than one pred of succ, and there are PHI nodes in
571 // the successor, then we need to add incoming edges for the PHI nodes
572 //
573 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
574
575 // Loop over all of the PHI nodes in the successor of BB.
576 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
577 PHINode *PN = cast<PHINode>(I);
578 Value *OldVal = PN->removeIncomingValue(BB, false);
579 assert(OldVal && "No entry in PHI for Pred BB!");
580
581 // If this incoming value is one of the PHI nodes in BB, the new entries
582 // in the PHI node are the entries from the old PHI.
583 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
584 PHINode *OldValPN = cast<PHINode>(OldVal);
585 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
586 // Note that, since we are merging phi nodes and BB and Succ might
587 // have common predecessors, we could end up with a phi node with
588 // identical incoming branches. This will be cleaned up later (and
589 // will trigger asserts if we try to clean it up now, without also
590 // simplifying the corresponding conditional branch).
591 PN->addIncoming(OldValPN->getIncomingValue(i),
592 OldValPN->getIncomingBlock(i));
593 } else {
594 // Add an incoming value for each of the new incoming values.
595 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
596 PN->addIncoming(OldVal, BBPreds[i]);
597 }
598 }
599 }
600
601 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
602 if (Succ->getSinglePredecessor()) {
603 // BB is the only predecessor of Succ, so Succ will end up with exactly
604 // the same predecessors BB had.
605 Succ->getInstList().splice(Succ->begin(),
606 BB->getInstList(), BB->begin());
607 } else {
608 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
609 assert(PN->use_empty() && "There shouldn't be any uses here!");
610 PN->eraseFromParent();
611 }
612 }
613
614 // Everything that jumped to BB now goes to Succ.
615 BB->replaceAllUsesWith(Succ);
616 if (!Succ->hasName()) Succ->takeName(BB);
617 BB->eraseFromParent(); // Delete the old basic block.
618 return true;
619}
620
Jim Grosbach43a82412009-12-02 17:06:45 +0000621/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
622/// nodes in this block. This doesn't try to be clever about PHI nodes
623/// which differ only in the order of the incoming values, but instcombine
624/// orders them so it usually won't matter.
625///
626bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
627 bool Changed = false;
628
629 // This implementation doesn't currently consider undef operands
630 // specially. Theroetically, two phis which are identical except for
631 // one having an undef where the other doesn't could be collapsed.
632
633 // Map from PHI hash values to PHI nodes. If multiple PHIs have
634 // the same hash value, the element is the first PHI in the
635 // linked list in CollisionMap.
636 DenseMap<uintptr_t, PHINode *> HashMap;
637
638 // Maintain linked lists of PHI nodes with common hash values.
639 DenseMap<PHINode *, PHINode *> CollisionMap;
640
641 // Examine each PHI.
642 for (BasicBlock::iterator I = BB->begin();
643 PHINode *PN = dyn_cast<PHINode>(I++); ) {
644 // Compute a hash value on the operands. Instcombine will likely have sorted
645 // them, which helps expose duplicates, but we have to check all the
646 // operands to be safe in case instcombine hasn't run.
647 uintptr_t Hash = 0;
648 for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
649 // This hash algorithm is quite weak as hash functions go, but it seems
650 // to do a good enough job for this particular purpose, and is very quick.
651 Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
652 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
653 }
Jakob Stoklund Olesen2bc2a082011-03-04 02:48:56 +0000654 // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
655 Hash >>= 1;
Jim Grosbach43a82412009-12-02 17:06:45 +0000656 // If we've never seen this hash value before, it's a unique PHI.
657 std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
658 HashMap.insert(std::make_pair(Hash, PN));
659 if (Pair.second) continue;
660 // Otherwise it's either a duplicate or a hash collision.
661 for (PHINode *OtherPN = Pair.first->second; ; ) {
662 if (OtherPN->isIdenticalTo(PN)) {
663 // A duplicate. Replace this PHI with its duplicate.
664 PN->replaceAllUsesWith(OtherPN);
665 PN->eraseFromParent();
666 Changed = true;
667 break;
668 }
669 // A non-duplicate hash collision.
670 DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
671 if (I == CollisionMap.end()) {
672 // Set this PHI to be the head of the linked list of colliding PHIs.
673 PHINode *Old = Pair.first->second;
674 Pair.first->second = PN;
675 CollisionMap[PN] = Old;
676 break;
677 }
678 // Procede to the next PHI in the list.
679 OtherPN = I->second;
680 }
681 }
682
683 return Changed;
684}
Chris Lattner687140c2010-12-25 20:37:57 +0000685
686/// enforceKnownAlignment - If the specified pointer points to an object that
687/// we control, modify the object's alignment to PrefAlign. This isn't
688/// often possible though. If alignment is important, a more reliable approach
689/// is to simply align all global variables and allocation instructions to
690/// their preferred alignment from the beginning.
691///
Benjamin Kramer19282362010-12-30 22:34:44 +0000692static unsigned enforceKnownAlignment(Value *V, unsigned Align,
693 unsigned PrefAlign) {
Chris Lattner687140c2010-12-25 20:37:57 +0000694
695 User *U = dyn_cast<User>(V);
696 if (!U) return Align;
697
698 switch (Operator::getOpcode(U)) {
699 default: break;
700 case Instruction::BitCast:
701 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
702 case Instruction::GetElementPtr: {
703 // If all indexes are zero, it is just the alignment of the base pointer.
704 bool AllZeroOperands = true;
705 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
706 if (!isa<Constant>(*i) ||
707 !cast<Constant>(*i)->isNullValue()) {
708 AllZeroOperands = false;
709 break;
710 }
711
712 if (AllZeroOperands) {
713 // Treat this like a bitcast.
714 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
715 }
716 return Align;
717 }
718 case Instruction::Alloca: {
719 AllocaInst *AI = cast<AllocaInst>(V);
720 // If there is a requested alignment and if this is an alloca, round up.
721 if (AI->getAlignment() >= PrefAlign)
722 return AI->getAlignment();
723 AI->setAlignment(PrefAlign);
724 return PrefAlign;
725 }
726 }
727
728 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
729 // If there is a large requested alignment and we can, bump up the alignment
730 // of the global.
731 if (GV->isDeclaration()) return Align;
732
733 if (GV->getAlignment() >= PrefAlign)
734 return GV->getAlignment();
735 // We can only increase the alignment of the global if it has no alignment
736 // specified or if it is not assigned a section. If it is assigned a
737 // section, the global could be densely packed with other objects in the
738 // section, increasing the alignment could cause padding issues.
739 if (!GV->hasSection() || GV->getAlignment() == 0)
740 GV->setAlignment(PrefAlign);
741 return GV->getAlignment();
742 }
743
744 return Align;
745}
746
747/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
748/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
749/// and it is more than the alignment of the ultimate object, see if we can
750/// increase the alignment of the ultimate object, making this check succeed.
751unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
752 const TargetData *TD) {
753 assert(V->getType()->isPointerTy() &&
754 "getOrEnforceKnownAlignment expects a pointer!");
755 unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
756 APInt Mask = APInt::getAllOnesValue(BitWidth);
757 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattnerae47be12010-12-25 20:52:04 +0000758 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
Chris Lattner687140c2010-12-25 20:37:57 +0000759 unsigned TrailZ = KnownZero.countTrailingOnes();
760
761 // Avoid trouble with rediculously large TrailZ values, such as
762 // those computed from a null pointer.
763 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
764
765 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
766
767 // LLVM doesn't support alignments larger than this currently.
768 Align = std::min(Align, +Value::MaximumAlignment);
769
770 if (PrefAlign > Align)
771 Align = enforceKnownAlignment(V, Align, PrefAlign);
772
773 // We don't need to make any adjustment.
774 return Align;
775}
776
Devang Patel5ee20682011-03-17 21:58:19 +0000777///===---------------------------------------------------------------------===//
778/// Dbg Intrinsic utilities
779///
780
781/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
782/// that has an associated llvm.dbg.decl intrinsic.
783bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
784 StoreInst *SI, DIBuilder &Builder) {
785 DIVariable DIVar(DDI->getVariable());
786 if (!DIVar.Verify())
787 return false;
788
789 Instruction *DbgVal =
790 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0,
791 DIVar, SI);
792
793 // Propagate any debug metadata from the store onto the dbg.value.
794 DebugLoc SIDL = SI->getDebugLoc();
795 if (!SIDL.isUnknown())
796 DbgVal->setDebugLoc(SIDL);
797 // Otherwise propagate debug metadata from dbg.declare.
798 else
799 DbgVal->setDebugLoc(DDI->getDebugLoc());
800 return true;
801}
802
Devang Patel36fae672011-03-18 23:45:43 +0000803/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
804/// that has an associated llvm.dbg.decl intrinsic.
805bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
806 LoadInst *LI, DIBuilder &Builder) {
807 DIVariable DIVar(DDI->getVariable());
808 if (!DIVar.Verify())
809 return false;
810
811 Instruction *DbgVal =
812 Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
813 DIVar, LI);
814
815 // Propagate any debug metadata from the store onto the dbg.value.
816 DebugLoc LIDL = LI->getDebugLoc();
817 if (!LIDL.isUnknown())
818 DbgVal->setDebugLoc(LIDL);
819 // Otherwise propagate debug metadata from dbg.declare.
820 else
821 DbgVal->setDebugLoc(DDI->getDebugLoc());
822 return true;
823}
824
Devang Patel813c9a02011-03-17 22:18:16 +0000825/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
826/// of llvm.dbg.value intrinsics.
827bool llvm::LowerDbgDeclare(Function &F) {
828 DIBuilder DIB(*F.getParent());
829 SmallVector<DbgDeclareInst *, 4> Dbgs;
830 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
831 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
832 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
833 Dbgs.push_back(DDI);
834 }
835 if (Dbgs.empty())
836 return false;
837
838 for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
839 E = Dbgs.end(); I != E; ++I) {
840 DbgDeclareInst *DDI = *I;
841 if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
842 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
843 UI != E; ++UI)
844 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
845 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
Devang Patel36fae672011-03-18 23:45:43 +0000846 else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
847 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Devang Patel813c9a02011-03-17 22:18:16 +0000848 }
849 DDI->eraseFromParent();
850 }
851 return true;
852}