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