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