1 //===- InstCombinePHI.cpp -------------------------------------------------===// 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 visitPHINode function. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/ValueTracking.h" 19 #include "llvm/IR/PatternMatch.h" 20 #include "llvm/Support/CommandLine.h" 21 #include "llvm/Transforms/InstCombine/InstCombiner.h" 22 #include "llvm/Transforms/Utils/Local.h" 23 24 using namespace llvm; 25 using namespace llvm::PatternMatch; 26 27 #define DEBUG_TYPE "instcombine" 28 29 static cl::opt<unsigned> 30 MaxNumPhis("instcombine-max-num-phis", cl::init(512), 31 cl::desc("Maximum number phis to handle in intptr/ptrint folding")); 32 33 STATISTIC(NumPHIsOfInsertValues, 34 "Number of phi-of-insertvalue turned into insertvalue-of-phis"); 35 STATISTIC(NumPHIsOfExtractValues, 36 "Number of phi-of-extractvalue turned into extractvalue-of-phi"); 37 38 /// The PHI arguments will be folded into a single operation with a PHI node 39 /// as input. The debug location of the single operation will be the merged 40 /// locations of the original PHI node arguments. 41 void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) { 42 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); 43 Inst->setDebugLoc(FirstInst->getDebugLoc()); 44 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc 45 // will be inefficient. 46 assert(!isa<CallInst>(Inst)); 47 48 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { 49 auto *I = cast<Instruction>(PN.getIncomingValue(i)); 50 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc()); 51 } 52 } 53 54 // Replace Integer typed PHI PN if the PHI's value is used as a pointer value. 55 // If there is an existing pointer typed PHI that produces the same value as PN, 56 // replace PN and the IntToPtr operation with it. Otherwise, synthesize a new 57 // PHI node: 58 // 59 // Case-1: 60 // bb1: 61 // int_init = PtrToInt(ptr_init) 62 // br label %bb2 63 // bb2: 64 // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2] 65 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2] 66 // ptr_val2 = IntToPtr(int_val) 67 // ... 68 // use(ptr_val2) 69 // ptr_val_inc = ... 70 // inc_val_inc = PtrToInt(ptr_val_inc) 71 // 72 // ==> 73 // bb1: 74 // br label %bb2 75 // bb2: 76 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2] 77 // ... 78 // use(ptr_val) 79 // ptr_val_inc = ... 80 // 81 // Case-2: 82 // bb1: 83 // int_ptr = BitCast(ptr_ptr) 84 // int_init = Load(int_ptr) 85 // br label %bb2 86 // bb2: 87 // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2] 88 // ptr_val2 = IntToPtr(int_val) 89 // ... 90 // use(ptr_val2) 91 // ptr_val_inc = ... 92 // inc_val_inc = PtrToInt(ptr_val_inc) 93 // ==> 94 // bb1: 95 // ptr_init = Load(ptr_ptr) 96 // br label %bb2 97 // bb2: 98 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2] 99 // ... 100 // use(ptr_val) 101 // ptr_val_inc = ... 102 // ... 103 // 104 Instruction *InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) { 105 if (!PN.getType()->isIntegerTy()) 106 return nullptr; 107 if (!PN.hasOneUse()) 108 return nullptr; 109 110 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back()); 111 if (!IntToPtr) 112 return nullptr; 113 114 // Check if the pointer is actually used as pointer: 115 auto HasPointerUse = [](Instruction *IIP) { 116 for (User *U : IIP->users()) { 117 Value *Ptr = nullptr; 118 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) { 119 Ptr = LoadI->getPointerOperand(); 120 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 121 Ptr = SI->getPointerOperand(); 122 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) { 123 Ptr = GI->getPointerOperand(); 124 } 125 126 if (Ptr && Ptr == IIP) 127 return true; 128 } 129 return false; 130 }; 131 132 if (!HasPointerUse(IntToPtr)) 133 return nullptr; 134 135 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) != 136 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType())) 137 return nullptr; 138 139 SmallVector<Value *, 4> AvailablePtrVals; 140 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) { 141 Value *Arg = PN.getIncomingValue(i); 142 143 // First look backward: 144 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) { 145 AvailablePtrVals.emplace_back(PI->getOperand(0)); 146 continue; 147 } 148 149 // Next look forward: 150 Value *ArgIntToPtr = nullptr; 151 for (User *U : Arg->users()) { 152 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() && 153 (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) || 154 cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) { 155 ArgIntToPtr = U; 156 break; 157 } 158 } 159 160 if (ArgIntToPtr) { 161 AvailablePtrVals.emplace_back(ArgIntToPtr); 162 continue; 163 } 164 165 // If Arg is defined by a PHI, allow it. This will also create 166 // more opportunities iteratively. 167 if (isa<PHINode>(Arg)) { 168 AvailablePtrVals.emplace_back(Arg); 169 continue; 170 } 171 172 // For a single use integer load: 173 auto *LoadI = dyn_cast<LoadInst>(Arg); 174 if (!LoadI) 175 return nullptr; 176 177 if (!LoadI->hasOneUse()) 178 return nullptr; 179 180 // Push the integer typed Load instruction into the available 181 // value set, and fix it up later when the pointer typed PHI 182 // is synthesized. 183 AvailablePtrVals.emplace_back(LoadI); 184 } 185 186 // Now search for a matching PHI 187 auto *BB = PN.getParent(); 188 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() && 189 "Not enough available ptr typed incoming values"); 190 PHINode *MatchingPtrPHI = nullptr; 191 unsigned NumPhis = 0; 192 for (auto II = BB->begin(); II != BB->end(); II++, NumPhis++) { 193 // FIXME: consider handling this in AggressiveInstCombine 194 PHINode *PtrPHI = dyn_cast<PHINode>(II); 195 if (!PtrPHI) 196 break; 197 if (NumPhis > MaxNumPhis) 198 return nullptr; 199 if (PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType()) 200 continue; 201 MatchingPtrPHI = PtrPHI; 202 for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) { 203 if (AvailablePtrVals[i] != 204 PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) { 205 MatchingPtrPHI = nullptr; 206 break; 207 } 208 } 209 210 if (MatchingPtrPHI) 211 break; 212 } 213 214 if (MatchingPtrPHI) { 215 assert(MatchingPtrPHI->getType() == IntToPtr->getType() && 216 "Phi's Type does not match with IntToPtr"); 217 // The PtrToCast + IntToPtr will be simplified later 218 return CastInst::CreateBitOrPointerCast(MatchingPtrPHI, 219 IntToPtr->getOperand(0)->getType()); 220 } 221 222 // If it requires a conversion for every PHI operand, do not do it. 223 if (all_of(AvailablePtrVals, [&](Value *V) { 224 return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V); 225 })) 226 return nullptr; 227 228 // If any of the operand that requires casting is a terminator 229 // instruction, do not do it. Similarly, do not do the transform if the value 230 // is PHI in a block with no insertion point, for example, a catchswitch 231 // block, since we will not be able to insert a cast after the PHI. 232 if (any_of(AvailablePtrVals, [&](Value *V) { 233 if (V->getType() == IntToPtr->getType()) 234 return false; 235 auto *Inst = dyn_cast<Instruction>(V); 236 if (!Inst) 237 return false; 238 if (Inst->isTerminator()) 239 return true; 240 auto *BB = Inst->getParent(); 241 if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end()) 242 return true; 243 return false; 244 })) 245 return nullptr; 246 247 PHINode *NewPtrPHI = PHINode::Create( 248 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr"); 249 250 InsertNewInstBefore(NewPtrPHI, PN); 251 SmallDenseMap<Value *, Instruction *> Casts; 252 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) { 253 auto *IncomingBB = PN.getIncomingBlock(i); 254 auto *IncomingVal = AvailablePtrVals[i]; 255 256 if (IncomingVal->getType() == IntToPtr->getType()) { 257 NewPtrPHI->addIncoming(IncomingVal, IncomingBB); 258 continue; 259 } 260 261 #ifndef NDEBUG 262 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal); 263 assert((isa<PHINode>(IncomingVal) || 264 IncomingVal->getType()->isPointerTy() || 265 (LoadI && LoadI->hasOneUse())) && 266 "Can not replace LoadInst with multiple uses"); 267 #endif 268 // Need to insert a BitCast. 269 // For an integer Load instruction with a single use, the load + IntToPtr 270 // cast will be simplified into a pointer load: 271 // %v = load i64, i64* %a.ip, align 8 272 // %v.cast = inttoptr i64 %v to float ** 273 // ==> 274 // %v.ptrp = bitcast i64 * %a.ip to float ** 275 // %v.cast = load float *, float ** %v.ptrp, align 8 276 Instruction *&CI = Casts[IncomingVal]; 277 if (!CI) { 278 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(), 279 IncomingVal->getName() + ".ptr"); 280 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) { 281 BasicBlock::iterator InsertPos(IncomingI); 282 InsertPos++; 283 BasicBlock *BB = IncomingI->getParent(); 284 if (isa<PHINode>(IncomingI)) 285 InsertPos = BB->getFirstInsertionPt(); 286 assert(InsertPos != BB->end() && "should have checked above"); 287 InsertNewInstBefore(CI, *InsertPos); 288 } else { 289 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock(); 290 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt()); 291 } 292 } 293 NewPtrPHI->addIncoming(CI, IncomingBB); 294 } 295 296 // The PtrToCast + IntToPtr will be simplified later 297 return CastInst::CreateBitOrPointerCast(NewPtrPHI, 298 IntToPtr->getOperand(0)->getType()); 299 } 300 301 /// If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)], 302 /// turn this into a phi[a,c] and phi[b,d] and a single insertvalue. 303 Instruction * 304 InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) { 305 auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0)); 306 307 // Scan to see if all operands are `insertvalue`'s with the same indicies, 308 // and all have a single use. 309 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { 310 auto *I = dyn_cast<InsertValueInst>(PN.getIncomingValue(i)); 311 if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices()) 312 return nullptr; 313 } 314 315 // For each operand of an `insertvalue` 316 std::array<PHINode *, 2> NewOperands; 317 for (int OpIdx : {0, 1}) { 318 auto *&NewOperand = NewOperands[OpIdx]; 319 // Create a new PHI node to receive the values the operand has in each 320 // incoming basic block. 321 NewOperand = PHINode::Create( 322 FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(), 323 FirstIVI->getOperand(OpIdx)->getName() + ".pn"); 324 // And populate each operand's PHI with said values. 325 for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) 326 NewOperand->addIncoming( 327 cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx), 328 std::get<0>(Incoming)); 329 InsertNewInstBefore(NewOperand, PN); 330 } 331 332 // And finally, create `insertvalue` over the newly-formed PHI nodes. 333 auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1], 334 FirstIVI->getIndices(), PN.getName()); 335 336 PHIArgMergedDebugLoc(NewIVI, PN); 337 ++NumPHIsOfInsertValues; 338 return NewIVI; 339 } 340 341 /// If we have something like phi [extractvalue(a,0), extractvalue(b,0)], 342 /// turn this into a phi[a,b] and a single extractvalue. 343 Instruction * 344 InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) { 345 auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0)); 346 347 // Scan to see if all operands are `extractvalue`'s with the same indicies, 348 // and all have a single use. 349 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { 350 auto *I = dyn_cast<ExtractValueInst>(PN.getIncomingValue(i)); 351 if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() || 352 I->getAggregateOperand()->getType() != 353 FirstEVI->getAggregateOperand()->getType()) 354 return nullptr; 355 } 356 357 // Create a new PHI node to receive the values the aggregate operand has 358 // in each incoming basic block. 359 auto *NewAggregateOperand = PHINode::Create( 360 FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(), 361 FirstEVI->getAggregateOperand()->getName() + ".pn"); 362 // And populate the PHI with said values. 363 for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) 364 NewAggregateOperand->addIncoming( 365 cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(), 366 std::get<0>(Incoming)); 367 InsertNewInstBefore(NewAggregateOperand, PN); 368 369 // And finally, create `extractvalue` over the newly-formed PHI nodes. 370 auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand, 371 FirstEVI->getIndices(), PN.getName()); 372 373 PHIArgMergedDebugLoc(NewEVI, PN); 374 ++NumPHIsOfExtractValues; 375 return NewEVI; 376 } 377 378 /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the 379 /// adds all have a single user, turn this into a phi and a single binop. 380 Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) { 381 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); 382 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)); 383 unsigned Opc = FirstInst->getOpcode(); 384 Value *LHSVal = FirstInst->getOperand(0); 385 Value *RHSVal = FirstInst->getOperand(1); 386 387 Type *LHSType = LHSVal->getType(); 388 Type *RHSType = RHSVal->getType(); 389 390 // Scan to see if all operands are the same opcode, and all have one user. 391 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { 392 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i)); 393 if (!I || I->getOpcode() != Opc || !I->hasOneUser() || 394 // Verify type of the LHS matches so we don't fold cmp's of different 395 // types. 396 I->getOperand(0)->getType() != LHSType || 397 I->getOperand(1)->getType() != RHSType) 398 return nullptr; 399 400 // If they are CmpInst instructions, check their predicates 401 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 402 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate()) 403 return nullptr; 404 405 // Keep track of which operand needs a phi node. 406 if (I->getOperand(0) != LHSVal) LHSVal = nullptr; 407 if (I->getOperand(1) != RHSVal) RHSVal = nullptr; 408 } 409 410 // If both LHS and RHS would need a PHI, don't do this transformation, 411 // because it would increase the number of PHIs entering the block, 412 // which leads to higher register pressure. This is especially 413 // bad when the PHIs are in the header of a loop. 414 if (!LHSVal && !RHSVal) 415 return nullptr; 416 417 // Otherwise, this is safe to transform! 418 419 Value *InLHS = FirstInst->getOperand(0); 420 Value *InRHS = FirstInst->getOperand(1); 421 PHINode *NewLHS = nullptr, *NewRHS = nullptr; 422 if (!LHSVal) { 423 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(), 424 FirstInst->getOperand(0)->getName() + ".pn"); 425 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0)); 426 InsertNewInstBefore(NewLHS, PN); 427 LHSVal = NewLHS; 428 } 429 430 if (!RHSVal) { 431 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(), 432 FirstInst->getOperand(1)->getName() + ".pn"); 433 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0)); 434 InsertNewInstBefore(NewRHS, PN); 435 RHSVal = NewRHS; 436 } 437 438 // Add all operands to the new PHIs. 439 if (NewLHS || NewRHS) { 440 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 441 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i)); 442 if (NewLHS) { 443 Value *NewInLHS = InInst->getOperand(0); 444 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i)); 445 } 446 if (NewRHS) { 447 Value *NewInRHS = InInst->getOperand(1); 448 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i)); 449 } 450 } 451 } 452 453 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) { 454 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 455 LHSVal, RHSVal); 456 PHIArgMergedDebugLoc(NewCI, PN); 457 return NewCI; 458 } 459 460 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst); 461 BinaryOperator *NewBinOp = 462 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal); 463 464 NewBinOp->copyIRFlags(PN.getIncomingValue(0)); 465 466 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) 467 NewBinOp->andIRFlags(PN.getIncomingValue(i)); 468 469 PHIArgMergedDebugLoc(NewBinOp, PN); 470 return NewBinOp; 471 } 472 473 Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) { 474 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0)); 475 476 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 477 FirstInst->op_end()); 478 // This is true if all GEP bases are allocas and if all indices into them are 479 // constants. 480 bool AllBasePointersAreAllocas = true; 481 482 // We don't want to replace this phi if the replacement would require 483 // more than one phi, which leads to higher register pressure. This is 484 // especially bad when the PHIs are in the header of a loop. 485 bool NeededPhi = false; 486 487 bool AllInBounds = true; 488 489 // Scan to see if all operands are the same opcode, and all have one user. 490 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { 491 GetElementPtrInst *GEP = 492 dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i)); 493 if (!GEP || !GEP->hasOneUser() || GEP->getType() != FirstInst->getType() || 494 GEP->getNumOperands() != FirstInst->getNumOperands()) 495 return nullptr; 496 497 AllInBounds &= GEP->isInBounds(); 498 499 // Keep track of whether or not all GEPs are of alloca pointers. 500 if (AllBasePointersAreAllocas && 501 (!isa<AllocaInst>(GEP->getOperand(0)) || 502 !GEP->hasAllConstantIndices())) 503 AllBasePointersAreAllocas = false; 504 505 // Compare the operand lists. 506 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) { 507 if (FirstInst->getOperand(op) == GEP->getOperand(op)) 508 continue; 509 510 // Don't merge two GEPs when two operands differ (introducing phi nodes) 511 // if one of the PHIs has a constant for the index. The index may be 512 // substantially cheaper to compute for the constants, so making it a 513 // variable index could pessimize the path. This also handles the case 514 // for struct indices, which must always be constant. 515 if (isa<ConstantInt>(FirstInst->getOperand(op)) || 516 isa<ConstantInt>(GEP->getOperand(op))) 517 return nullptr; 518 519 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType()) 520 return nullptr; 521 522 // If we already needed a PHI for an earlier operand, and another operand 523 // also requires a PHI, we'd be introducing more PHIs than we're 524 // eliminating, which increases register pressure on entry to the PHI's 525 // block. 526 if (NeededPhi) 527 return nullptr; 528 529 FixedOperands[op] = nullptr; // Needs a PHI. 530 NeededPhi = true; 531 } 532 } 533 534 // If all of the base pointers of the PHI'd GEPs are from allocas, don't 535 // bother doing this transformation. At best, this will just save a bit of 536 // offset calculation, but all the predecessors will have to materialize the 537 // stack address into a register anyway. We'd actually rather *clone* the 538 // load up into the predecessors so that we have a load of a gep of an alloca, 539 // which can usually all be folded into the load. 540 if (AllBasePointersAreAllocas) 541 return nullptr; 542 543 // Otherwise, this is safe to transform. Insert PHI nodes for each operand 544 // that is variable. 545 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size()); 546 547 bool HasAnyPHIs = false; 548 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) { 549 if (FixedOperands[i]) continue; // operand doesn't need a phi. 550 Value *FirstOp = FirstInst->getOperand(i); 551 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e, 552 FirstOp->getName()+".pn"); 553 InsertNewInstBefore(NewPN, PN); 554 555 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0)); 556 OperandPhis[i] = NewPN; 557 FixedOperands[i] = NewPN; 558 HasAnyPHIs = true; 559 } 560 561 562 // Add all operands to the new PHIs. 563 if (HasAnyPHIs) { 564 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 565 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i)); 566 BasicBlock *InBB = PN.getIncomingBlock(i); 567 568 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op) 569 if (PHINode *OpPhi = OperandPhis[op]) 570 OpPhi->addIncoming(InGEP->getOperand(op), InBB); 571 } 572 } 573 574 Value *Base = FixedOperands[0]; 575 GetElementPtrInst *NewGEP = 576 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base, 577 makeArrayRef(FixedOperands).slice(1)); 578 if (AllInBounds) NewGEP->setIsInBounds(); 579 PHIArgMergedDebugLoc(NewGEP, PN); 580 return NewGEP; 581 } 582 583 /// Return true if we know that it is safe to sink the load out of the block 584 /// that defines it. This means that it must be obvious the value of the load is 585 /// not changed from the point of the load to the end of the block it is in. 586 /// 587 /// Finally, it is safe, but not profitable, to sink a load targeting a 588 /// non-address-taken alloca. Doing so will cause us to not promote the alloca 589 /// to a register. 590 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) { 591 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end(); 592 593 for (++BBI; BBI != E; ++BBI) 594 if (BBI->mayWriteToMemory()) 595 return false; 596 597 // Check for non-address taken alloca. If not address-taken already, it isn't 598 // profitable to do this xform. 599 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) { 600 bool isAddressTaken = false; 601 for (User *U : AI->users()) { 602 if (isa<LoadInst>(U)) continue; 603 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 604 // If storing TO the alloca, then the address isn't taken. 605 if (SI->getOperand(1) == AI) continue; 606 } 607 isAddressTaken = true; 608 break; 609 } 610 611 if (!isAddressTaken && AI->isStaticAlloca()) 612 return false; 613 } 614 615 // If this load is a load from a GEP with a constant offset from an alloca, 616 // then we don't want to sink it. In its present form, it will be 617 // load [constant stack offset]. Sinking it will cause us to have to 618 // materialize the stack addresses in each predecessor in a register only to 619 // do a shared load from register in the successor. 620 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0))) 621 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0))) 622 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices()) 623 return false; 624 625 return true; 626 } 627 628 Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) { 629 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0)); 630 631 // FIXME: This is overconservative; this transform is allowed in some cases 632 // for atomic operations. 633 if (FirstLI->isAtomic()) 634 return nullptr; 635 636 // When processing loads, we need to propagate two bits of information to the 637 // sunk load: whether it is volatile, and what its alignment is. We currently 638 // don't sink loads when some have their alignment specified and some don't. 639 // visitLoadInst will propagate an alignment onto the load when TD is around, 640 // and if TD isn't around, we can't handle the mixed case. 641 bool isVolatile = FirstLI->isVolatile(); 642 Align LoadAlignment = FirstLI->getAlign(); 643 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace(); 644 645 // We can't sink the load if the loaded value could be modified between the 646 // load and the PHI. 647 if (FirstLI->getParent() != PN.getIncomingBlock(0) || 648 !isSafeAndProfitableToSinkLoad(FirstLI)) 649 return nullptr; 650 651 // If the PHI is of volatile loads and the load block has multiple 652 // successors, sinking it would remove a load of the volatile value from 653 // the path through the other successor. 654 if (isVolatile && 655 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1) 656 return nullptr; 657 658 // Check to see if all arguments are the same operation. 659 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 660 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i)); 661 if (!LI || !LI->hasOneUser()) 662 return nullptr; 663 664 // We can't sink the load if the loaded value could be modified between 665 // the load and the PHI. 666 if (LI->isVolatile() != isVolatile || 667 LI->getParent() != PN.getIncomingBlock(i) || 668 LI->getPointerAddressSpace() != LoadAddrSpace || 669 !isSafeAndProfitableToSinkLoad(LI)) 670 return nullptr; 671 672 LoadAlignment = std::min(LoadAlignment, Align(LI->getAlign())); 673 674 // If the PHI is of volatile loads and the load block has multiple 675 // successors, sinking it would remove a load of the volatile value from 676 // the path through the other successor. 677 if (isVolatile && 678 LI->getParent()->getTerminator()->getNumSuccessors() != 1) 679 return nullptr; 680 } 681 682 // Okay, they are all the same operation. Create a new PHI node of the 683 // correct type, and PHI together all of the LHS's of the instructions. 684 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(), 685 PN.getNumIncomingValues(), 686 PN.getName()+".in"); 687 688 Value *InVal = FirstLI->getOperand(0); 689 NewPN->addIncoming(InVal, PN.getIncomingBlock(0)); 690 LoadInst *NewLI = 691 new LoadInst(FirstLI->getType(), NewPN, "", isVolatile, LoadAlignment); 692 693 unsigned KnownIDs[] = { 694 LLVMContext::MD_tbaa, 695 LLVMContext::MD_range, 696 LLVMContext::MD_invariant_load, 697 LLVMContext::MD_alias_scope, 698 LLVMContext::MD_noalias, 699 LLVMContext::MD_nonnull, 700 LLVMContext::MD_align, 701 LLVMContext::MD_dereferenceable, 702 LLVMContext::MD_dereferenceable_or_null, 703 LLVMContext::MD_access_group, 704 }; 705 706 for (unsigned ID : KnownIDs) 707 NewLI->setMetadata(ID, FirstLI->getMetadata(ID)); 708 709 // Add all operands to the new PHI and combine TBAA metadata. 710 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 711 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i)); 712 combineMetadata(NewLI, LI, KnownIDs, true); 713 Value *NewInVal = LI->getOperand(0); 714 if (NewInVal != InVal) 715 InVal = nullptr; 716 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i)); 717 } 718 719 if (InVal) { 720 // The new PHI unions all of the same values together. This is really 721 // common, so we handle it intelligently here for compile-time speed. 722 NewLI->setOperand(0, InVal); 723 delete NewPN; 724 } else { 725 InsertNewInstBefore(NewPN, PN); 726 } 727 728 // If this was a volatile load that we are merging, make sure to loop through 729 // and mark all the input loads as non-volatile. If we don't do this, we will 730 // insert a new volatile load and the old ones will not be deletable. 731 if (isVolatile) 732 for (Value *IncValue : PN.incoming_values()) 733 cast<LoadInst>(IncValue)->setVolatile(false); 734 735 PHIArgMergedDebugLoc(NewLI, PN); 736 return NewLI; 737 } 738 739 /// TODO: This function could handle other cast types, but then it might 740 /// require special-casing a cast from the 'i1' type. See the comment in 741 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types. 742 Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) { 743 // We cannot create a new instruction after the PHI if the terminator is an 744 // EHPad because there is no valid insertion point. 745 if (Instruction *TI = Phi.getParent()->getTerminator()) 746 if (TI->isEHPad()) 747 return nullptr; 748 749 // Early exit for the common case of a phi with two operands. These are 750 // handled elsewhere. See the comment below where we check the count of zexts 751 // and constants for more details. 752 unsigned NumIncomingValues = Phi.getNumIncomingValues(); 753 if (NumIncomingValues < 3) 754 return nullptr; 755 756 // Find the narrower type specified by the first zext. 757 Type *NarrowType = nullptr; 758 for (Value *V : Phi.incoming_values()) { 759 if (auto *Zext = dyn_cast<ZExtInst>(V)) { 760 NarrowType = Zext->getSrcTy(); 761 break; 762 } 763 } 764 if (!NarrowType) 765 return nullptr; 766 767 // Walk the phi operands checking that we only have zexts or constants that 768 // we can shrink for free. Store the new operands for the new phi. 769 SmallVector<Value *, 4> NewIncoming; 770 unsigned NumZexts = 0; 771 unsigned NumConsts = 0; 772 for (Value *V : Phi.incoming_values()) { 773 if (auto *Zext = dyn_cast<ZExtInst>(V)) { 774 // All zexts must be identical and have one user. 775 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser()) 776 return nullptr; 777 NewIncoming.push_back(Zext->getOperand(0)); 778 NumZexts++; 779 } else if (auto *C = dyn_cast<Constant>(V)) { 780 // Make sure that constants can fit in the new type. 781 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType); 782 if (ConstantExpr::getZExt(Trunc, C->getType()) != C) 783 return nullptr; 784 NewIncoming.push_back(Trunc); 785 NumConsts++; 786 } else { 787 // If it's not a cast or a constant, bail out. 788 return nullptr; 789 } 790 } 791 792 // The more common cases of a phi with no constant operands or just one 793 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi() 794 // respectively. foldOpIntoPhi() wants to do the opposite transform that is 795 // performed here. It tries to replicate a cast in the phi operand's basic 796 // block to expose other folding opportunities. Thus, InstCombine will 797 // infinite loop without this check. 798 if (NumConsts == 0 || NumZexts < 2) 799 return nullptr; 800 801 // All incoming values are zexts or constants that are safe to truncate. 802 // Create a new phi node of the narrow type, phi together all of the new 803 // operands, and zext the result back to the original type. 804 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues, 805 Phi.getName() + ".shrunk"); 806 for (unsigned i = 0; i != NumIncomingValues; ++i) 807 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i)); 808 809 InsertNewInstBefore(NewPhi, Phi); 810 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType()); 811 } 812 813 /// If all operands to a PHI node are the same "unary" operator and they all are 814 /// only used by the PHI, PHI together their inputs, and do the operation once, 815 /// to the result of the PHI. 816 Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) { 817 // We cannot create a new instruction after the PHI if the terminator is an 818 // EHPad because there is no valid insertion point. 819 if (Instruction *TI = PN.getParent()->getTerminator()) 820 if (TI->isEHPad()) 821 return nullptr; 822 823 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); 824 825 if (isa<GetElementPtrInst>(FirstInst)) 826 return foldPHIArgGEPIntoPHI(PN); 827 if (isa<LoadInst>(FirstInst)) 828 return foldPHIArgLoadIntoPHI(PN); 829 if (isa<InsertValueInst>(FirstInst)) 830 return foldPHIArgInsertValueInstructionIntoPHI(PN); 831 if (isa<ExtractValueInst>(FirstInst)) 832 return foldPHIArgExtractValueInstructionIntoPHI(PN); 833 834 // Scan the instruction, looking for input operations that can be folded away. 835 // If all input operands to the phi are the same instruction (e.g. a cast from 836 // the same type or "+42") we can pull the operation through the PHI, reducing 837 // code size and simplifying code. 838 Constant *ConstantOp = nullptr; 839 Type *CastSrcTy = nullptr; 840 841 if (isa<CastInst>(FirstInst)) { 842 CastSrcTy = FirstInst->getOperand(0)->getType(); 843 844 // Be careful about transforming integer PHIs. We don't want to pessimize 845 // the code by turning an i32 into an i1293. 846 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) { 847 if (!shouldChangeType(PN.getType(), CastSrcTy)) 848 return nullptr; 849 } 850 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) { 851 // Can fold binop, compare or shift here if the RHS is a constant, 852 // otherwise call FoldPHIArgBinOpIntoPHI. 853 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1)); 854 if (!ConstantOp) 855 return foldPHIArgBinOpIntoPHI(PN); 856 } else { 857 return nullptr; // Cannot fold this operation. 858 } 859 860 // Check to see if all arguments are the same operation. 861 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 862 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i)); 863 if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst)) 864 return nullptr; 865 if (CastSrcTy) { 866 if (I->getOperand(0)->getType() != CastSrcTy) 867 return nullptr; // Cast operation must match. 868 } else if (I->getOperand(1) != ConstantOp) { 869 return nullptr; 870 } 871 } 872 873 // Okay, they are all the same operation. Create a new PHI node of the 874 // correct type, and PHI together all of the LHS's of the instructions. 875 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(), 876 PN.getNumIncomingValues(), 877 PN.getName()+".in"); 878 879 Value *InVal = FirstInst->getOperand(0); 880 NewPN->addIncoming(InVal, PN.getIncomingBlock(0)); 881 882 // Add all operands to the new PHI. 883 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { 884 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0); 885 if (NewInVal != InVal) 886 InVal = nullptr; 887 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i)); 888 } 889 890 Value *PhiVal; 891 if (InVal) { 892 // The new PHI unions all of the same values together. This is really 893 // common, so we handle it intelligently here for compile-time speed. 894 PhiVal = InVal; 895 delete NewPN; 896 } else { 897 InsertNewInstBefore(NewPN, PN); 898 PhiVal = NewPN; 899 } 900 901 // Insert and return the new operation. 902 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) { 903 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal, 904 PN.getType()); 905 PHIArgMergedDebugLoc(NewCI, PN); 906 return NewCI; 907 } 908 909 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) { 910 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp); 911 BinOp->copyIRFlags(PN.getIncomingValue(0)); 912 913 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) 914 BinOp->andIRFlags(PN.getIncomingValue(i)); 915 916 PHIArgMergedDebugLoc(BinOp, PN); 917 return BinOp; 918 } 919 920 CmpInst *CIOp = cast<CmpInst>(FirstInst); 921 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 922 PhiVal, ConstantOp); 923 PHIArgMergedDebugLoc(NewCI, PN); 924 return NewCI; 925 } 926 927 /// Return true if this PHI node is only used by a PHI node cycle that is dead. 928 static bool DeadPHICycle(PHINode *PN, 929 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) { 930 if (PN->use_empty()) return true; 931 if (!PN->hasOneUse()) return false; 932 933 // Remember this node, and if we find the cycle, return. 934 if (!PotentiallyDeadPHIs.insert(PN).second) 935 return true; 936 937 // Don't scan crazily complex things. 938 if (PotentiallyDeadPHIs.size() == 16) 939 return false; 940 941 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back())) 942 return DeadPHICycle(PU, PotentiallyDeadPHIs); 943 944 return false; 945 } 946 947 /// Return true if this phi node is always equal to NonPhiInVal. 948 /// This happens with mutually cyclic phi nodes like: 949 /// z = some value; x = phi (y, z); y = phi (x, z) 950 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 951 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) { 952 // See if we already saw this PHI node. 953 if (!ValueEqualPHIs.insert(PN).second) 954 return true; 955 956 // Don't scan crazily complex things. 957 if (ValueEqualPHIs.size() == 16) 958 return false; 959 960 // Scan the operands to see if they are either phi nodes or are equal to 961 // the value. 962 for (Value *Op : PN->incoming_values()) { 963 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) { 964 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs)) 965 return false; 966 } else if (Op != NonPhiInVal) 967 return false; 968 } 969 970 return true; 971 } 972 973 /// Return an existing non-zero constant if this phi node has one, otherwise 974 /// return constant 1. 975 static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) { 976 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi"); 977 for (Value *V : PN.operands()) 978 if (auto *ConstVA = dyn_cast<ConstantInt>(V)) 979 if (!ConstVA->isZero()) 980 return ConstVA; 981 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1); 982 } 983 984 namespace { 985 struct PHIUsageRecord { 986 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on) 987 unsigned Shift; // The amount shifted. 988 Instruction *Inst; // The trunc instruction. 989 990 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User) 991 : PHIId(pn), Shift(Sh), Inst(User) {} 992 993 bool operator<(const PHIUsageRecord &RHS) const { 994 if (PHIId < RHS.PHIId) return true; 995 if (PHIId > RHS.PHIId) return false; 996 if (Shift < RHS.Shift) return true; 997 if (Shift > RHS.Shift) return false; 998 return Inst->getType()->getPrimitiveSizeInBits() < 999 RHS.Inst->getType()->getPrimitiveSizeInBits(); 1000 } 1001 }; 1002 1003 struct LoweredPHIRecord { 1004 PHINode *PN; // The PHI that was lowered. 1005 unsigned Shift; // The amount shifted. 1006 unsigned Width; // The width extracted. 1007 1008 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty) 1009 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {} 1010 1011 // Ctor form used by DenseMap. 1012 LoweredPHIRecord(PHINode *pn, unsigned Sh) 1013 : PN(pn), Shift(Sh), Width(0) {} 1014 }; 1015 } 1016 1017 namespace llvm { 1018 template<> 1019 struct DenseMapInfo<LoweredPHIRecord> { 1020 static inline LoweredPHIRecord getEmptyKey() { 1021 return LoweredPHIRecord(nullptr, 0); 1022 } 1023 static inline LoweredPHIRecord getTombstoneKey() { 1024 return LoweredPHIRecord(nullptr, 1); 1025 } 1026 static unsigned getHashValue(const LoweredPHIRecord &Val) { 1027 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^ 1028 (Val.Width>>3); 1029 } 1030 static bool isEqual(const LoweredPHIRecord &LHS, 1031 const LoweredPHIRecord &RHS) { 1032 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift && 1033 LHS.Width == RHS.Width; 1034 } 1035 }; 1036 } 1037 1038 1039 /// This is an integer PHI and we know that it has an illegal type: see if it is 1040 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into 1041 /// the various pieces being extracted. This sort of thing is introduced when 1042 /// SROA promotes an aggregate to large integer values. 1043 /// 1044 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an 1045 /// inttoptr. We should produce new PHIs in the right type. 1046 /// 1047 Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) { 1048 // PHIUsers - Keep track of all of the truncated values extracted from a set 1049 // of PHIs, along with their offset. These are the things we want to rewrite. 1050 SmallVector<PHIUsageRecord, 16> PHIUsers; 1051 1052 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI 1053 // nodes which are extracted from. PHIsToSlice is a set we use to avoid 1054 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to 1055 // check the uses of (to ensure they are all extracts). 1056 SmallVector<PHINode*, 8> PHIsToSlice; 1057 SmallPtrSet<PHINode*, 8> PHIsInspected; 1058 1059 PHIsToSlice.push_back(&FirstPhi); 1060 PHIsInspected.insert(&FirstPhi); 1061 1062 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) { 1063 PHINode *PN = PHIsToSlice[PHIId]; 1064 1065 // Scan the input list of the PHI. If any input is an invoke, and if the 1066 // input is defined in the predecessor, then we won't be split the critical 1067 // edge which is required to insert a truncate. Because of this, we have to 1068 // bail out. 1069 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1070 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i)); 1071 if (!II) continue; 1072 if (II->getParent() != PN->getIncomingBlock(i)) 1073 continue; 1074 1075 // If we have a phi, and if it's directly in the predecessor, then we have 1076 // a critical edge where we need to put the truncate. Since we can't 1077 // split the edge in instcombine, we have to bail out. 1078 return nullptr; 1079 } 1080 1081 for (User *U : PN->users()) { 1082 Instruction *UserI = cast<Instruction>(U); 1083 1084 // If the user is a PHI, inspect its uses recursively. 1085 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) { 1086 if (PHIsInspected.insert(UserPN).second) 1087 PHIsToSlice.push_back(UserPN); 1088 continue; 1089 } 1090 1091 // Truncates are always ok. 1092 if (isa<TruncInst>(UserI)) { 1093 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI)); 1094 continue; 1095 } 1096 1097 // Otherwise it must be a lshr which can only be used by one trunc. 1098 if (UserI->getOpcode() != Instruction::LShr || 1099 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) || 1100 !isa<ConstantInt>(UserI->getOperand(1))) 1101 return nullptr; 1102 1103 // Bail on out of range shifts. 1104 unsigned SizeInBits = UserI->getType()->getScalarSizeInBits(); 1105 if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits)) 1106 return nullptr; 1107 1108 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue(); 1109 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back())); 1110 } 1111 } 1112 1113 // If we have no users, they must be all self uses, just nuke the PHI. 1114 if (PHIUsers.empty()) 1115 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType())); 1116 1117 // If this phi node is transformable, create new PHIs for all the pieces 1118 // extracted out of it. First, sort the users by their offset and size. 1119 array_pod_sort(PHIUsers.begin(), PHIUsers.end()); 1120 1121 LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n'; 1122 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) dbgs() 1123 << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';); 1124 1125 // PredValues - This is a temporary used when rewriting PHI nodes. It is 1126 // hoisted out here to avoid construction/destruction thrashing. 1127 DenseMap<BasicBlock*, Value*> PredValues; 1128 1129 // ExtractedVals - Each new PHI we introduce is saved here so we don't 1130 // introduce redundant PHIs. 1131 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals; 1132 1133 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) { 1134 unsigned PHIId = PHIUsers[UserI].PHIId; 1135 PHINode *PN = PHIsToSlice[PHIId]; 1136 unsigned Offset = PHIUsers[UserI].Shift; 1137 Type *Ty = PHIUsers[UserI].Inst->getType(); 1138 1139 PHINode *EltPHI; 1140 1141 // If we've already lowered a user like this, reuse the previously lowered 1142 // value. 1143 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) { 1144 1145 // Otherwise, Create the new PHI node for this user. 1146 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(), 1147 PN->getName()+".off"+Twine(Offset), PN); 1148 assert(EltPHI->getType() != PN->getType() && 1149 "Truncate didn't shrink phi?"); 1150 1151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1152 BasicBlock *Pred = PN->getIncomingBlock(i); 1153 Value *&PredVal = PredValues[Pred]; 1154 1155 // If we already have a value for this predecessor, reuse it. 1156 if (PredVal) { 1157 EltPHI->addIncoming(PredVal, Pred); 1158 continue; 1159 } 1160 1161 // Handle the PHI self-reuse case. 1162 Value *InVal = PN->getIncomingValue(i); 1163 if (InVal == PN) { 1164 PredVal = EltPHI; 1165 EltPHI->addIncoming(PredVal, Pred); 1166 continue; 1167 } 1168 1169 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) { 1170 // If the incoming value was a PHI, and if it was one of the PHIs we 1171 // already rewrote it, just use the lowered value. 1172 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) { 1173 PredVal = Res; 1174 EltPHI->addIncoming(PredVal, Pred); 1175 continue; 1176 } 1177 } 1178 1179 // Otherwise, do an extract in the predecessor. 1180 Builder.SetInsertPoint(Pred->getTerminator()); 1181 Value *Res = InVal; 1182 if (Offset) 1183 Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(), 1184 Offset), "extract"); 1185 Res = Builder.CreateTrunc(Res, Ty, "extract.t"); 1186 PredVal = Res; 1187 EltPHI->addIncoming(Res, Pred); 1188 1189 // If the incoming value was a PHI, and if it was one of the PHIs we are 1190 // rewriting, we will ultimately delete the code we inserted. This 1191 // means we need to revisit that PHI to make sure we extract out the 1192 // needed piece. 1193 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i))) 1194 if (PHIsInspected.count(OldInVal)) { 1195 unsigned RefPHIId = 1196 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin(); 1197 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 1198 cast<Instruction>(Res))); 1199 ++UserE; 1200 } 1201 } 1202 PredValues.clear(); 1203 1204 LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": " 1205 << *EltPHI << '\n'); 1206 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI; 1207 } 1208 1209 // Replace the use of this piece with the PHI node. 1210 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI); 1211 } 1212 1213 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs) 1214 // with undefs. 1215 Value *Undef = UndefValue::get(FirstPhi.getType()); 1216 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) 1217 replaceInstUsesWith(*PHIsToSlice[i], Undef); 1218 return replaceInstUsesWith(FirstPhi, Undef); 1219 } 1220 1221 static Value *SimplifyUsingControlFlow(InstCombiner &Self, PHINode &PN, 1222 const DominatorTree &DT) { 1223 // Simplify the following patterns: 1224 // if (cond) 1225 // / \ 1226 // ... ... 1227 // \ / 1228 // phi [true] [false] 1229 if (!PN.getType()->isIntegerTy(1)) 1230 return nullptr; 1231 1232 if (PN.getNumOperands() != 2) 1233 return nullptr; 1234 1235 // Make sure all inputs are constants. 1236 if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); })) 1237 return nullptr; 1238 1239 BasicBlock *BB = PN.getParent(); 1240 // Do not bother with unreachable instructions. 1241 if (!DT.isReachableFromEntry(BB)) 1242 return nullptr; 1243 1244 // Same inputs. 1245 if (PN.getOperand(0) == PN.getOperand(1)) 1246 return PN.getOperand(0); 1247 1248 BasicBlock *TruePred = nullptr, *FalsePred = nullptr; 1249 for (auto *Pred : predecessors(BB)) { 1250 auto *Input = cast<ConstantInt>(PN.getIncomingValueForBlock(Pred)); 1251 if (Input->isAllOnesValue()) 1252 TruePred = Pred; 1253 else 1254 FalsePred = Pred; 1255 } 1256 assert(TruePred && FalsePred && "Must be!"); 1257 1258 // Check which edge of the dominator dominates the true input. If it is the 1259 // false edge, we should invert the condition. 1260 auto *IDom = DT.getNode(BB)->getIDom()->getBlock(); 1261 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 1262 if (!BI || BI->isUnconditional()) 1263 return nullptr; 1264 1265 // Check that edges outgoing from the idom's terminators dominate respective 1266 // inputs of the Phi. 1267 BasicBlockEdge TrueOutEdge(IDom, BI->getSuccessor(0)); 1268 BasicBlockEdge FalseOutEdge(IDom, BI->getSuccessor(1)); 1269 1270 BasicBlockEdge TrueIncEdge(TruePred, BB); 1271 BasicBlockEdge FalseIncEdge(FalsePred, BB); 1272 1273 auto *Cond = BI->getCondition(); 1274 if (DT.dominates(TrueOutEdge, TrueIncEdge) && 1275 DT.dominates(FalseOutEdge, FalseIncEdge)) 1276 // This Phi is actually equivalent to branching condition of IDom. 1277 return Cond; 1278 else if (DT.dominates(TrueOutEdge, FalseIncEdge) && 1279 DT.dominates(FalseOutEdge, TrueIncEdge)) { 1280 // This Phi is actually opposite to branching condition of IDom. We invert 1281 // the condition that will potentially open up some opportunities for 1282 // sinking. 1283 auto InsertPt = BB->getFirstInsertionPt(); 1284 if (InsertPt != BB->end()) { 1285 Self.Builder.SetInsertPoint(&*InsertPt); 1286 return Self.Builder.CreateNot(Cond); 1287 } 1288 } 1289 1290 return nullptr; 1291 } 1292 1293 // PHINode simplification 1294 // 1295 Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) { 1296 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN))) 1297 return replaceInstUsesWith(PN, V); 1298 1299 if (Instruction *Result = foldPHIArgZextsIntoPHI(PN)) 1300 return Result; 1301 1302 // If all PHI operands are the same operation, pull them through the PHI, 1303 // reducing code size. 1304 if (isa<Instruction>(PN.getIncomingValue(0)) && 1305 isa<Instruction>(PN.getIncomingValue(1)) && 1306 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() == 1307 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() && 1308 PN.getIncomingValue(0)->hasOneUser()) 1309 if (Instruction *Result = foldPHIArgOpIntoPHI(PN)) 1310 return Result; 1311 1312 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if 1313 // this PHI only has a single use (a PHI), and if that PHI only has one use (a 1314 // PHI)... break the cycle. 1315 if (PN.hasOneUse()) { 1316 if (Instruction *Result = foldIntegerTypedPHI(PN)) 1317 return Result; 1318 1319 Instruction *PHIUser = cast<Instruction>(PN.user_back()); 1320 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) { 1321 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs; 1322 PotentiallyDeadPHIs.insert(&PN); 1323 if (DeadPHICycle(PU, PotentiallyDeadPHIs)) 1324 return replaceInstUsesWith(PN, UndefValue::get(PN.getType())); 1325 } 1326 1327 // If this phi has a single use, and if that use just computes a value for 1328 // the next iteration of a loop, delete the phi. This occurs with unused 1329 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this 1330 // common case here is good because the only other things that catch this 1331 // are induction variable analysis (sometimes) and ADCE, which is only run 1332 // late. 1333 if (PHIUser->hasOneUse() && 1334 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) && 1335 PHIUser->user_back() == &PN) { 1336 return replaceInstUsesWith(PN, UndefValue::get(PN.getType())); 1337 } 1338 // When a PHI is used only to be compared with zero, it is safe to replace 1339 // an incoming value proved as known nonzero with any non-zero constant. 1340 // For example, in the code below, the incoming value %v can be replaced 1341 // with any non-zero constant based on the fact that the PHI is only used to 1342 // be compared with zero and %v is a known non-zero value: 1343 // %v = select %cond, 1, 2 1344 // %p = phi [%v, BB] ... 1345 // icmp eq, %p, 0 1346 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser); 1347 // FIXME: To be simple, handle only integer type for now. 1348 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() && 1349 match(CmpInst->getOperand(1), m_Zero())) { 1350 ConstantInt *NonZeroConst = nullptr; 1351 bool MadeChange = false; 1352 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1353 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator(); 1354 Value *VA = PN.getIncomingValue(i); 1355 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) { 1356 if (!NonZeroConst) 1357 NonZeroConst = GetAnyNonZeroConstInt(PN); 1358 1359 if (NonZeroConst != VA) { 1360 replaceOperand(PN, i, NonZeroConst); 1361 MadeChange = true; 1362 } 1363 } 1364 } 1365 if (MadeChange) 1366 return &PN; 1367 } 1368 } 1369 1370 // We sometimes end up with phi cycles that non-obviously end up being the 1371 // same value, for example: 1372 // z = some value; x = phi (y, z); y = phi (x, z) 1373 // where the phi nodes don't necessarily need to be in the same block. Do a 1374 // quick check to see if the PHI node only contains a single non-phi value, if 1375 // so, scan to see if the phi cycle is actually equal to that value. 1376 { 1377 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues(); 1378 // Scan for the first non-phi operand. 1379 while (InValNo != NumIncomingVals && 1380 isa<PHINode>(PN.getIncomingValue(InValNo))) 1381 ++InValNo; 1382 1383 if (InValNo != NumIncomingVals) { 1384 Value *NonPhiInVal = PN.getIncomingValue(InValNo); 1385 1386 // Scan the rest of the operands to see if there are any conflicts, if so 1387 // there is no need to recursively scan other phis. 1388 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) { 1389 Value *OpVal = PN.getIncomingValue(InValNo); 1390 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal)) 1391 break; 1392 } 1393 1394 // If we scanned over all operands, then we have one unique value plus 1395 // phi values. Scan PHI nodes to see if they all merge in each other or 1396 // the value. 1397 if (InValNo == NumIncomingVals) { 1398 SmallPtrSet<PHINode*, 16> ValueEqualPHIs; 1399 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs)) 1400 return replaceInstUsesWith(PN, NonPhiInVal); 1401 } 1402 } 1403 } 1404 1405 // If there are multiple PHIs, sort their operands so that they all list 1406 // the blocks in the same order. This will help identical PHIs be eliminated 1407 // by other passes. Other passes shouldn't depend on this for correctness 1408 // however. 1409 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin()); 1410 if (&PN != FirstPN) 1411 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) { 1412 BasicBlock *BBA = PN.getIncomingBlock(i); 1413 BasicBlock *BBB = FirstPN->getIncomingBlock(i); 1414 if (BBA != BBB) { 1415 Value *VA = PN.getIncomingValue(i); 1416 unsigned j = PN.getBasicBlockIndex(BBB); 1417 Value *VB = PN.getIncomingValue(j); 1418 PN.setIncomingBlock(i, BBB); 1419 PN.setIncomingValue(i, VB); 1420 PN.setIncomingBlock(j, BBA); 1421 PN.setIncomingValue(j, VA); 1422 // NOTE: Instcombine normally would want us to "return &PN" if we 1423 // modified any of the operands of an instruction. However, since we 1424 // aren't adding or removing uses (just rearranging them) we don't do 1425 // this in this case. 1426 } 1427 } 1428 1429 // If this is an integer PHI and we know that it has an illegal type, see if 1430 // it is only used by trunc or trunc(lshr) operations. If so, we split the 1431 // PHI into the various pieces being extracted. This sort of thing is 1432 // introduced when SROA promotes an aggregate to a single large integer type. 1433 if (PN.getType()->isIntegerTy() && 1434 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits())) 1435 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN)) 1436 return Res; 1437 1438 // Ultimately, try to replace this Phi with a dominating condition. 1439 if (auto *V = SimplifyUsingControlFlow(*this, PN, DT)) 1440 return replaceInstUsesWith(PN, V); 1441 1442 return nullptr; 1443 } 1444