1 //===- 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/InstructionSimplify.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
CanPHITrans(Instruction * Inst)25 static bool CanPHITrans(Instruction *Inst) {
26 if (isa<PHINode>(Inst) ||
27 isa<GetElementPtrInst>(Inst))
28 return true;
29
30 if (isa<CastInst>(Inst) &&
31 isSafeToSpeculativelyExecute(Inst))
32 return true;
33
34 if (Inst->getOpcode() == Instruction::Add &&
35 isa<ConstantInt>(Inst->getOperand(1)))
36 return true;
37
38 // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
39 // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
40 // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
41 return false;
42 }
43
44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const45 LLVM_DUMP_METHOD void PHITransAddr::dump() const {
46 if (!Addr) {
47 dbgs() << "PHITransAddr: null\n";
48 return;
49 }
50 dbgs() << "PHITransAddr: " << *Addr << "\n";
51 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
52 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
53 }
54 #endif
55
56
VerifySubExpr(Value * Expr,SmallVectorImpl<Instruction * > & InstInputs)57 static bool VerifySubExpr(Value *Expr,
58 SmallVectorImpl<Instruction*> &InstInputs) {
59 // If this is a non-instruction value, there is nothing to do.
60 Instruction *I = dyn_cast<Instruction>(Expr);
61 if (!I) return true;
62
63 // If it's an instruction, it is either in Tmp or its operands recursively
64 // are.
65 SmallVectorImpl<Instruction*>::iterator Entry =
66 std::find(InstInputs.begin(), InstInputs.end(), I);
67 if (Entry != InstInputs.end()) {
68 InstInputs.erase(Entry);
69 return true;
70 }
71
72 // If it isn't in the InstInputs list it is a subexpr incorporated into the
73 // address. Sanity check that it is phi translatable.
74 if (!CanPHITrans(I)) {
75 errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
76 errs() << *I << '\n';
77 llvm_unreachable("Either something is missing from InstInputs or "
78 "CanPHITrans is wrong.");
79 }
80
81 // Validate the operands of the instruction.
82 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
83 if (!VerifySubExpr(I->getOperand(i), InstInputs))
84 return false;
85
86 return true;
87 }
88
89 /// Verify - Check internal consistency of this data structure. If the
90 /// structure is valid, it returns true. If invalid, it prints errors and
91 /// returns false.
Verify() const92 bool PHITransAddr::Verify() const {
93 if (!Addr) return true;
94
95 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
96
97 if (!VerifySubExpr(Addr, Tmp))
98 return false;
99
100 if (!Tmp.empty()) {
101 errs() << "PHITransAddr contains extra instructions:\n";
102 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
103 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
104 llvm_unreachable("This is unexpected.");
105 }
106
107 // a-ok.
108 return true;
109 }
110
111
112 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
113 /// if we have some hope of doing it. This should be used as a filter to
114 /// avoid calling PHITranslateValue in hopeless situations.
IsPotentiallyPHITranslatable() const115 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
116 // If the input value is not an instruction, or if it is not defined in CurBB,
117 // then we don't need to phi translate it.
118 Instruction *Inst = dyn_cast<Instruction>(Addr);
119 return !Inst || CanPHITrans(Inst);
120 }
121
122
RemoveInstInputs(Value * V,SmallVectorImpl<Instruction * > & InstInputs)123 static void RemoveInstInputs(Value *V,
124 SmallVectorImpl<Instruction*> &InstInputs) {
125 Instruction *I = dyn_cast<Instruction>(V);
126 if (!I) return;
127
128 // If the instruction is in the InstInputs list, remove it.
129 SmallVectorImpl<Instruction*>::iterator Entry =
130 std::find(InstInputs.begin(), InstInputs.end(), I);
131 if (Entry != InstInputs.end()) {
132 InstInputs.erase(Entry);
133 return;
134 }
135
136 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
137
138 // Otherwise, it must have instruction inputs itself. Zap them recursively.
139 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
140 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
141 RemoveInstInputs(Op, InstInputs);
142 }
143 }
144
PHITranslateSubExpr(Value * V,BasicBlock * CurBB,BasicBlock * PredBB,const DominatorTree * DT)145 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
146 BasicBlock *PredBB,
147 const DominatorTree *DT) {
148 // If this is a non-instruction value, it can't require PHI translation.
149 Instruction *Inst = dyn_cast<Instruction>(V);
150 if (!Inst) return V;
151
152 // Determine whether 'Inst' is an input to our PHI translatable expression.
153 bool isInput =
154 std::find(InstInputs.begin(), InstInputs.end(), Inst) != InstInputs.end();
155
156 // Handle inputs instructions if needed.
157 if (isInput) {
158 if (Inst->getParent() != CurBB) {
159 // If it is an input defined in a different block, then it remains an
160 // input.
161 return Inst;
162 }
163
164 // If 'Inst' is defined in this block and is an input that needs to be phi
165 // translated, we need to incorporate the value into the expression or fail.
166
167 // In either case, the instruction itself isn't an input any longer.
168 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
169
170 // If this is a PHI, go ahead and translate it.
171 if (PHINode *PN = dyn_cast<PHINode>(Inst))
172 return AddAsInput(PN->getIncomingValueForBlock(PredBB));
173
174 // If this is a non-phi value, and it is analyzable, we can incorporate it
175 // into the expression by making all instruction operands be inputs.
176 if (!CanPHITrans(Inst))
177 return nullptr;
178
179 // All instruction operands are now inputs (and of course, they may also be
180 // defined in this block, so they may need to be phi translated themselves.
181 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
182 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
183 InstInputs.push_back(Op);
184 }
185
186 // Ok, it must be an intermediate result (either because it started that way
187 // or because we just incorporated it into the expression). See if its
188 // operands need to be phi translated, and if so, reconstruct it.
189
190 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
191 if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
192 Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
193 if (!PHIIn) return nullptr;
194 if (PHIIn == Cast->getOperand(0))
195 return Cast;
196
197 // Find an available version of this cast.
198
199 // Constants are trivial to find.
200 if (Constant *C = dyn_cast<Constant>(PHIIn))
201 return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
202 C, Cast->getType()));
203
204 // Otherwise we have to see if a casted version of the incoming pointer
205 // is available. If so, we can use it, otherwise we have to fail.
206 for (User *U : PHIIn->users()) {
207 if (CastInst *CastI = dyn_cast<CastInst>(U))
208 if (CastI->getOpcode() == Cast->getOpcode() &&
209 CastI->getType() == Cast->getType() &&
210 (!DT || DT->dominates(CastI->getParent(), PredBB)))
211 return CastI;
212 }
213 return nullptr;
214 }
215
216 // Handle getelementptr with at least one PHI translatable operand.
217 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
218 SmallVector<Value*, 8> GEPOps;
219 bool AnyChanged = false;
220 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
221 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
222 if (!GEPOp) return nullptr;
223
224 AnyChanged |= GEPOp != GEP->getOperand(i);
225 GEPOps.push_back(GEPOp);
226 }
227
228 if (!AnyChanged)
229 return GEP;
230
231 // Simplify the GEP to handle 'gep x, 0' -> x etc.
232 if (Value *V = SimplifyGEPInst(GEP->getSourceElementType(),
233 GEPOps, DL, TLI, DT, AC)) {
234 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
235 RemoveInstInputs(GEPOps[i], InstInputs);
236
237 return AddAsInput(V);
238 }
239
240 // Scan to see if we have this GEP available.
241 Value *APHIOp = GEPOps[0];
242 for (User *U : APHIOp->users()) {
243 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
244 if (GEPI->getType() == GEP->getType() &&
245 GEPI->getNumOperands() == GEPOps.size() &&
246 GEPI->getParent()->getParent() == CurBB->getParent() &&
247 (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
248 if (std::equal(GEPOps.begin(), GEPOps.end(), GEPI->op_begin()))
249 return GEPI;
250 }
251 }
252 return nullptr;
253 }
254
255 // Handle add with a constant RHS.
256 if (Inst->getOpcode() == Instruction::Add &&
257 isa<ConstantInt>(Inst->getOperand(1))) {
258 // PHI translate the LHS.
259 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
260 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
261 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
262
263 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
264 if (!LHS) return nullptr;
265
266 // If the PHI translated LHS is an add of a constant, fold the immediates.
267 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
268 if (BOp->getOpcode() == Instruction::Add)
269 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
270 LHS = BOp->getOperand(0);
271 RHS = ConstantExpr::getAdd(RHS, CI);
272 isNSW = isNUW = false;
273
274 // If the old 'LHS' was an input, add the new 'LHS' as an input.
275 if (std::find(InstInputs.begin(), InstInputs.end(), BOp) !=
276 InstInputs.end()) {
277 RemoveInstInputs(BOp, InstInputs);
278 AddAsInput(LHS);
279 }
280 }
281
282 // See if the add simplifies away.
283 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT, AC)) {
284 // If we simplified the operands, the LHS is no longer an input, but Res
285 // is.
286 RemoveInstInputs(LHS, InstInputs);
287 return AddAsInput(Res);
288 }
289
290 // If we didn't modify the add, just return it.
291 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
292 return Inst;
293
294 // Otherwise, see if we have this add available somewhere.
295 for (User *U : LHS->users()) {
296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
297 if (BO->getOpcode() == Instruction::Add &&
298 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
299 BO->getParent()->getParent() == CurBB->getParent() &&
300 (!DT || DT->dominates(BO->getParent(), PredBB)))
301 return BO;
302 }
303
304 return nullptr;
305 }
306
307 // Otherwise, we failed.
308 return nullptr;
309 }
310
311
312 /// PHITranslateValue - PHI translate the current address up the CFG from
313 /// CurBB to Pred, updating our state to reflect any needed changes. If
314 /// 'MustDominate' is true, the translated value must dominate
315 /// PredBB. This returns true on failure and sets Addr to null.
PHITranslateValue(BasicBlock * CurBB,BasicBlock * PredBB,const DominatorTree * DT,bool MustDominate)316 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
317 const DominatorTree *DT,
318 bool MustDominate) {
319 assert(DT || !MustDominate);
320 assert(Verify() && "Invalid PHITransAddr!");
321 if (DT && DT->isReachableFromEntry(PredBB))
322 Addr =
323 PHITranslateSubExpr(Addr, CurBB, PredBB, MustDominate ? DT : nullptr);
324 else
325 Addr = nullptr;
326 assert(Verify() && "Invalid PHITransAddr!");
327
328 if (MustDominate)
329 // Make sure the value is live in the predecessor.
330 if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
331 if (!DT->dominates(Inst->getParent(), PredBB))
332 Addr = nullptr;
333
334 return Addr == nullptr;
335 }
336
337 /// PHITranslateWithInsertion - PHI translate this value into the specified
338 /// predecessor block, inserting a computation of the value if it is
339 /// unavailable.
340 ///
341 /// All newly created instructions are added to the NewInsts list. This
342 /// returns null on failure.
343 ///
344 Value *PHITransAddr::
PHITranslateWithInsertion(BasicBlock * CurBB,BasicBlock * PredBB,const DominatorTree & DT,SmallVectorImpl<Instruction * > & NewInsts)345 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
346 const DominatorTree &DT,
347 SmallVectorImpl<Instruction*> &NewInsts) {
348 unsigned NISize = NewInsts.size();
349
350 // Attempt to PHI translate with insertion.
351 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
352
353 // If successful, return the new value.
354 if (Addr) return Addr;
355
356 // If not, destroy any intermediate instructions inserted.
357 while (NewInsts.size() != NISize)
358 NewInsts.pop_back_val()->eraseFromParent();
359 return nullptr;
360 }
361
362
363 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
364 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
365 /// block. All newly created instructions are added to the NewInsts list.
366 /// This returns null on failure.
367 ///
368 Value *PHITransAddr::
InsertPHITranslatedSubExpr(Value * InVal,BasicBlock * CurBB,BasicBlock * PredBB,const DominatorTree & DT,SmallVectorImpl<Instruction * > & NewInsts)369 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
370 BasicBlock *PredBB, const DominatorTree &DT,
371 SmallVectorImpl<Instruction*> &NewInsts) {
372 // See if we have a version of this value already available and dominating
373 // PredBB. If so, there is no need to insert a new instance of it.
374 PHITransAddr Tmp(InVal, DL, AC);
375 if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT, /*MustDominate=*/true))
376 return Tmp.getAddr();
377
378 // We don't need to PHI translate values which aren't instructions.
379 auto *Inst = dyn_cast<Instruction>(InVal);
380 if (!Inst)
381 return nullptr;
382
383 // Handle cast of PHI translatable value.
384 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
385 if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
386 Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
387 CurBB, PredBB, DT, NewInsts);
388 if (!OpVal) return nullptr;
389
390 // Otherwise insert a cast at the end of PredBB.
391 CastInst *New = CastInst::Create(Cast->getOpcode(), OpVal, InVal->getType(),
392 InVal->getName() + ".phi.trans.insert",
393 PredBB->getTerminator());
394 New->setDebugLoc(Inst->getDebugLoc());
395 NewInsts.push_back(New);
396 return New;
397 }
398
399 // Handle getelementptr with at least one PHI operand.
400 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
401 SmallVector<Value*, 8> GEPOps;
402 BasicBlock *CurBB = GEP->getParent();
403 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
404 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
405 CurBB, PredBB, DT, NewInsts);
406 if (!OpVal) return nullptr;
407 GEPOps.push_back(OpVal);
408 }
409
410 GetElementPtrInst *Result = GetElementPtrInst::Create(
411 GEP->getSourceElementType(), GEPOps[0], makeArrayRef(GEPOps).slice(1),
412 InVal->getName() + ".phi.trans.insert", PredBB->getTerminator());
413 Result->setDebugLoc(Inst->getDebugLoc());
414 Result->setIsInBounds(GEP->isInBounds());
415 NewInsts.push_back(Result);
416 return Result;
417 }
418
419 #if 0
420 // FIXME: This code works, but it is unclear that we actually want to insert
421 // a big chain of computation in order to make a value available in a block.
422 // This needs to be evaluated carefully to consider its cost trade offs.
423
424 // Handle add with a constant RHS.
425 if (Inst->getOpcode() == Instruction::Add &&
426 isa<ConstantInt>(Inst->getOperand(1))) {
427 // PHI translate the LHS.
428 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
429 CurBB, PredBB, DT, NewInsts);
430 if (OpVal == 0) return 0;
431
432 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
433 InVal->getName()+".phi.trans.insert",
434 PredBB->getTerminator());
435 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
436 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
437 NewInsts.push_back(Res);
438 return Res;
439 }
440 #endif
441
442 return nullptr;
443 }
444