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