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