blob: 07e291971a85aec6dd8c35532b9790ac31fd9ff0 [file] [log] [blame]
Chris Lattner210e45a2009-12-04 02:10:16 +00001//===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the PHITransAddr class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/PHITransAddr.h"
15#include "llvm/Analysis/Dominators.h"
Chris Lattner9a864122009-12-07 18:36:53 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7dedbf42009-12-09 00:01:00 +000017#include "llvm/Support/raw_ostream.h"
Chris Lattner210e45a2009-12-04 02:10:16 +000018using namespace llvm;
19
Chris Lattner6fcca1c2009-12-07 19:04:49 +000020static bool CanPHITrans(Instruction *Inst) {
21 if (isa<PHINode>(Inst) ||
22 isa<BitCastInst>(Inst) ||
23 isa<GetElementPtrInst>(Inst))
24 return true;
25
Chris Lattner34f84902009-12-08 06:06:26 +000026 if (Inst->getOpcode() == Instruction::Add &&
Chris Lattner6fcca1c2009-12-07 19:04:49 +000027 isa<ConstantInt>(Inst->getOperand(1)))
28 return true;
29
30 // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
31 // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
32 // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
33 return false;
34}
35
Chris Lattner7dedbf42009-12-09 00:01:00 +000036void PHITransAddr::dump() const {
37 if (Addr == 0) {
38 errs() << "PHITransAddr: null\n";
39 return;
40 }
41 errs() << "PHITransAddr: " << *Addr << "\n";
42 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
43 errs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
44}
45
46
47static bool VerifySubExpr(Value *Expr,
48 SmallVectorImpl<Instruction*> &InstInputs) {
49 // If this is a non-instruction value, there is nothing to do.
50 Instruction *I = dyn_cast<Instruction>(Expr);
51 if (I == 0) return true;
52
53 // If it's an instruction, it is either in Tmp or its operands recursively
54 // are.
55 SmallVectorImpl<Instruction*>::iterator Entry =
56 std::find(InstInputs.begin(), InstInputs.end(), I);
57 if (Entry != InstInputs.end()) {
58 InstInputs.erase(Entry);
59 return true;
60 }
61
62 // If it isn't in the InstInputs list it is a subexpr incorporated into the
63 // address. Sanity check that it is phi translatable.
64 if (!CanPHITrans(I)) {
65 errs() << "Non phi translatable instruction found in PHITransAddr, either "
66 "something is missing from InstInputs or CanPHITrans is wrong:\n";
67 errs() << *I << '\n';
68 return false;
69 }
70
71 // Validate the operands of the instruction.
72 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
73 if (!VerifySubExpr(I->getOperand(i), InstInputs))
74 return false;
75
76 return true;
77}
78
79/// Verify - Check internal consistency of this data structure. If the
80/// structure is valid, it returns true. If invalid, it prints errors and
81/// returns false.
82bool PHITransAddr::Verify() const {
83 if (Addr == 0) return true;
84
85 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
86
87 if (!VerifySubExpr(Addr, Tmp))
88 return false;
89
90 if (!Tmp.empty()) {
91 errs() << "PHITransAddr inconsistent, contains extra instructions:\n";
92 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
93 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
94 return false;
95 }
96
97 // a-ok.
98 return true;
99}
100
101
Chris Lattner9a864122009-12-07 18:36:53 +0000102/// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
103/// if we have some hope of doing it. This should be used as a filter to
104/// avoid calling PHITranslateValue in hopeless situations.
105bool PHITransAddr::IsPotentiallyPHITranslatable() const {
106 // If the input value is not an instruction, or if it is not defined in CurBB,
107 // then we don't need to phi translate it.
108 Instruction *Inst = dyn_cast<Instruction>(Addr);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000109 return Inst == 0 || CanPHITrans(Inst);
Chris Lattner210e45a2009-12-04 02:10:16 +0000110}
111
Chris Lattner9a864122009-12-07 18:36:53 +0000112
Chris Lattner6200e532009-12-09 00:56:14 +0000113static void RemoveInstInputs(Value *V,
Chris Lattner43678f42009-12-08 23:42:51 +0000114 SmallVectorImpl<Instruction*> &InstInputs) {
Chris Lattner6200e532009-12-09 00:56:14 +0000115 Instruction *I = dyn_cast<Instruction>(V);
116 if (I == 0) return;
117
Chris Lattner43678f42009-12-08 23:42:51 +0000118 // If the instruction is in the InstInputs list, remove it.
119 SmallVectorImpl<Instruction*>::iterator Entry =
120 std::find(InstInputs.begin(), InstInputs.end(), I);
121 if (Entry != InstInputs.end()) {
122 InstInputs.erase(Entry);
123 return;
124 }
125
Chris Lattner6200e532009-12-09 00:56:14 +0000126 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
Chris Lattner43678f42009-12-08 23:42:51 +0000127
Chris Lattner6200e532009-12-09 00:56:14 +0000128 // Otherwise, it must have instruction inputs itself. Zap them recursively.
129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
130 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
131 RemoveInstInputs(Op, InstInputs);
132 }
Chris Lattner43678f42009-12-08 23:42:51 +0000133}
134
Chris Lattner9a864122009-12-07 18:36:53 +0000135Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
136 BasicBlock *PredBB) {
137 // If this is a non-instruction value, it can't require PHI translation.
138 Instruction *Inst = dyn_cast<Instruction>(V);
139 if (Inst == 0) return V;
140
Chris Lattneraf503152009-12-09 00:10:55 +0000141 // Determine whether 'Inst' is an input to our PHI translatable expression.
142 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
143
144 // Handle inputs instructions if needed.
145 if (isInput) {
146 if (Inst->getParent() != CurBB) {
147 // If it is an input defined in a different block, then it remains an
148 // input.
149 return Inst;
150 }
Chris Lattnere09e98c2009-12-09 00:18:13 +0000151
152 // If 'Inst' is defined in this block and is an input that needs to be phi
153 // translated, we need to incorporate the value into the expression or fail.
154
Chris Lattner6200e532009-12-09 00:56:14 +0000155 // In either case, the instruction itself isn't an input any longer.
156 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
157
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000158 // If this is a PHI, go ahead and translate it.
159 if (PHINode *PN = dyn_cast<PHINode>(Inst))
Chris Lattner6200e532009-12-09 00:56:14 +0000160 return AddAsInput(PN->getIncomingValueForBlock(PredBB));
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000161
162 // If this is a non-phi value, and it is analyzable, we can incorporate it
163 // into the expression by making all instruction operands be inputs.
164 if (!CanPHITrans(Inst))
165 return 0;
Chris Lattnere09e98c2009-12-09 00:18:13 +0000166
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000167 // All instruction operands are now inputs (and of course, they may also be
168 // defined in this block, so they may need to be phi translated themselves.
169 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
170 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
171 InstInputs.push_back(Op);
Chris Lattner9a864122009-12-07 18:36:53 +0000172 }
173
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000174 // Ok, it must be an intermediate result (either because it started that way
175 // or because we just incorporated it into the expression). See if its
176 // operands need to be phi translated, and if so, reconstruct it.
Chris Lattner9a864122009-12-07 18:36:53 +0000177
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000178 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
179 Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB);
180 if (PHIIn == 0) return 0;
181 if (PHIIn == BC->getOperand(0))
182 return BC;
183
184 // Find an available version of this cast.
185
186 // Constants are trivial to find.
187 if (Constant *C = dyn_cast<Constant>(PHIIn))
Chris Lattner6200e532009-12-09 00:56:14 +0000188 return AddAsInput(ConstantExpr::getBitCast(C, BC->getType()));
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000189
190 // Otherwise we have to see if a bitcasted version of the incoming pointer
191 // is available. If so, we can use it, otherwise we have to fail.
192 for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
193 UI != E; ++UI) {
194 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI))
195 if (BCI->getType() == BC->getType())
196 return BCI;
197 }
198 return 0;
199 }
Chris Lattner9a864122009-12-07 18:36:53 +0000200
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000201 // Handle getelementptr with at least one PHI translatable operand.
202 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
203 SmallVector<Value*, 8> GEPOps;
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000204 bool AnyChanged = false;
205 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
206 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB);
207 if (GEPOp == 0) return 0;
208
Chris Lattner60454172009-12-07 19:52:57 +0000209 AnyChanged |= GEPOp != GEP->getOperand(i);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000210 GEPOps.push_back(GEPOp);
211 }
212
213 if (!AnyChanged)
214 return GEP;
215
216 // Simplify the GEP to handle 'gep x, 0' -> x etc.
Chris Lattner6200e532009-12-09 00:56:14 +0000217 if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD)) {
218 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
219 RemoveInstInputs(GEPOps[i], InstInputs);
220
221 return AddAsInput(V);
222 }
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000223
224 // Scan to see if we have this GEP available.
225 Value *APHIOp = GEPOps[0];
226 for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
227 UI != E; ++UI) {
228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
229 if (GEPI->getType() == GEP->getType() &&
230 GEPI->getNumOperands() == GEPOps.size() &&
231 GEPI->getParent()->getParent() == CurBB->getParent()) {
232 bool Mismatch = false;
233 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
234 if (GEPI->getOperand(i) != GEPOps[i]) {
235 Mismatch = true;
236 break;
237 }
238 if (!Mismatch)
239 return GEPI;
240 }
241 }
242 return 0;
243 }
244
245 // Handle add with a constant RHS.
246 if (Inst->getOpcode() == Instruction::Add &&
247 isa<ConstantInt>(Inst->getOperand(1))) {
248 // PHI translate the LHS.
249 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
250 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
251 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
252
253 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB);
254 if (LHS == 0) return 0;
255
256 // If the PHI translated LHS is an add of a constant, fold the immediates.
257 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
258 if (BOp->getOpcode() == Instruction::Add)
259 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
260 LHS = BOp->getOperand(0);
261 RHS = ConstantExpr::getAdd(RHS, CI);
262 isNSW = isNUW = false;
Chris Lattner6200e532009-12-09 00:56:14 +0000263
264 // If the old 'LHS' was an input, add the new 'LHS' as an input.
265 if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
266 RemoveInstInputs(BOp, InstInputs);
267 AddAsInput(LHS);
268 }
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000269 }
270
271 // See if the add simplifies away.
Chris Lattner6200e532009-12-09 00:56:14 +0000272 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD)) {
273 // If we simplified the operands, the LHS is no longer an input, but Res
274 // is.
275 RemoveInstInputs(LHS, InstInputs);
276 return AddAsInput(Res);
277 }
Chris Lattner4d3a16f2009-12-09 17:27:45 +0000278
279 // If we didn't modify the add, just return it.
280 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
281 return Inst;
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000282
283 // Otherwise, see if we have this add available somewhere.
284 for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
285 UI != E; ++UI) {
286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
Chris Lattnereddc65a2009-12-09 17:18:49 +0000287 if (BO->getOpcode() == Instruction::Add &&
288 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000289 BO->getParent()->getParent() == CurBB->getParent())
290 return BO;
291 }
292
293 return 0;
294 }
295
296 // Otherwise, we failed.
297 return 0;
Chris Lattner210e45a2009-12-04 02:10:16 +0000298}
299
Chris Lattner9a864122009-12-07 18:36:53 +0000300
301/// PHITranslateValue - PHI translate the current address up the CFG from
302/// CurBB to Pred, updating our state the reflect any needed changes. This
Chris Lattnere05a1882009-12-07 19:45:30 +0000303/// returns true on failure and sets Addr to null.
Chris Lattner9a864122009-12-07 18:36:53 +0000304bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) {
Chris Lattner7dedbf42009-12-09 00:01:00 +0000305 assert(Verify() && "Invalid PHITransAddr!");
Chris Lattner9a864122009-12-07 18:36:53 +0000306 Addr = PHITranslateSubExpr(Addr, CurBB, PredBB);
Chris Lattner7dedbf42009-12-09 00:01:00 +0000307 assert(Verify() && "Invalid PHITransAddr!");
Chris Lattner9a864122009-12-07 18:36:53 +0000308 return Addr == 0;
309}
310
311/// GetAvailablePHITranslatedSubExpr - Return the value computed by
312/// PHITranslateSubExpr if it dominates PredBB, otherwise return null.
Chris Lattner210e45a2009-12-04 02:10:16 +0000313Value *PHITransAddr::
Chris Lattner9a864122009-12-07 18:36:53 +0000314GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB,
Chris Lattner34f84902009-12-08 06:06:26 +0000315 const DominatorTree &DT) const {
316 PHITransAddr Tmp(V, TD);
317 Tmp.PHITranslateValue(CurBB, PredBB);
318
Chris Lattner210e45a2009-12-04 02:10:16 +0000319 // See if PHI translation succeeds.
Chris Lattner34f84902009-12-08 06:06:26 +0000320 V = Tmp.getAddr();
Chris Lattner210e45a2009-12-04 02:10:16 +0000321
322 // Make sure the value is live in the predecessor.
323 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
324 if (!DT.dominates(Inst->getParent(), PredBB))
325 return 0;
326 return V;
327}
328
Chris Lattner9a864122009-12-07 18:36:53 +0000329
330/// PHITranslateWithInsertion - PHI translate this value into the specified
331/// predecessor block, inserting a computation of the value if it is
332/// unavailable.
333///
334/// All newly created instructions are added to the NewInsts list. This
335/// returns null on failure.
336///
337Value *PHITransAddr::
338PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
339 const DominatorTree &DT,
340 SmallVectorImpl<Instruction*> &NewInsts) {
341 unsigned NISize = NewInsts.size();
342
343 // Attempt to PHI translate with insertion.
344 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
345
346 // If successful, return the new value.
347 if (Addr) return Addr;
348
349 // If not, destroy any intermediate instructions inserted.
350 while (NewInsts.size() != NISize)
351 NewInsts.pop_back_val()->eraseFromParent();
352 return 0;
353}
354
355
Chris Lattner210e45a2009-12-04 02:10:16 +0000356/// InsertPHITranslatedPointer - Insert a computation of the PHI translated
357/// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
358/// block. All newly created instructions are added to the NewInsts list.
359/// This returns null on failure.
360///
361Value *PHITransAddr::
Chris Lattner9a864122009-12-07 18:36:53 +0000362InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
363 BasicBlock *PredBB, const DominatorTree &DT,
364 SmallVectorImpl<Instruction*> &NewInsts) {
Chris Lattner210e45a2009-12-04 02:10:16 +0000365 // See if we have a version of this value already available and dominating
Chris Lattner9a864122009-12-07 18:36:53 +0000366 // PredBB. If so, there is no need to insert a new instance of it.
367 if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT))
Chris Lattner210e45a2009-12-04 02:10:16 +0000368 return Res;
369
Chris Lattner9a864122009-12-07 18:36:53 +0000370 // If we don't have an available version of this value, it must be an
371 // instruction.
372 Instruction *Inst = cast<Instruction>(InVal);
373
374 // Handle bitcast of PHI translatable value.
375 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
376 Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0),
377 CurBB, PredBB, DT, NewInsts);
378 if (OpVal == 0) return 0;
379
380 // Otherwise insert a bitcast at the end of PredBB.
381 BitCastInst *New = new BitCastInst(OpVal, InVal->getType(),
382 InVal->getName()+".phi.trans.insert",
383 PredBB->getTerminator());
384 NewInsts.push_back(New);
385 return New;
386 }
387
388 // Handle getelementptr with at least one PHI operand.
389 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
390 SmallVector<Value*, 8> GEPOps;
391 BasicBlock *CurBB = GEP->getParent();
392 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
393 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
394 CurBB, PredBB, DT, NewInsts);
395 if (OpVal == 0) return 0;
396 GEPOps.push_back(OpVal);
397 }
398
399 GetElementPtrInst *Result =
400 GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
401 InVal->getName()+".phi.trans.insert",
402 PredBB->getTerminator());
403 Result->setIsInBounds(GEP->isInBounds());
404 NewInsts.push_back(Result);
405 return Result;
406 }
407
408#if 0
409 // FIXME: This code works, but it is unclear that we actually want to insert
410 // a big chain of computation in order to make a value available in a block.
411 // This needs to be evaluated carefully to consider its cost trade offs.
412
413 // Handle add with a constant RHS.
414 if (Inst->getOpcode() == Instruction::Add &&
415 isa<ConstantInt>(Inst->getOperand(1))) {
416 // PHI translate the LHS.
417 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
418 CurBB, PredBB, DT, NewInsts);
419 if (OpVal == 0) return 0;
420
421 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
422 InVal->getName()+".phi.trans.insert",
423 PredBB->getTerminator());
424 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
425 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
426 NewInsts.push_back(Res);
427 return Res;
428 }
429#endif
430
Chris Lattner210e45a2009-12-04 02:10:16 +0000431 return 0;
432}