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