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