Coverage Report

Created: 2024-01-17 10:31

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