1//===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the PHITransAddr class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/PHITransAddr.h"
14#include "llvm/Analysis/InstructionSimplify.h"
15#include "llvm/Analysis/ValueTracking.h"
16#include "llvm/Config/llvm-config.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/Dominators.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace llvm;
24
25static cl::opt<bool> EnableAddPhiTranslation(
26 "gvn-add-phi-translation", cl::init(Val: false), cl::Hidden,
27 cl::desc("Enable phi-translation of add instructions"));
28
29static bool canPHITrans(Instruction *Inst) {
30 if (isa<PHINode>(Val: Inst) || isa<GetElementPtrInst>(Val: Inst) || isa<CastInst>(Val: Inst))
31 return true;
32
33 if (Inst->getOpcode() == Instruction::Add &&
34 isa<ConstantInt>(Val: Inst->getOperand(i: 1)))
35 return true;
36
37 return false;
38}
39
40#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
41LLVM_DUMP_METHOD void PHITransAddr::dump() const {
42 if (!Addr) {
43 dbgs() << "PHITransAddr: null\n";
44 return;
45 }
46 dbgs() << "PHITransAddr: " << *Addr << "\n";
47 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
48 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
49}
50#endif
51
52static bool verifySubExpr(Value *Expr,
53 SmallVectorImpl<Instruction *> &InstInputs) {
54 // If this is a non-instruction value, there is nothing to do.
55 Instruction *I = dyn_cast<Instruction>(Val: Expr);
56 if (!I) return true;
57
58 // If it's an instruction, it is either in Tmp or its operands recursively
59 // are.
60 if (auto Entry = find(Range&: InstInputs, Val: I); Entry != InstInputs.end()) {
61 InstInputs.erase(CI: Entry);
62 return true;
63 }
64
65 // If it isn't in the InstInputs list it is a subexpr incorporated into the
66 // address. Validate that it is phi translatable.
67 if (!canPHITrans(Inst: I)) {
68 errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
69 errs() << *I << '\n';
70 llvm_unreachable("Either something is missing from InstInputs or "
71 "canPHITrans is wrong.");
72 }
73
74 // Validate the operands of the instruction.
75 return all_of(Range: I->operands(),
76 P: [&](Value *Op) { return verifySubExpr(Expr: Op, InstInputs); });
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) return true;
84
85 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
86
87 if (!verifySubExpr(Expr: Addr, InstInputs&: Tmp))
88 return false;
89
90 if (!Tmp.empty()) {
91 errs() << "PHITransAddr contains extra instructions:\n";
92 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
93 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
94 llvm_unreachable("This is unexpected.");
95 }
96
97 // a-ok.
98 return true;
99}
100
101/// isPotentiallyPHITranslatable - If this needs PHI translation, return true
102/// if we have some hope of doing it. This should be used as a filter to
103/// avoid calling PHITranslateValue in hopeless situations.
104bool PHITransAddr::isPotentiallyPHITranslatable() const {
105 // If the input value is not an instruction, or if it is not defined in CurBB,
106 // then we don't need to phi translate it.
107 Instruction *Inst = dyn_cast<Instruction>(Val: Addr);
108 return !Inst || canPHITrans(Inst);
109}
110
111static void RemoveInstInputs(Value *V,
112 SmallVectorImpl<Instruction*> &InstInputs) {
113 Instruction *I = dyn_cast<Instruction>(Val: V);
114 if (!I) return;
115
116 // If the instruction is in the InstInputs list, remove it.
117 if (auto Entry = find(Range&: InstInputs, Val: I); Entry != InstInputs.end()) {
118 InstInputs.erase(CI: Entry);
119 return;
120 }
121
122 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
123
124 // Otherwise, it must have instruction inputs itself. Zap them recursively.
125 for (Value *Op : I->operands())
126 if (Instruction *OpInst = dyn_cast<Instruction>(Val: Op))
127 RemoveInstInputs(V: OpInst, InstInputs);
128}
129
130Value *PHITransAddr::translateSubExpr(Value *V, BasicBlock *CurBB,
131 BasicBlock *PredBB,
132 const DominatorTree *DT, Value *Cond,
133 bool CondVal) {
134 // If this is a non-instruction value, it can't require PHI translation.
135 Instruction *Inst = dyn_cast<Instruction>(Val: V);
136 if (!Inst) return V;
137
138 // Determine whether 'Inst' is an input to our PHI translatable expression.
139 bool isInput = is_contained(Range&: InstInputs, Element: Inst);
140
141 // Handle inputs instructions if needed.
142 if (isInput) {
143 if (Inst->getParent() != CurBB) {
144 // If it is an input defined in a different block, then it remains an
145 // input.
146 return Inst;
147 }
148
149 // If 'Inst' is defined in this block and is an input that needs to be phi
150 // translated, we need to incorporate the value into the expression or fail.
151
152 // In either case, the instruction itself isn't an input any longer.
153 InstInputs.erase(CI: find(Range&: InstInputs, Val: Inst));
154
155 // If this is a PHI, go ahead and translate it.
156 if (PHINode *PN = dyn_cast<PHINode>(Val: Inst)) {
157 Value *Incoming = PN->getIncomingValueForBlock(BB: PredBB);
158 // If the incoming value on this edge is a select on the condition we are
159 // resolving, fold it to the requested side. This is what lets us obtain
160 // the two distinct addresses referenced by a select-dependent load along
161 // a backedge (e.g. min/max idioms).
162 if (Cond)
163 if (auto *SI = dyn_cast<SelectInst>(Val: Incoming))
164 if (SI->getCondition() == Cond)
165 return addAsInput(V: CondVal ? SI->getTrueValue()
166 : SI->getFalseValue());
167 return addAsInput(V: Incoming);
168 }
169
170 // If this is a non-phi value, and it is analyzable, we can incorporate it
171 // into the expression by making all instruction operands be inputs.
172 if (!canPHITrans(Inst))
173 return nullptr;
174
175 // All instruction operands are now inputs (and of course, they may also be
176 // defined in this block, so they may need to be phi translated themselves.
177 for (Value *Op : Inst->operands())
178 addAsInput(V: Op);
179 }
180
181 // Ok, it must be an intermediate result (either because it started that way
182 // or because we just incorporated it into the expression). See if its
183 // operands need to be phi translated, and if so, reconstruct it.
184
185 if (CastInst *Cast = dyn_cast<CastInst>(Val: Inst)) {
186 Value *PHIIn =
187 translateSubExpr(V: Cast->getOperand(i_nocapture: 0), CurBB, PredBB, DT, Cond, CondVal);
188 if (!PHIIn) return nullptr;
189 if (PHIIn == Cast->getOperand(i_nocapture: 0))
190 return Cast;
191
192 // Find an available version of this cast.
193
194 // Try to simplify cast first.
195 if (Value *V = simplifyCastInst(CastOpc: Cast->getOpcode(), Op: PHIIn, Ty: Cast->getType(),
196 Q: {DL, TLI, DT, AC})) {
197 RemoveInstInputs(V: PHIIn, InstInputs);
198 return addAsInput(V);
199 }
200
201 // Otherwise we have to see if a casted version of the incoming pointer
202 // is available. If so, we can use it, otherwise we have to fail.
203 for (User *U : PHIIn->users()) {
204 if (CastInst *CastI = dyn_cast<CastInst>(Val: U))
205 if (CastI->getOpcode() == Cast->getOpcode() &&
206 CastI->getType() == Cast->getType() &&
207 (!DT || DT->dominates(A: CastI->getParent(), B: PredBB)))
208 return CastI;
209 }
210 return nullptr;
211 }
212
213 // Handle getelementptr with at least one PHI translatable operand.
214 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Inst)) {
215 SmallVector<Value*, 8> GEPOps;
216 bool AnyChanged = false;
217 for (Value *Op : GEP->operands()) {
218 Value *GEPOp = translateSubExpr(V: Op, CurBB, PredBB, DT, Cond, CondVal);
219 if (!GEPOp) return nullptr;
220
221 AnyChanged |= GEPOp != Op;
222 GEPOps.push_back(Elt: GEPOp);
223 }
224
225 if (!AnyChanged)
226 return GEP;
227
228 // Simplify the GEP to handle 'gep x, 0' -> x etc.
229 if (Value *V = simplifyGEPInst(SrcTy: GEP->getSourceElementType(), Ptr: GEPOps[0],
230 Indices: ArrayRef<Value *>(GEPOps).slice(N: 1),
231 NW: GEP->getNoWrapFlags(), Q: {DL, TLI, DT, AC})) {
232 for (Value *Op : GEPOps)
233 RemoveInstInputs(V: Op, InstInputs);
234
235 return addAsInput(V);
236 }
237
238 // Scan to see if we have this GEP available.
239 Value *APHIOp = GEPOps[0];
240 if (isa<ConstantData>(Val: APHIOp))
241 return nullptr;
242
243 for (User *U : APHIOp->users()) {
244 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: U))
245 if (GEPI->getType() == GEP->getType() &&
246 GEPI->getSourceElementType() == GEP->getSourceElementType() &&
247 GEPI->getNumOperands() == GEPOps.size() &&
248 GEPI->getParent()->getParent() == CurBB->getParent() &&
249 (!DT || DT->dominates(A: GEPI->getParent(), B: PredBB))) {
250 if (std::equal(first1: GEPOps.begin(), last1: GEPOps.end(), first2: GEPI->op_begin()))
251 return GEPI;
252 }
253 }
254 return nullptr;
255 }
256
257 // Handle add with a constant RHS.
258 if (Inst->getOpcode() == Instruction::Add &&
259 isa<ConstantInt>(Val: Inst->getOperand(i: 1))) {
260 // PHI translate the LHS.
261 Constant *RHS = cast<ConstantInt>(Val: Inst->getOperand(i: 1));
262 bool isNSW = cast<BinaryOperator>(Val: Inst)->hasNoSignedWrap();
263 bool isNUW = cast<BinaryOperator>(Val: Inst)->hasNoUnsignedWrap();
264
265 Value *LHS =
266 translateSubExpr(V: Inst->getOperand(i: 0), CurBB, PredBB, DT, Cond, CondVal);
267 if (!LHS) return nullptr;
268
269 // If the PHI translated LHS is an add of a constant, fold the immediates.
270 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: LHS))
271 if (BOp->getOpcode() == Instruction::Add)
272 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BOp->getOperand(i_nocapture: 1))) {
273 LHS = BOp->getOperand(i_nocapture: 0);
274 RHS = ConstantExpr::getAdd(C1: RHS, C2: CI);
275 isNSW = isNUW = false;
276
277 // If the old 'LHS' was an input, add the new 'LHS' as an input.
278 if (is_contained(Range&: InstInputs, Element: BOp)) {
279 RemoveInstInputs(V: BOp, InstInputs);
280 addAsInput(V: LHS);
281 }
282 }
283
284 // See if the add simplifies away.
285 if (Value *Res = simplifyAddInst(LHS, RHS, IsNSW: isNSW, IsNUW: isNUW, Q: {DL, TLI, DT, AC})) {
286 // If we simplified the operands, the LHS is no longer an input, but Res
287 // is.
288 RemoveInstInputs(V: LHS, InstInputs);
289 return addAsInput(V: Res);
290 }
291
292 // If we didn't modify the add, just return it.
293 if (LHS == Inst->getOperand(i: 0) && RHS == Inst->getOperand(i: 1))
294 return Inst;
295
296 // Otherwise, see if we have this add available somewhere.
297 for (User *U : LHS->users()) {
298 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U))
299 if (BO->getOpcode() == Instruction::Add &&
300 BO->getOperand(i_nocapture: 0) == LHS && BO->getOperand(i_nocapture: 1) == RHS &&
301 BO->getParent()->getParent() == CurBB->getParent() &&
302 (!DT || DT->dominates(A: BO->getParent(), B: PredBB)))
303 return BO;
304 }
305
306 return nullptr;
307 }
308
309 // Otherwise, we failed.
310 return nullptr;
311}
312
313/// PHITranslateValue - PHI translate the current address up the CFG from
314/// CurBB to Pred, updating our state to reflect any needed changes. If
315/// 'MustDominate' is true, the translated value must dominate PredBB.
316Value *PHITransAddr::translateValue(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(A: PredBB))
322 Addr = translateSubExpr(V: Addr, CurBB, PredBB, DT);
323 else
324 Addr = nullptr;
325 assert(verify() && "Invalid PHITransAddr!");
326
327 if (MustDominate)
328 // Make sure the value is live in the predecessor.
329 if (Instruction *Inst = dyn_cast_or_null<Instruction>(Val: Addr))
330 if (!DT->dominates(A: Inst->getParent(), B: PredBB))
331 Addr = nullptr;
332
333 return Addr;
334}
335
336SelectAddr::SelectAddrs PHITransAddr::translateValue(BasicBlock *CurBB,
337 BasicBlock *PredBB,
338 const DominatorTree *DT,
339 Value *Cond) {
340 assert(Cond && "expected a non-null select condition");
341 assert(verify() && "Invalid PHITransAddr!");
342
343 if (!DT || !DT->isReachableFromEntry(A: PredBB))
344 return {nullptr, nullptr};
345
346 auto TranslateSide = [&](bool CondVal) -> Value * {
347 // Work on a copy so that the original address state is preserved and the
348 // other side can be translated independently.
349 PHITransAddr Tmp(*this);
350 return Tmp.translateSubExpr(V: Tmp.Addr, CurBB, PredBB, DT, Cond, CondVal);
351 };
352
353 return {TranslateSide(/*CondVal=*/true), TranslateSide(/*CondVal=*/false)};
354}
355
356Value *PHITransAddr::getSelectCondition() const {
357 for (Instruction *I : InstInputs)
358 if (auto *SI = dyn_cast<SelectInst>(Val: I))
359 return SI->getCondition();
360 return nullptr;
361}
362
363/// PHITranslateWithInsertion - PHI translate this value into the specified
364/// predecessor block, inserting a computation of the value if it is
365/// unavailable.
366///
367/// All newly created instructions are added to the NewInsts list. This
368/// returns null on failure.
369///
370Value *
371PHITransAddr::translateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
372 const DominatorTree &DT,
373 SmallVectorImpl<Instruction *> &NewInsts) {
374 unsigned NISize = NewInsts.size();
375
376 // Attempt to PHI translate with insertion.
377 Addr = insertTranslatedSubExpr(InVal: Addr, CurBB, PredBB, DT, NewInsts);
378
379 // If successful, return the new value.
380 if (Addr) return Addr;
381
382 // If not, destroy any intermediate instructions inserted.
383 while (NewInsts.size() != NISize)
384 NewInsts.pop_back_val()->eraseFromParent();
385 return nullptr;
386}
387
388/// insertTranslatedSubExpr - Insert a computation of the PHI translated
389/// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
390/// block. All newly created instructions are added to the NewInsts list.
391/// This returns null on failure.
392///
393Value *PHITransAddr::insertTranslatedSubExpr(
394 Value *InVal, BasicBlock *CurBB, BasicBlock *PredBB,
395 const DominatorTree &DT, SmallVectorImpl<Instruction *> &NewInsts) {
396 // See if we have a version of this value already available and dominating
397 // PredBB. If so, there is no need to insert a new instance of it.
398 PHITransAddr Tmp(InVal, DL, AC);
399 if (Value *Addr =
400 Tmp.translateValue(CurBB, PredBB, DT: &DT, /*MustDominate=*/true))
401 return Addr;
402
403 // We don't need to PHI translate values which aren't instructions.
404 auto *Inst = dyn_cast<Instruction>(Val: InVal);
405 if (!Inst)
406 return nullptr;
407
408 // Handle cast of PHI translatable value.
409 if (CastInst *Cast = dyn_cast<CastInst>(Val: Inst)) {
410 Value *OpVal = insertTranslatedSubExpr(InVal: Cast->getOperand(i_nocapture: 0), CurBB, PredBB,
411 DT, NewInsts);
412 if (!OpVal) return nullptr;
413
414 // Otherwise insert a cast at the end of PredBB.
415 CastInst *New = CastInst::Create(Cast->getOpcode(), S: OpVal, Ty: InVal->getType(),
416 Name: InVal->getName() + ".phi.trans.insert",
417 InsertBefore: PredBB->getTerminator()->getIterator());
418 New->setDebugLoc(Inst->getDebugLoc());
419 NewInsts.push_back(Elt: New);
420 return New;
421 }
422
423 // Handle getelementptr with at least one PHI operand.
424 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Inst)) {
425 SmallVector<Value*, 8> GEPOps;
426 BasicBlock *CurBB = GEP->getParent();
427 for (Value *Op : GEP->operands()) {
428 Value *OpVal = insertTranslatedSubExpr(InVal: Op, CurBB, PredBB, DT, NewInsts);
429 if (!OpVal) return nullptr;
430 GEPOps.push_back(Elt: OpVal);
431 }
432
433 GetElementPtrInst *Result = GetElementPtrInst::Create(
434 PointeeType: GEP->getSourceElementType(), Ptr: GEPOps[0], IdxList: ArrayRef(GEPOps).slice(N: 1),
435 NameStr: InVal->getName() + ".phi.trans.insert",
436 InsertBefore: PredBB->getTerminator()->getIterator());
437 Result->setDebugLoc(Inst->getDebugLoc());
438 Result->setNoWrapFlags(GEP->getNoWrapFlags());
439 NewInsts.push_back(Elt: Result);
440 return Result;
441 }
442
443 // Handle add with a constant RHS.
444 if (EnableAddPhiTranslation && Inst->getOpcode() == Instruction::Add &&
445 isa<ConstantInt>(Val: Inst->getOperand(i: 1))) {
446
447 // FIXME: This code works, but it is unclear that we actually want to insert
448 // a big chain of computation in order to make a value available in a block.
449 // This needs to be evaluated carefully to consider its cost trade offs.
450
451 // PHI translate the LHS.
452 Value *OpVal = insertTranslatedSubExpr(InVal: Inst->getOperand(i: 0), CurBB, PredBB,
453 DT, NewInsts);
454 if (OpVal == nullptr)
455 return nullptr;
456
457 BinaryOperator *Res = BinaryOperator::CreateAdd(
458 V1: OpVal, V2: Inst->getOperand(i: 1), Name: InVal->getName() + ".phi.trans.insert",
459 InsertBefore: PredBB->getTerminator()->getIterator());
460 Res->setHasNoSignedWrap(cast<BinaryOperator>(Val: Inst)->hasNoSignedWrap());
461 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Val: Inst)->hasNoUnsignedWrap());
462 NewInsts.push_back(Elt: Res);
463 return Res;
464 }
465
466 return nullptr;
467}
468