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() || 515 GEP->getSourceElementType() != FirstInst->getSourceElementType() || 516 GEP->getNumOperands() != FirstInst->getNumOperands()) 517 return nullptr; 518 519 AllInBounds &= GEP->isInBounds(); 520 521 // Keep track of whether or not all GEPs are of alloca pointers. 522 if (AllBasePointersAreAllocas && 523 (!isa<AllocaInst>(GEP->getOperand(0)) || 524 !GEP->hasAllConstantIndices())) 525 AllBasePointersAreAllocas = false; 526 527 // Compare the operand lists. 528 for (unsigned Op = 0, E = FirstInst->getNumOperands(); Op != E; ++Op) { 529 if (FirstInst->getOperand(Op) == GEP->getOperand(Op)) 530 continue; 531 532 // Don't merge two GEPs when two operands differ (introducing phi nodes) 533 // if one of the PHIs has a constant for the index. The index may be 534 // substantially cheaper to compute for the constants, so making it a 535 // variable index could pessimize the path. This also handles the case 536 // for struct indices, which must always be constant. 537 if (isa<ConstantInt>(FirstInst->getOperand(Op)) || 538 isa<ConstantInt>(GEP->getOperand(Op))) 539 return nullptr; 540 541 if (FirstInst->getOperand(Op)->getType() != 542 GEP->getOperand(Op)->getType()) 543 return nullptr; 544 545 // If we already needed a PHI for an earlier operand, and another operand 546 // also requires a PHI, we'd be introducing more PHIs than we're 547 // eliminating, which increases register pressure on entry to the PHI's 548 // block. 549 if (NeededPhi) 550 return nullptr; 551 552 FixedOperands[Op] = nullptr; // Needs a PHI. 553 NeededPhi = true; 554 } 555 } 556 557 // If all of the base pointers of the PHI'd GEPs are from allocas, don't 558 // bother doing this transformation. At best, this will just save a bit of 559 // offset calculation, but all the predecessors will have to materialize the 560 // stack address into a register anyway. We'd actually rather *clone* the 561 // load up into the predecessors so that we have a load of a gep of an alloca, 562 // which can usually all be folded into the load. 563 if (AllBasePointersAreAllocas) 564 return nullptr; 565 566 // Otherwise, this is safe to transform. Insert PHI nodes for each operand 567 // that is variable. 568 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size()); 569 570 bool HasAnyPHIs = false; 571 for (unsigned I = 0, E = FixedOperands.size(); I != E; ++I) { 572 if (FixedOperands[I]) 573 continue; // operand doesn't need a phi. 574 Value *FirstOp = FirstInst->getOperand(I); 575 PHINode *NewPN = 576 PHINode::Create(FirstOp->getType(), E, 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 // Add all operands to the new PHIs. 586 if (HasAnyPHIs) { 587 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) { 588 BasicBlock *InBB = std::get<0>(Incoming); 589 Value *InVal = std::get<1>(Incoming); 590 GetElementPtrInst *InGEP = cast<GetElementPtrInst>(InVal); 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 const 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 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) { 686 BasicBlock *InBB = std::get<0>(Incoming); 687 Value *InVal = std::get<1>(Incoming); 688 LoadInst *LI = dyn_cast<LoadInst>(InVal); 689 if (!LI || !LI->hasOneUser() || LI->isAtomic()) 690 return nullptr; 691 692 // Make sure all arguments are the same type of operation. 693 if (LI->isVolatile() != IsVolatile || 694 LI->getPointerAddressSpace() != LoadAddrSpace) 695 return nullptr; 696 697 // We can't sink the load if the loaded value could be modified between 698 // the load and the PHI. 699 if (LI->getParent() != InBB || !isSafeAndProfitableToSinkLoad(LI)) 700 return nullptr; 701 702 LoadAlignment = std::min(LoadAlignment, LI->getAlign()); 703 704 // If the PHI is of volatile loads and the load block has multiple 705 // successors, sinking it would remove a load of the volatile value from 706 // the path through the other successor. 707 if (IsVolatile && LI->getParent()->getTerminator()->getNumSuccessors() != 1) 708 return nullptr; 709 } 710 711 // Okay, they are all the same operation. Create a new PHI node of the 712 // correct type, and PHI together all of the LHS's of the instructions. 713 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(), 714 PN.getNumIncomingValues(), 715 PN.getName()+".in"); 716 717 Value *InVal = FirstLI->getOperand(0); 718 NewPN->addIncoming(InVal, PN.getIncomingBlock(0)); 719 LoadInst *NewLI = 720 new LoadInst(FirstLI->getType(), NewPN, "", IsVolatile, LoadAlignment); 721 722 unsigned KnownIDs[] = { 723 LLVMContext::MD_tbaa, 724 LLVMContext::MD_range, 725 LLVMContext::MD_invariant_load, 726 LLVMContext::MD_alias_scope, 727 LLVMContext::MD_noalias, 728 LLVMContext::MD_nonnull, 729 LLVMContext::MD_align, 730 LLVMContext::MD_dereferenceable, 731 LLVMContext::MD_dereferenceable_or_null, 732 LLVMContext::MD_access_group, 733 }; 734 735 for (unsigned ID : KnownIDs) 736 NewLI->setMetadata(ID, FirstLI->getMetadata(ID)); 737 738 // Add all operands to the new PHI and combine TBAA metadata. 739 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) { 740 BasicBlock *BB = std::get<0>(Incoming); 741 Value *V = std::get<1>(Incoming); 742 LoadInst *LI = cast<LoadInst>(V); 743 combineMetadata(NewLI, LI, KnownIDs, true); 744 Value *NewInVal = LI->getOperand(0); 745 if (NewInVal != InVal) 746 InVal = nullptr; 747 NewPN->addIncoming(NewInVal, BB); 748 } 749 750 if (InVal) { 751 // The new PHI unions all of the same values together. This is really 752 // common, so we handle it intelligently here for compile-time speed. 753 NewLI->setOperand(0, InVal); 754 delete NewPN; 755 } else { 756 InsertNewInstBefore(NewPN, PN); 757 } 758 759 // If this was a volatile load that we are merging, make sure to loop through 760 // and mark all the input loads as non-volatile. If we don't do this, we will 761 // insert a new volatile load and the old ones will not be deletable. 762 if (IsVolatile) 763 for (Value *IncValue : PN.incoming_values()) 764 cast<LoadInst>(IncValue)->setVolatile(false); 765 766 PHIArgMergedDebugLoc(NewLI, PN); 767 return NewLI; 768 } 769 770 /// TODO: This function could handle other cast types, but then it might 771 /// require special-casing a cast from the 'i1' type. See the comment in 772 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types. 773 Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) { 774 // We cannot create a new instruction after the PHI if the terminator is an 775 // EHPad because there is no valid insertion point. 776 if (Instruction *TI = Phi.getParent()->getTerminator()) 777 if (TI->isEHPad()) 778 return nullptr; 779 780 // Early exit for the common case of a phi with two operands. These are 781 // handled elsewhere. See the comment below where we check the count of zexts 782 // and constants for more details. 783 unsigned NumIncomingValues = Phi.getNumIncomingValues(); 784 if (NumIncomingValues < 3) 785 return nullptr; 786 787 // Find the narrower type specified by the first zext. 788 Type *NarrowType = nullptr; 789 for (Value *V : Phi.incoming_values()) { 790 if (auto *Zext = dyn_cast<ZExtInst>(V)) { 791 NarrowType = Zext->getSrcTy(); 792 break; 793 } 794 } 795 if (!NarrowType) 796 return nullptr; 797 798 // Walk the phi operands checking that we only have zexts or constants that 799 // we can shrink for free. Store the new operands for the new phi. 800 SmallVector<Value *, 4> NewIncoming; 801 unsigned NumZexts = 0; 802 unsigned NumConsts = 0; 803 for (Value *V : Phi.incoming_values()) { 804 if (auto *Zext = dyn_cast<ZExtInst>(V)) { 805 // All zexts must be identical and have one user. 806 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser()) 807 return nullptr; 808 NewIncoming.push_back(Zext->getOperand(0)); 809 NumZexts++; 810 } else if (auto *C = dyn_cast<Constant>(V)) { 811 // Make sure that constants can fit in the new type. 812 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType); 813 if (ConstantExpr::getZExt(Trunc, C->getType()) != C) 814 return nullptr; 815 NewIncoming.push_back(Trunc); 816 NumConsts++; 817 } else { 818 // If it's not a cast or a constant, bail out. 819 return nullptr; 820 } 821 } 822 823 // The more common cases of a phi with no constant operands or just one 824 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi() 825 // respectively. foldOpIntoPhi() wants to do the opposite transform that is 826 // performed here. It tries to replicate a cast in the phi operand's basic 827 // block to expose other folding opportunities. Thus, InstCombine will 828 // infinite loop without this check. 829 if (NumConsts == 0 || NumZexts < 2) 830 return nullptr; 831 832 // All incoming values are zexts or constants that are safe to truncate. 833 // Create a new phi node of the narrow type, phi together all of the new 834 // operands, and zext the result back to the original type. 835 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues, 836 Phi.getName() + ".shrunk"); 837 for (unsigned I = 0; I != NumIncomingValues; ++I) 838 NewPhi->addIncoming(NewIncoming[I], Phi.getIncomingBlock(I)); 839 840 InsertNewInstBefore(NewPhi, Phi); 841 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType()); 842 } 843 844 /// If all operands to a PHI node are the same "unary" operator and they all are 845 /// only used by the PHI, PHI together their inputs, and do the operation once, 846 /// to the result of the PHI. 847 Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) { 848 // We cannot create a new instruction after the PHI if the terminator is an 849 // EHPad because there is no valid insertion point. 850 if (Instruction *TI = PN.getParent()->getTerminator()) 851 if (TI->isEHPad()) 852 return nullptr; 853 854 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); 855 856 if (isa<GetElementPtrInst>(FirstInst)) 857 return foldPHIArgGEPIntoPHI(PN); 858 if (isa<LoadInst>(FirstInst)) 859 return foldPHIArgLoadIntoPHI(PN); 860 if (isa<InsertValueInst>(FirstInst)) 861 return foldPHIArgInsertValueInstructionIntoPHI(PN); 862 if (isa<ExtractValueInst>(FirstInst)) 863 return foldPHIArgExtractValueInstructionIntoPHI(PN); 864 865 // Scan the instruction, looking for input operations that can be folded away. 866 // If all input operands to the phi are the same instruction (e.g. a cast from 867 // the same type or "+42") we can pull the operation through the PHI, reducing 868 // code size and simplifying code. 869 Constant *ConstantOp = nullptr; 870 Type *CastSrcTy = nullptr; 871 872 if (isa<CastInst>(FirstInst)) { 873 CastSrcTy = FirstInst->getOperand(0)->getType(); 874 875 // Be careful about transforming integer PHIs. We don't want to pessimize 876 // the code by turning an i32 into an i1293. 877 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) { 878 if (!shouldChangeType(PN.getType(), CastSrcTy)) 879 return nullptr; 880 } 881 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) { 882 // Can fold binop, compare or shift here if the RHS is a constant, 883 // otherwise call FoldPHIArgBinOpIntoPHI. 884 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1)); 885 if (!ConstantOp) 886 return foldPHIArgBinOpIntoPHI(PN); 887 } else { 888 return nullptr; // Cannot fold this operation. 889 } 890 891 // Check to see if all arguments are the same operation. 892 for (Value *V : drop_begin(PN.incoming_values())) { 893 Instruction *I = dyn_cast<Instruction>(V); 894 if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst)) 895 return nullptr; 896 if (CastSrcTy) { 897 if (I->getOperand(0)->getType() != CastSrcTy) 898 return nullptr; // Cast operation must match. 899 } else if (I->getOperand(1) != ConstantOp) { 900 return nullptr; 901 } 902 } 903 904 // Okay, they are all the same operation. Create a new PHI node of the 905 // correct type, and PHI together all of the LHS's of the instructions. 906 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(), 907 PN.getNumIncomingValues(), 908 PN.getName()+".in"); 909 910 Value *InVal = FirstInst->getOperand(0); 911 NewPN->addIncoming(InVal, PN.getIncomingBlock(0)); 912 913 // Add all operands to the new PHI. 914 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) { 915 BasicBlock *BB = std::get<0>(Incoming); 916 Value *V = std::get<1>(Incoming); 917 Value *NewInVal = cast<Instruction>(V)->getOperand(0); 918 if (NewInVal != InVal) 919 InVal = nullptr; 920 NewPN->addIncoming(NewInVal, BB); 921 } 922 923 Value *PhiVal; 924 if (InVal) { 925 // The new PHI unions all of the same values together. This is really 926 // common, so we handle it intelligently here for compile-time speed. 927 PhiVal = InVal; 928 delete NewPN; 929 } else { 930 InsertNewInstBefore(NewPN, PN); 931 PhiVal = NewPN; 932 } 933 934 // Insert and return the new operation. 935 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) { 936 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal, 937 PN.getType()); 938 PHIArgMergedDebugLoc(NewCI, PN); 939 return NewCI; 940 } 941 942 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) { 943 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp); 944 BinOp->copyIRFlags(PN.getIncomingValue(0)); 945 946 for (Value *V : drop_begin(PN.incoming_values())) 947 BinOp->andIRFlags(V); 948 949 PHIArgMergedDebugLoc(BinOp, PN); 950 return BinOp; 951 } 952 953 CmpInst *CIOp = cast<CmpInst>(FirstInst); 954 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 955 PhiVal, ConstantOp); 956 PHIArgMergedDebugLoc(NewCI, PN); 957 return NewCI; 958 } 959 960 /// Return true if this PHI node is only used by a PHI node cycle that is dead. 961 static bool isDeadPHICycle(PHINode *PN, 962 SmallPtrSetImpl<PHINode *> &PotentiallyDeadPHIs) { 963 if (PN->use_empty()) return true; 964 if (!PN->hasOneUse()) return false; 965 966 // Remember this node, and if we find the cycle, return. 967 if (!PotentiallyDeadPHIs.insert(PN).second) 968 return true; 969 970 // Don't scan crazily complex things. 971 if (PotentiallyDeadPHIs.size() == 16) 972 return false; 973 974 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back())) 975 return isDeadPHICycle(PU, PotentiallyDeadPHIs); 976 977 return false; 978 } 979 980 /// Return true if this phi node is always equal to NonPhiInVal. 981 /// This happens with mutually cyclic phi nodes like: 982 /// z = some value; x = phi (y, z); y = phi (x, z) 983 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 984 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) { 985 // See if we already saw this PHI node. 986 if (!ValueEqualPHIs.insert(PN).second) 987 return true; 988 989 // Don't scan crazily complex things. 990 if (ValueEqualPHIs.size() == 16) 991 return false; 992 993 // Scan the operands to see if they are either phi nodes or are equal to 994 // the value. 995 for (Value *Op : PN->incoming_values()) { 996 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) { 997 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs)) 998 return false; 999 } else if (Op != NonPhiInVal) 1000 return false; 1001 } 1002 1003 return true; 1004 } 1005 1006 /// Return an existing non-zero constant if this phi node has one, otherwise 1007 /// return constant 1. 1008 static ConstantInt *getAnyNonZeroConstInt(PHINode &PN) { 1009 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi"); 1010 for (Value *V : PN.operands()) 1011 if (auto *ConstVA = dyn_cast<ConstantInt>(V)) 1012 if (!ConstVA->isZero()) 1013 return ConstVA; 1014 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1); 1015 } 1016 1017 namespace { 1018 struct PHIUsageRecord { 1019 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on) 1020 unsigned Shift; // The amount shifted. 1021 Instruction *Inst; // The trunc instruction. 1022 1023 PHIUsageRecord(unsigned Pn, unsigned Sh, Instruction *User) 1024 : PHIId(Pn), Shift(Sh), Inst(User) {} 1025 1026 bool operator<(const PHIUsageRecord &RHS) const { 1027 if (PHIId < RHS.PHIId) return true; 1028 if (PHIId > RHS.PHIId) return false; 1029 if (Shift < RHS.Shift) return true; 1030 if (Shift > RHS.Shift) return false; 1031 return Inst->getType()->getPrimitiveSizeInBits() < 1032 RHS.Inst->getType()->getPrimitiveSizeInBits(); 1033 } 1034 }; 1035 1036 struct LoweredPHIRecord { 1037 PHINode *PN; // The PHI that was lowered. 1038 unsigned Shift; // The amount shifted. 1039 unsigned Width; // The width extracted. 1040 1041 LoweredPHIRecord(PHINode *Phi, unsigned Sh, Type *Ty) 1042 : PN(Phi), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {} 1043 1044 // Ctor form used by DenseMap. 1045 LoweredPHIRecord(PHINode *Phi, unsigned Sh) : PN(Phi), Shift(Sh), Width(0) {} 1046 }; 1047 } // namespace 1048 1049 namespace llvm { 1050 template<> 1051 struct DenseMapInfo<LoweredPHIRecord> { 1052 static inline LoweredPHIRecord getEmptyKey() { 1053 return LoweredPHIRecord(nullptr, 0); 1054 } 1055 static inline LoweredPHIRecord getTombstoneKey() { 1056 return LoweredPHIRecord(nullptr, 1); 1057 } 1058 static unsigned getHashValue(const LoweredPHIRecord &Val) { 1059 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^ 1060 (Val.Width>>3); 1061 } 1062 static bool isEqual(const LoweredPHIRecord &LHS, 1063 const LoweredPHIRecord &RHS) { 1064 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift && 1065 LHS.Width == RHS.Width; 1066 } 1067 }; 1068 } // namespace llvm 1069 1070 1071 /// This is an integer PHI and we know that it has an illegal type: see if it is 1072 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into 1073 /// the various pieces being extracted. This sort of thing is introduced when 1074 /// SROA promotes an aggregate to large integer values. 1075 /// 1076 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an 1077 /// inttoptr. We should produce new PHIs in the right type. 1078 /// 1079 Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) { 1080 // PHIUsers - Keep track of all of the truncated values extracted from a set 1081 // of PHIs, along with their offset. These are the things we want to rewrite. 1082 SmallVector<PHIUsageRecord, 16> PHIUsers; 1083 1084 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI 1085 // nodes which are extracted from. PHIsToSlice is a set we use to avoid 1086 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to 1087 // check the uses of (to ensure they are all extracts). 1088 SmallVector<PHINode*, 8> PHIsToSlice; 1089 SmallPtrSet<PHINode*, 8> PHIsInspected; 1090 1091 PHIsToSlice.push_back(&FirstPhi); 1092 PHIsInspected.insert(&FirstPhi); 1093 1094 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) { 1095 PHINode *PN = PHIsToSlice[PHIId]; 1096 1097 // Scan the input list of the PHI. If any input is an invoke, and if the 1098 // input is defined in the predecessor, then we won't be split the critical 1099 // edge which is required to insert a truncate. Because of this, we have to 1100 // bail out. 1101 for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) { 1102 BasicBlock *BB = std::get<0>(Incoming); 1103 Value *V = std::get<1>(Incoming); 1104 InvokeInst *II = dyn_cast<InvokeInst>(V); 1105 if (!II) 1106 continue; 1107 if (II->getParent() != BB) 1108 continue; 1109 1110 // If we have a phi, and if it's directly in the predecessor, then we have 1111 // a critical edge where we need to put the truncate. Since we can't 1112 // split the edge in instcombine, we have to bail out. 1113 return nullptr; 1114 } 1115 1116 for (User *U : PN->users()) { 1117 Instruction *UserI = cast<Instruction>(U); 1118 1119 // If the user is a PHI, inspect its uses recursively. 1120 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) { 1121 if (PHIsInspected.insert(UserPN).second) 1122 PHIsToSlice.push_back(UserPN); 1123 continue; 1124 } 1125 1126 // Truncates are always ok. 1127 if (isa<TruncInst>(UserI)) { 1128 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI)); 1129 continue; 1130 } 1131 1132 // Otherwise it must be a lshr which can only be used by one trunc. 1133 if (UserI->getOpcode() != Instruction::LShr || 1134 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) || 1135 !isa<ConstantInt>(UserI->getOperand(1))) 1136 return nullptr; 1137 1138 // Bail on out of range shifts. 1139 unsigned SizeInBits = UserI->getType()->getScalarSizeInBits(); 1140 if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits)) 1141 return nullptr; 1142 1143 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue(); 1144 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back())); 1145 } 1146 } 1147 1148 // If we have no users, they must be all self uses, just nuke the PHI. 1149 if (PHIUsers.empty()) 1150 return replaceInstUsesWith(FirstPhi, PoisonValue::get(FirstPhi.getType())); 1151 1152 // If this phi node is transformable, create new PHIs for all the pieces 1153 // extracted out of it. First, sort the users by their offset and size. 1154 array_pod_sort(PHIUsers.begin(), PHIUsers.end()); 1155 1156 LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n'; 1157 for (unsigned I = 1; I != PHIsToSlice.size(); ++I) dbgs() 1158 << "AND USER PHI #" << I << ": " << *PHIsToSlice[I] << '\n'); 1159 1160 // PredValues - This is a temporary used when rewriting PHI nodes. It is 1161 // hoisted out here to avoid construction/destruction thrashing. 1162 DenseMap<BasicBlock*, Value*> PredValues; 1163 1164 // ExtractedVals - Each new PHI we introduce is saved here so we don't 1165 // introduce redundant PHIs. 1166 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals; 1167 1168 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) { 1169 unsigned PHIId = PHIUsers[UserI].PHIId; 1170 PHINode *PN = PHIsToSlice[PHIId]; 1171 unsigned Offset = PHIUsers[UserI].Shift; 1172 Type *Ty = PHIUsers[UserI].Inst->getType(); 1173 1174 PHINode *EltPHI; 1175 1176 // If we've already lowered a user like this, reuse the previously lowered 1177 // value. 1178 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) { 1179 1180 // Otherwise, Create the new PHI node for this user. 1181 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(), 1182 PN->getName()+".off"+Twine(Offset), PN); 1183 assert(EltPHI->getType() != PN->getType() && 1184 "Truncate didn't shrink phi?"); 1185 1186 for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) { 1187 BasicBlock *Pred = std::get<0>(Incoming); 1188 Value *InVal = std::get<1>(Incoming); 1189 Value *&PredVal = PredValues[Pred]; 1190 1191 // If we already have a value for this predecessor, reuse it. 1192 if (PredVal) { 1193 EltPHI->addIncoming(PredVal, Pred); 1194 continue; 1195 } 1196 1197 // Handle the PHI self-reuse case. 1198 if (InVal == PN) { 1199 PredVal = EltPHI; 1200 EltPHI->addIncoming(PredVal, Pred); 1201 continue; 1202 } 1203 1204 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) { 1205 // If the incoming value was a PHI, and if it was one of the PHIs we 1206 // already rewrote it, just use the lowered value. 1207 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) { 1208 PredVal = Res; 1209 EltPHI->addIncoming(PredVal, Pred); 1210 continue; 1211 } 1212 } 1213 1214 // Otherwise, do an extract in the predecessor. 1215 Builder.SetInsertPoint(Pred->getTerminator()); 1216 Value *Res = InVal; 1217 if (Offset) 1218 Res = Builder.CreateLShr( 1219 Res, ConstantInt::get(InVal->getType(), Offset), "extract"); 1220 Res = Builder.CreateTrunc(Res, Ty, "extract.t"); 1221 PredVal = Res; 1222 EltPHI->addIncoming(Res, Pred); 1223 1224 // If the incoming value was a PHI, and if it was one of the PHIs we are 1225 // rewriting, we will ultimately delete the code we inserted. This 1226 // means we need to revisit that PHI to make sure we extract out the 1227 // needed piece. 1228 if (PHINode *OldInVal = dyn_cast<PHINode>(InVal)) 1229 if (PHIsInspected.count(OldInVal)) { 1230 unsigned RefPHIId = 1231 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin(); 1232 PHIUsers.push_back( 1233 PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Res))); 1234 ++UserE; 1235 } 1236 } 1237 PredValues.clear(); 1238 1239 LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": " 1240 << *EltPHI << '\n'); 1241 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI; 1242 } 1243 1244 // Replace the use of this piece with the PHI node. 1245 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI); 1246 } 1247 1248 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs) 1249 // with poison. 1250 Value *Poison = PoisonValue::get(FirstPhi.getType()); 1251 for (PHINode *PHI : drop_begin(PHIsToSlice)) 1252 replaceInstUsesWith(*PHI, Poison); 1253 return replaceInstUsesWith(FirstPhi, Poison); 1254 } 1255 1256 static Value *simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN, 1257 const DominatorTree &DT) { 1258 // Simplify the following patterns: 1259 // if (cond) 1260 // / \ 1261 // ... ... 1262 // \ / 1263 // phi [true] [false] 1264 if (!PN.getType()->isIntegerTy(1)) 1265 return nullptr; 1266 1267 if (PN.getNumOperands() != 2) 1268 return nullptr; 1269 1270 // Make sure all inputs are constants. 1271 if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); })) 1272 return nullptr; 1273 1274 BasicBlock *BB = PN.getParent(); 1275 // Do not bother with unreachable instructions. 1276 if (!DT.isReachableFromEntry(BB)) 1277 return nullptr; 1278 1279 // Same inputs. 1280 if (PN.getOperand(0) == PN.getOperand(1)) 1281 return PN.getOperand(0); 1282 1283 BasicBlock *TruePred = nullptr, *FalsePred = nullptr; 1284 for (auto *Pred : predecessors(BB)) { 1285 auto *Input = cast<ConstantInt>(PN.getIncomingValueForBlock(Pred)); 1286 if (Input->isAllOnesValue()) 1287 TruePred = Pred; 1288 else 1289 FalsePred = Pred; 1290 } 1291 assert(TruePred && FalsePred && "Must be!"); 1292 1293 // Check which edge of the dominator dominates the true input. If it is the 1294 // false edge, we should invert the condition. 1295 auto *IDom = DT.getNode(BB)->getIDom()->getBlock(); 1296 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 1297 if (!BI || BI->isUnconditional()) 1298 return nullptr; 1299 1300 // Check that edges outgoing from the idom's terminators dominate respective 1301 // inputs of the Phi. 1302 BasicBlockEdge TrueOutEdge(IDom, BI->getSuccessor(0)); 1303 BasicBlockEdge FalseOutEdge(IDom, BI->getSuccessor(1)); 1304 1305 BasicBlockEdge TrueIncEdge(TruePred, BB); 1306 BasicBlockEdge FalseIncEdge(FalsePred, BB); 1307 1308 auto *Cond = BI->getCondition(); 1309 if (DT.dominates(TrueOutEdge, TrueIncEdge) && 1310 DT.dominates(FalseOutEdge, FalseIncEdge)) 1311 // This Phi is actually equivalent to branching condition of IDom. 1312 return Cond; 1313 if (DT.dominates(TrueOutEdge, FalseIncEdge) && 1314 DT.dominates(FalseOutEdge, TrueIncEdge)) { 1315 // This Phi is actually opposite to branching condition of IDom. We invert 1316 // the condition that will potentially open up some opportunities for 1317 // sinking. 1318 auto InsertPt = BB->getFirstInsertionPt(); 1319 if (InsertPt != BB->end()) { 1320 Self.Builder.SetInsertPoint(&*InsertPt); 1321 return Self.Builder.CreateNot(Cond); 1322 } 1323 } 1324 1325 return nullptr; 1326 } 1327 1328 // PHINode simplification 1329 // 1330 Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) { 1331 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN))) 1332 return replaceInstUsesWith(PN, V); 1333 1334 if (Instruction *Result = foldPHIArgZextsIntoPHI(PN)) 1335 return Result; 1336 1337 if (Instruction *Result = foldPHIArgIntToPtrToPHI(PN)) 1338 return Result; 1339 1340 // If all PHI operands are the same operation, pull them through the PHI, 1341 // reducing code size. 1342 if (isa<Instruction>(PN.getIncomingValue(0)) && 1343 isa<Instruction>(PN.getIncomingValue(1)) && 1344 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() == 1345 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() && 1346 PN.getIncomingValue(0)->hasOneUser()) 1347 if (Instruction *Result = foldPHIArgOpIntoPHI(PN)) 1348 return Result; 1349 1350 // If the incoming values are pointer casts of the same original value, 1351 // replace the phi with a single cast iff we can insert a non-PHI instruction. 1352 if (PN.getType()->isPointerTy() && 1353 PN.getParent()->getFirstInsertionPt() != PN.getParent()->end()) { 1354 Value *IV0 = PN.getIncomingValue(0); 1355 Value *IV0Stripped = IV0->stripPointerCasts(); 1356 // Set to keep track of values known to be equal to IV0Stripped after 1357 // stripping pointer casts. 1358 SmallPtrSet<Value *, 4> CheckedIVs; 1359 CheckedIVs.insert(IV0); 1360 if (IV0 != IV0Stripped && 1361 all_of(PN.incoming_values(), [&CheckedIVs, IV0Stripped](Value *IV) { 1362 return !CheckedIVs.insert(IV).second || 1363 IV0Stripped == IV->stripPointerCasts(); 1364 })) { 1365 return CastInst::CreatePointerCast(IV0Stripped, PN.getType()); 1366 } 1367 } 1368 1369 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if 1370 // this PHI only has a single use (a PHI), and if that PHI only has one use (a 1371 // PHI)... break the cycle. 1372 if (PN.hasOneUse()) { 1373 if (Instruction *Result = foldIntegerTypedPHI(PN)) 1374 return Result; 1375 1376 Instruction *PHIUser = cast<Instruction>(PN.user_back()); 1377 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) { 1378 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs; 1379 PotentiallyDeadPHIs.insert(&PN); 1380 if (isDeadPHICycle(PU, PotentiallyDeadPHIs)) 1381 return replaceInstUsesWith(PN, PoisonValue::get(PN.getType())); 1382 } 1383 1384 // If this phi has a single use, and if that use just computes a value for 1385 // the next iteration of a loop, delete the phi. This occurs with unused 1386 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this 1387 // common case here is good because the only other things that catch this 1388 // are induction variable analysis (sometimes) and ADCE, which is only run 1389 // late. 1390 if (PHIUser->hasOneUse() && 1391 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) && 1392 PHIUser->user_back() == &PN) { 1393 return replaceInstUsesWith(PN, PoisonValue::get(PN.getType())); 1394 } 1395 // When a PHI is used only to be compared with zero, it is safe to replace 1396 // an incoming value proved as known nonzero with any non-zero constant. 1397 // For example, in the code below, the incoming value %v can be replaced 1398 // with any non-zero constant based on the fact that the PHI is only used to 1399 // be compared with zero and %v is a known non-zero value: 1400 // %v = select %cond, 1, 2 1401 // %p = phi [%v, BB] ... 1402 // icmp eq, %p, 0 1403 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser); 1404 // FIXME: To be simple, handle only integer type for now. 1405 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() && 1406 match(CmpInst->getOperand(1), m_Zero())) { 1407 ConstantInt *NonZeroConst = nullptr; 1408 bool MadeChange = false; 1409 for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) { 1410 Instruction *CtxI = PN.getIncomingBlock(I)->getTerminator(); 1411 Value *VA = PN.getIncomingValue(I); 1412 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) { 1413 if (!NonZeroConst) 1414 NonZeroConst = getAnyNonZeroConstInt(PN); 1415 1416 if (NonZeroConst != VA) { 1417 replaceOperand(PN, I, NonZeroConst); 1418 MadeChange = true; 1419 } 1420 } 1421 } 1422 if (MadeChange) 1423 return &PN; 1424 } 1425 } 1426 1427 // We sometimes end up with phi cycles that non-obviously end up being the 1428 // same value, for example: 1429 // z = some value; x = phi (y, z); y = phi (x, z) 1430 // where the phi nodes don't necessarily need to be in the same block. Do a 1431 // quick check to see if the PHI node only contains a single non-phi value, if 1432 // so, scan to see if the phi cycle is actually equal to that value. 1433 { 1434 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues(); 1435 // Scan for the first non-phi operand. 1436 while (InValNo != NumIncomingVals && 1437 isa<PHINode>(PN.getIncomingValue(InValNo))) 1438 ++InValNo; 1439 1440 if (InValNo != NumIncomingVals) { 1441 Value *NonPhiInVal = PN.getIncomingValue(InValNo); 1442 1443 // Scan the rest of the operands to see if there are any conflicts, if so 1444 // there is no need to recursively scan other phis. 1445 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) { 1446 Value *OpVal = PN.getIncomingValue(InValNo); 1447 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal)) 1448 break; 1449 } 1450 1451 // If we scanned over all operands, then we have one unique value plus 1452 // phi values. Scan PHI nodes to see if they all merge in each other or 1453 // the value. 1454 if (InValNo == NumIncomingVals) { 1455 SmallPtrSet<PHINode*, 16> ValueEqualPHIs; 1456 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs)) 1457 return replaceInstUsesWith(PN, NonPhiInVal); 1458 } 1459 } 1460 } 1461 1462 // If there are multiple PHIs, sort their operands so that they all list 1463 // the blocks in the same order. This will help identical PHIs be eliminated 1464 // by other passes. Other passes shouldn't depend on this for correctness 1465 // however. 1466 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin()); 1467 if (&PN != FirstPN) 1468 for (unsigned I = 0, E = FirstPN->getNumIncomingValues(); I != E; ++I) { 1469 BasicBlock *BBA = PN.getIncomingBlock(I); 1470 BasicBlock *BBB = FirstPN->getIncomingBlock(I); 1471 if (BBA != BBB) { 1472 Value *VA = PN.getIncomingValue(I); 1473 unsigned J = PN.getBasicBlockIndex(BBB); 1474 Value *VB = PN.getIncomingValue(J); 1475 PN.setIncomingBlock(I, BBB); 1476 PN.setIncomingValue(I, VB); 1477 PN.setIncomingBlock(J, BBA); 1478 PN.setIncomingValue(J, VA); 1479 // NOTE: Instcombine normally would want us to "return &PN" if we 1480 // modified any of the operands of an instruction. However, since we 1481 // aren't adding or removing uses (just rearranging them) we don't do 1482 // this in this case. 1483 } 1484 } 1485 1486 // Is there an identical PHI node in this basic block? 1487 for (PHINode &IdenticalPN : PN.getParent()->phis()) { 1488 // Ignore the PHI node itself. 1489 if (&IdenticalPN == &PN) 1490 continue; 1491 // Note that even though we've just canonicalized this PHI, due to the 1492 // worklist visitation order, there are no guarantess that *every* PHI 1493 // has been canonicalized, so we can't just compare operands ranges. 1494 if (!PN.isIdenticalToWhenDefined(&IdenticalPN)) 1495 continue; 1496 // Just use that PHI instead then. 1497 ++NumPHICSEs; 1498 return replaceInstUsesWith(PN, &IdenticalPN); 1499 } 1500 1501 // If this is an integer PHI and we know that it has an illegal type, see if 1502 // it is only used by trunc or trunc(lshr) operations. If so, we split the 1503 // PHI into the various pieces being extracted. This sort of thing is 1504 // introduced when SROA promotes an aggregate to a single large integer type. 1505 if (PN.getType()->isIntegerTy() && 1506 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits())) 1507 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN)) 1508 return Res; 1509 1510 // Ultimately, try to replace this Phi with a dominating condition. 1511 if (auto *V = simplifyUsingControlFlow(*this, PN, DT)) 1512 return replaceInstUsesWith(PN, V); 1513 1514 return nullptr; 1515 } 1516