blob: a71ebdcd346a4e3888b1b59239dcd06673b522d1 [file] [log] [blame]
Chris Lattnerde1fede2010-01-05 05:31:55 +00001//===- InstCombinePHI.cpp -------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitPHINode function.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
Duncan Sands4581ddc2010-11-14 13:30:18 +000017#include "llvm/Analysis/InstructionSimplify.h"
David Blaikie31b98d22018-06-04 21:23:21 +000018#include "llvm/Transforms/Utils/Local.h"
Jun Bum Lim339e9722016-02-11 15:50:07 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/PatternMatch.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000021using namespace llvm;
Jun Bum Lim339e9722016-02-11 15:50:07 +000022using namespace llvm::PatternMatch;
Chris Lattnerde1fede2010-01-05 05:31:55 +000023
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Xinliang David Libc471c32018-05-17 19:24:03 +000026static cl::opt<unsigned>
27MaxNumPhis("instcombine-max-num-phis", cl::init(512),
28 cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
29
Robert Lougher2428a402016-12-14 17:49:19 +000030/// The PHI arguments will be folded into a single operation with a PHI node
31/// as input. The debug location of the single operation will be the merged
32/// locations of the original PHI node arguments.
Dehao Chenf4646272017-10-02 18:13:14 +000033void InstCombiner::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
Robert Lougher2428a402016-12-14 17:49:19 +000034 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Dehao Chenf4646272017-10-02 18:13:14 +000035 Inst->setDebugLoc(FirstInst->getDebugLoc());
36 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
37 // will be inefficient.
38 assert(!isa<CallInst>(Inst));
Robert Lougher2428a402016-12-14 17:49:19 +000039
40 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
41 auto *I = cast<Instruction>(PN.getIncomingValue(i));
Dehao Chenf4646272017-10-02 18:13:14 +000042 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
Robert Lougher2428a402016-12-14 17:49:19 +000043 }
Robert Lougher2428a402016-12-14 17:49:19 +000044}
45
Xinliang David Li4cdc9da2017-10-10 05:07:54 +000046// Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
47// If there is an existing pointer typed PHI that produces the same value as PN,
48// replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
49// PHI node:
50//
51// Case-1:
52// bb1:
53// int_init = PtrToInt(ptr_init)
54// br label %bb2
55// bb2:
56// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
57// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
58// ptr_val2 = IntToPtr(int_val)
59// ...
60// use(ptr_val2)
61// ptr_val_inc = ...
62// inc_val_inc = PtrToInt(ptr_val_inc)
63//
64// ==>
65// bb1:
66// br label %bb2
67// bb2:
68// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
69// ...
70// use(ptr_val)
71// ptr_val_inc = ...
72//
73// Case-2:
74// bb1:
75// int_ptr = BitCast(ptr_ptr)
76// int_init = Load(int_ptr)
77// br label %bb2
78// bb2:
79// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
80// ptr_val2 = IntToPtr(int_val)
81// ...
82// use(ptr_val2)
83// ptr_val_inc = ...
84// inc_val_inc = PtrToInt(ptr_val_inc)
85// ==>
86// bb1:
87// ptr_init = Load(ptr_ptr)
88// br label %bb2
89// bb2:
90// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
91// ...
92// use(ptr_val)
93// ptr_val_inc = ...
94// ...
95//
96Instruction *InstCombiner::FoldIntegerTypedPHI(PHINode &PN) {
97 if (!PN.getType()->isIntegerTy())
98 return nullptr;
99 if (!PN.hasOneUse())
100 return nullptr;
101
102 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
103 if (!IntToPtr)
104 return nullptr;
105
106 // Check if the pointer is actually used as pointer:
107 auto HasPointerUse = [](Instruction *IIP) {
108 for (User *U : IIP->users()) {
109 Value *Ptr = nullptr;
110 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
111 Ptr = LoadI->getPointerOperand();
112 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
113 Ptr = SI->getPointerOperand();
114 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
115 Ptr = GI->getPointerOperand();
116 }
117
118 if (Ptr && Ptr == IIP)
119 return true;
120 }
121 return false;
122 };
123
124 if (!HasPointerUse(IntToPtr))
125 return nullptr;
126
127 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
128 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
129 return nullptr;
130
131 SmallVector<Value *, 4> AvailablePtrVals;
132 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
133 Value *Arg = PN.getIncomingValue(i);
134
135 // First look backward:
136 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
137 AvailablePtrVals.emplace_back(PI->getOperand(0));
138 continue;
139 }
140
141 // Next look forward:
142 Value *ArgIntToPtr = nullptr;
143 for (User *U : Arg->users()) {
144 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
145 (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) ||
146 cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) {
147 ArgIntToPtr = U;
148 break;
149 }
150 }
151
152 if (ArgIntToPtr) {
153 AvailablePtrVals.emplace_back(ArgIntToPtr);
154 continue;
155 }
156
157 // If Arg is defined by a PHI, allow it. This will also create
158 // more opportunities iteratively.
159 if (isa<PHINode>(Arg)) {
160 AvailablePtrVals.emplace_back(Arg);
161 continue;
162 }
163
164 // For a single use integer load:
165 auto *LoadI = dyn_cast<LoadInst>(Arg);
166 if (!LoadI)
167 return nullptr;
168
169 if (!LoadI->hasOneUse())
170 return nullptr;
171
172 // Push the integer typed Load instruction into the available
173 // value set, and fix it up later when the pointer typed PHI
174 // is synthesized.
175 AvailablePtrVals.emplace_back(LoadI);
176 }
177
178 // Now search for a matching PHI
179 auto *BB = PN.getParent();
180 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
181 "Not enough available ptr typed incoming values");
182 PHINode *MatchingPtrPHI = nullptr;
Xinliang David Libc471c32018-05-17 19:24:03 +0000183 unsigned NumPhis = 0;
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000184 for (auto II = BB->begin(), EI = BasicBlock::iterator(BB->getFirstNonPHI());
Xinliang David Libc471c32018-05-17 19:24:03 +0000185 II != EI; II++, NumPhis++) {
186 // FIXME: consider handling this in AggressiveInstCombine
187 if (NumPhis > MaxNumPhis)
188 return nullptr;
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000189 PHINode *PtrPHI = dyn_cast<PHINode>(II);
190 if (!PtrPHI || PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType())
191 continue;
192 MatchingPtrPHI = PtrPHI;
193 for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) {
194 if (AvailablePtrVals[i] !=
195 PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) {
196 MatchingPtrPHI = nullptr;
197 break;
198 }
199 }
200
201 if (MatchingPtrPHI)
202 break;
203 }
204
205 if (MatchingPtrPHI) {
206 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
207 "Phi's Type does not match with IntToPtr");
208 // The PtrToCast + IntToPtr will be simplified later
209 return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
210 IntToPtr->getOperand(0)->getType());
211 }
212
213 // If it requires a conversion for every PHI operand, do not do it.
Fangrui Song2e83b2e2018-10-19 06:12:02 +0000214 if (all_of(AvailablePtrVals, [&](Value *V) {
215 return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
216 }))
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000217 return nullptr;
218
219 // If any of the operand that requires casting is a terminator
220 // instruction, do not do it.
Fangrui Song2e83b2e2018-10-19 06:12:02 +0000221 if (any_of(AvailablePtrVals, [&](Value *V) {
222 if (V->getType() == IntToPtr->getType())
223 return false;
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000224
Fangrui Song2e83b2e2018-10-19 06:12:02 +0000225 auto *Inst = dyn_cast<Instruction>(V);
226 return Inst && Inst->isTerminator();
227 }))
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000228 return nullptr;
229
230 PHINode *NewPtrPHI = PHINode::Create(
231 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
232
233 InsertNewInstBefore(NewPtrPHI, PN);
234 SmallDenseMap<Value *, Instruction *> Casts;
235 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
236 auto *IncomingBB = PN.getIncomingBlock(i);
237 auto *IncomingVal = AvailablePtrVals[i];
238
239 if (IncomingVal->getType() == IntToPtr->getType()) {
240 NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
241 continue;
242 }
243
244#ifndef NDEBUG
245 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
246 assert((isa<PHINode>(IncomingVal) ||
247 IncomingVal->getType()->isPointerTy() ||
248 (LoadI && LoadI->hasOneUse())) &&
249 "Can not replace LoadInst with multiple uses");
250#endif
251 // Need to insert a BitCast.
252 // For an integer Load instruction with a single use, the load + IntToPtr
253 // cast will be simplified into a pointer load:
254 // %v = load i64, i64* %a.ip, align 8
255 // %v.cast = inttoptr i64 %v to float **
256 // ==>
257 // %v.ptrp = bitcast i64 * %a.ip to float **
258 // %v.cast = load float *, float ** %v.ptrp, align 8
259 Instruction *&CI = Casts[IncomingVal];
260 if (!CI) {
261 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
262 IncomingVal->getName() + ".ptr");
263 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
264 BasicBlock::iterator InsertPos(IncomingI);
265 InsertPos++;
266 if (isa<PHINode>(IncomingI))
267 InsertPos = IncomingI->getParent()->getFirstInsertionPt();
268 InsertNewInstBefore(CI, *InsertPos);
269 } else {
270 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
271 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
272 }
273 }
274 NewPtrPHI->addIncoming(CI, IncomingBB);
275 }
276
277 // The PtrToCast + IntToPtr will be simplified later
278 return CastInst::CreateBitOrPointerCast(NewPtrPHI,
279 IntToPtr->getOperand(0)->getType());
280}
281
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000282/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
283/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000284Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
285 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
286 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
287 unsigned Opc = FirstInst->getOpcode();
288 Value *LHSVal = FirstInst->getOperand(0);
289 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000290
Chris Lattner229907c2011-07-18 04:54:35 +0000291 Type *LHSType = LHSVal->getType();
292 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000293
Chris Lattnerde1fede2010-01-05 05:31:55 +0000294 // Scan to see if all operands are the same opcode, and all have one use.
295 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
296 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
297 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
298 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +0000299 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000300 I->getOperand(0)->getType() != LHSType ||
301 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +0000302 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000303
304 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +0000305 if (CmpInst *CI = dyn_cast<CmpInst>(I))
306 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +0000307 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000308
Chris Lattnerde1fede2010-01-05 05:31:55 +0000309 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +0000310 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
311 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000312 }
313
314 // If both LHS and RHS would need a PHI, don't do this transformation,
315 // because it would increase the number of PHIs entering the block,
316 // which leads to higher register pressure. This is especially
317 // bad when the PHIs are in the header of a loop.
318 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000319 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000320
Chris Lattnerde1fede2010-01-05 05:31:55 +0000321 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000322
Chris Lattnerde1fede2010-01-05 05:31:55 +0000323 Value *InLHS = FirstInst->getOperand(0);
324 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +0000325 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
326 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000327 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000328 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000329 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
330 InsertNewInstBefore(NewLHS, PN);
331 LHSVal = NewLHS;
332 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000333
Craig Topperf40110f2014-04-25 05:29:35 +0000334 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000335 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000336 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000337 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
338 InsertNewInstBefore(NewRHS, PN);
339 RHSVal = NewRHS;
340 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000341
Chris Lattnerde1fede2010-01-05 05:31:55 +0000342 // Add all operands to the new PHIs.
343 if (NewLHS || NewRHS) {
344 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
345 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
346 if (NewLHS) {
347 Value *NewInLHS = InInst->getOperand(0);
348 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
349 }
350 if (NewRHS) {
351 Value *NewInRHS = InInst->getOperand(1);
352 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
353 }
354 }
355 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356
Eli Friedman35211c62011-05-27 00:19:40 +0000357 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
358 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
359 LHSVal, RHSVal);
Dehao Chenf4646272017-10-02 18:13:14 +0000360 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000361 return NewCI;
362 }
363
Chris Lattnera8fed472011-02-17 23:01:49 +0000364 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
365 BinaryOperator *NewBinOp =
366 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Silviu Barangae985c762016-04-22 11:21:36 +0000367
368 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
369
370 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
371 NewBinOp->andIRFlags(PN.getIncomingValue(i));
372
Dehao Chenf4646272017-10-02 18:13:14 +0000373 PHIArgMergedDebugLoc(NewBinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000374 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000375}
376
377Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
378 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000379
380 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000381 FirstInst->op_end());
382 // This is true if all GEP bases are allocas and if all indices into them are
383 // constants.
384 bool AllBasePointersAreAllocas = true;
385
386 // We don't want to replace this phi if the replacement would require
387 // more than one phi, which leads to higher register pressure. This is
388 // especially bad when the PHIs are in the header of a loop.
389 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000390
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000391 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000392
Chris Lattnerde1fede2010-01-05 05:31:55 +0000393 // Scan to see if all operands are the same opcode, and all have one use.
394 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
395 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
396 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
397 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000398 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000399
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000400 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000401
Chris Lattnerde1fede2010-01-05 05:31:55 +0000402 // Keep track of whether or not all GEPs are of alloca pointers.
403 if (AllBasePointersAreAllocas &&
404 (!isa<AllocaInst>(GEP->getOperand(0)) ||
405 !GEP->hasAllConstantIndices()))
406 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000407
Chris Lattnerde1fede2010-01-05 05:31:55 +0000408 // Compare the operand lists.
409 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
410 if (FirstInst->getOperand(op) == GEP->getOperand(op))
411 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000412
Chris Lattnerde1fede2010-01-05 05:31:55 +0000413 // Don't merge two GEPs when two operands differ (introducing phi nodes)
414 // if one of the PHIs has a constant for the index. The index may be
415 // substantially cheaper to compute for the constants, so making it a
416 // variable index could pessimize the path. This also handles the case
417 // for struct indices, which must always be constant.
418 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
419 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000420 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000421
Chris Lattnerde1fede2010-01-05 05:31:55 +0000422 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000423 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000424
425 // If we already needed a PHI for an earlier operand, and another operand
426 // also requires a PHI, we'd be introducing more PHIs than we're
427 // eliminating, which increases register pressure on entry to the PHI's
428 // block.
429 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000430 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000431
Craig Topperf40110f2014-04-25 05:29:35 +0000432 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000433 NeededPhi = true;
434 }
435 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000436
Chris Lattnerde1fede2010-01-05 05:31:55 +0000437 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
438 // bother doing this transformation. At best, this will just save a bit of
439 // offset calculation, but all the predecessors will have to materialize the
440 // stack address into a register anyway. We'd actually rather *clone* the
441 // load up into the predecessors so that we have a load of a gep of an alloca,
442 // which can usually all be folded into the load.
443 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000444 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000445
Chris Lattnerde1fede2010-01-05 05:31:55 +0000446 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
447 // that is variable.
448 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000449
Chris Lattnerde1fede2010-01-05 05:31:55 +0000450 bool HasAnyPHIs = false;
451 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
452 if (FixedOperands[i]) continue; // operand doesn't need a phi.
453 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000454 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000455 FirstOp->getName()+".pn");
456 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000457
Chris Lattnerde1fede2010-01-05 05:31:55 +0000458 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
459 OperandPhis[i] = NewPN;
460 FixedOperands[i] = NewPN;
461 HasAnyPHIs = true;
462 }
463
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000464
Chris Lattnerde1fede2010-01-05 05:31:55 +0000465 // Add all operands to the new PHIs.
466 if (HasAnyPHIs) {
467 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
468 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
469 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000470
Chris Lattnerde1fede2010-01-05 05:31:55 +0000471 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
472 if (PHINode *OpPhi = OperandPhis[op])
473 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
474 }
475 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000476
Chris Lattnerde1fede2010-01-05 05:31:55 +0000477 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000479 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
480 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000481 if (AllInBounds) NewGEP->setIsInBounds();
Dehao Chenf4646272017-10-02 18:13:14 +0000482 PHIArgMergedDebugLoc(NewGEP, PN);
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000483 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000484}
485
486
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000487/// Return true if we know that it is safe to sink the load out of the block
488/// that defines it. This means that it must be obvious the value of the load is
489/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000490///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000491/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000492/// non-address-taken alloca. Doing so will cause us to not promote the alloca
493/// to a register.
494static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000495 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000496
Chris Lattnerde1fede2010-01-05 05:31:55 +0000497 for (++BBI; BBI != E; ++BBI)
498 if (BBI->mayWriteToMemory())
499 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000500
Chris Lattnerde1fede2010-01-05 05:31:55 +0000501 // Check for non-address taken alloca. If not address-taken already, it isn't
502 // profitable to do this xform.
503 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
504 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000506 if (isa<LoadInst>(U)) continue;
507 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000508 // If storing TO the alloca, then the address isn't taken.
509 if (SI->getOperand(1) == AI) continue;
510 }
511 isAddressTaken = true;
512 break;
513 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000514
Chris Lattnerde1fede2010-01-05 05:31:55 +0000515 if (!isAddressTaken && AI->isStaticAlloca())
516 return false;
517 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000518
Chris Lattnerde1fede2010-01-05 05:31:55 +0000519 // If this load is a load from a GEP with a constant offset from an alloca,
520 // then we don't want to sink it. In its present form, it will be
521 // load [constant stack offset]. Sinking it will cause us to have to
522 // materialize the stack addresses in each predecessor in a register only to
523 // do a shared load from register in the successor.
524 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
525 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
526 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
527 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000528
Chris Lattnerde1fede2010-01-05 05:31:55 +0000529 return true;
530}
531
532Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
533 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000534
535 // FIXME: This is overconservative; this transform is allowed in some cases
536 // for atomic operations.
537 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000538 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000539
Chris Lattnerde1fede2010-01-05 05:31:55 +0000540 // When processing loads, we need to propagate two bits of information to the
541 // sunk load: whether it is volatile, and what its alignment is. We currently
542 // don't sink loads when some have their alignment specified and some don't.
543 // visitLoadInst will propagate an alignment onto the load when TD is around,
544 // and if TD isn't around, we can't handle the mixed case.
545 bool isVolatile = FirstLI->isVolatile();
546 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000547 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000548
Chris Lattnerde1fede2010-01-05 05:31:55 +0000549 // We can't sink the load if the loaded value could be modified between the
550 // load and the PHI.
551 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
552 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000553 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000554
Chris Lattnerde1fede2010-01-05 05:31:55 +0000555 // If the PHI is of volatile loads and the load block has multiple
556 // successors, sinking it would remove a load of the volatile value from
557 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000558 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000559 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000560 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000561
Chris Lattnerde1fede2010-01-05 05:31:55 +0000562 // Check to see if all arguments are the same operation.
563 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
564 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
565 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000566 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000567
568 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000569 // the load and the PHI.
570 if (LI->isVolatile() != isVolatile ||
571 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000572 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000573 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000574 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000575
Chris Lattnerde1fede2010-01-05 05:31:55 +0000576 // If some of the loads have an alignment specified but not all of them,
577 // we can't do the transformation.
578 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000579 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000580
Chris Lattnerde1fede2010-01-05 05:31:55 +0000581 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000582
Chris Lattnerde1fede2010-01-05 05:31:55 +0000583 // If the PHI is of volatile loads and the load block has multiple
584 // successors, sinking it would remove a load of the volatile value from
585 // the path through the other successor.
586 if (isVolatile &&
587 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000589 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000590
Chris Lattnerde1fede2010-01-05 05:31:55 +0000591 // Okay, they are all the same operation. Create a new PHI node of the
592 // correct type, and PHI together all of the LHS's of the instructions.
593 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000594 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000595 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596
Chris Lattnerde1fede2010-01-05 05:31:55 +0000597 Value *InVal = FirstLI->getOperand(0);
598 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000599 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000600
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000601 unsigned KnownIDs[] = {
602 LLVMContext::MD_tbaa,
603 LLVMContext::MD_range,
604 LLVMContext::MD_invariant_load,
605 LLVMContext::MD_alias_scope,
606 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000607 LLVMContext::MD_nonnull,
608 LLVMContext::MD_align,
609 LLVMContext::MD_dereferenceable,
610 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000611 };
612
613 for (unsigned ID : KnownIDs)
614 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
615
616 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000617 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000618 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
Florian Hahn406f1ff2018-08-24 11:40:04 +0000619 combineMetadata(NewLI, LI, KnownIDs, true);
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000620 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000621 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000622 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000623 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
624 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000625
Chris Lattnerde1fede2010-01-05 05:31:55 +0000626 if (InVal) {
627 // The new PHI unions all of the same values together. This is really
628 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000629 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000630 delete NewPN;
631 } else {
632 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000633 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000634
Chris Lattnerde1fede2010-01-05 05:31:55 +0000635 // If this was a volatile load that we are merging, make sure to loop through
636 // and mark all the input loads as non-volatile. If we don't do this, we will
637 // insert a new volatile load and the old ones will not be deletable.
638 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000639 for (Value *IncValue : PN.incoming_values())
640 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000641
Dehao Chenf4646272017-10-02 18:13:14 +0000642 PHIArgMergedDebugLoc(NewLI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000643 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000644}
645
Sanjay Patel95334072015-09-27 20:34:31 +0000646/// TODO: This function could handle other cast types, but then it might
647/// require special-casing a cast from the 'i1' type. See the comment in
648/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
649Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
David Majnemereafa28a2015-11-07 00:52:53 +0000650 // We cannot create a new instruction after the PHI if the terminator is an
651 // EHPad because there is no valid insertion point.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000652 if (Instruction *TI = Phi.getParent()->getTerminator())
David Majnemereafa28a2015-11-07 00:52:53 +0000653 if (TI->isEHPad())
654 return nullptr;
655
Sanjay Patel95334072015-09-27 20:34:31 +0000656 // Early exit for the common case of a phi with two operands. These are
657 // handled elsewhere. See the comment below where we check the count of zexts
658 // and constants for more details.
659 unsigned NumIncomingValues = Phi.getNumIncomingValues();
660 if (NumIncomingValues < 3)
661 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000662
Sanjay Patel95334072015-09-27 20:34:31 +0000663 // Find the narrower type specified by the first zext.
664 Type *NarrowType = nullptr;
665 for (Value *V : Phi.incoming_values()) {
666 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
667 NarrowType = Zext->getSrcTy();
668 break;
669 }
670 }
671 if (!NarrowType)
672 return nullptr;
673
674 // Walk the phi operands checking that we only have zexts or constants that
675 // we can shrink for free. Store the new operands for the new phi.
676 SmallVector<Value *, 4> NewIncoming;
677 unsigned NumZexts = 0;
678 unsigned NumConsts = 0;
679 for (Value *V : Phi.incoming_values()) {
680 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
681 // All zexts must be identical and have one use.
682 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
683 return nullptr;
684 NewIncoming.push_back(Zext->getOperand(0));
685 NumZexts++;
686 } else if (auto *C = dyn_cast<Constant>(V)) {
687 // Make sure that constants can fit in the new type.
688 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
689 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
690 return nullptr;
691 NewIncoming.push_back(Trunc);
692 NumConsts++;
693 } else {
694 // If it's not a cast or a constant, bail out.
695 return nullptr;
696 }
697 }
698
699 // The more common cases of a phi with no constant operands or just one
Craig Topperfb71b7d2017-04-14 19:20:12 +0000700 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
701 // respectively. foldOpIntoPhi() wants to do the opposite transform that is
Sanjay Patel95334072015-09-27 20:34:31 +0000702 // performed here. It tries to replicate a cast in the phi operand's basic
703 // block to expose other folding opportunities. Thus, InstCombine will
704 // infinite loop without this check.
705 if (NumConsts == 0 || NumZexts < 2)
706 return nullptr;
707
708 // All incoming values are zexts or constants that are safe to truncate.
709 // Create a new phi node of the narrow type, phi together all of the new
710 // operands, and zext the result back to the original type.
711 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
712 Phi.getName() + ".shrunk");
713 for (unsigned i = 0; i != NumIncomingValues; ++i)
714 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
715
716 InsertNewInstBefore(NewPhi, Phi);
717 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
718}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000719
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000720/// If all operands to a PHI node are the same "unary" operator and they all are
721/// only used by the PHI, PHI together their inputs, and do the operation once,
722/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000723Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
David Majnemer27f24472015-11-06 23:59:23 +0000724 // We cannot create a new instruction after the PHI if the terminator is an
725 // EHPad because there is no valid insertion point.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000726 if (Instruction *TI = PN.getParent()->getTerminator())
David Majnemer27f24472015-11-06 23:59:23 +0000727 if (TI->isEHPad())
728 return nullptr;
729
Chris Lattnerde1fede2010-01-05 05:31:55 +0000730 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
731
732 if (isa<GetElementPtrInst>(FirstInst))
733 return FoldPHIArgGEPIntoPHI(PN);
734 if (isa<LoadInst>(FirstInst))
735 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000736
Chris Lattnerde1fede2010-01-05 05:31:55 +0000737 // Scan the instruction, looking for input operations that can be folded away.
738 // If all input operands to the phi are the same instruction (e.g. a cast from
739 // the same type or "+42") we can pull the operation through the PHI, reducing
740 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000741 Constant *ConstantOp = nullptr;
742 Type *CastSrcTy = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000743
Chris Lattnerde1fede2010-01-05 05:31:55 +0000744 if (isa<CastInst>(FirstInst)) {
745 CastSrcTy = FirstInst->getOperand(0)->getType();
746
747 // Be careful about transforming integer PHIs. We don't want to pessimize
748 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000749 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Sanjay Patel2217f752017-01-31 17:25:42 +0000750 if (!shouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000751 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000752 }
753 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000754 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000755 // otherwise call FoldPHIArgBinOpIntoPHI.
756 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000757 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000758 return FoldPHIArgBinOpIntoPHI(PN);
759 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000760 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000761 }
762
763 // Check to see if all arguments are the same operation.
764 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
765 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000766 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
767 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000768 if (CastSrcTy) {
769 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000770 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000771 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000772 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000773 }
774 }
775
776 // Okay, they are all the same operation. Create a new PHI node of the
777 // correct type, and PHI together all of the LHS's of the instructions.
778 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000779 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000780 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000781
782 Value *InVal = FirstInst->getOperand(0);
783 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
784
785 // Add all operands to the new PHI.
786 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
787 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
788 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000789 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000790 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
791 }
792
793 Value *PhiVal;
794 if (InVal) {
795 // The new PHI unions all of the same values together. This is really
796 // common, so we handle it intelligently here for compile-time speed.
797 PhiVal = InVal;
798 delete NewPN;
799 } else {
800 InsertNewInstBefore(NewPN, PN);
801 PhiVal = NewPN;
802 }
803
804 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000805 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
806 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
807 PN.getType());
Dehao Chenf4646272017-10-02 18:13:14 +0000808 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000809 return NewCI;
810 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811
Chris Lattnera8fed472011-02-17 23:01:49 +0000812 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
813 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Silviu Barangae985c762016-04-22 11:21:36 +0000814 BinOp->copyIRFlags(PN.getIncomingValue(0));
815
816 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
817 BinOp->andIRFlags(PN.getIncomingValue(i));
818
Dehao Chenf4646272017-10-02 18:13:14 +0000819 PHIArgMergedDebugLoc(BinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000820 return BinOp;
821 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000822
Chris Lattnerde1fede2010-01-05 05:31:55 +0000823 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000824 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
825 PhiVal, ConstantOp);
Dehao Chenf4646272017-10-02 18:13:14 +0000826 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000827 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000828}
829
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000830/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000831static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000832 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000833 if (PN->use_empty()) return true;
834 if (!PN->hasOneUse()) return false;
835
836 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000837 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000838 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000839
Chris Lattnerde1fede2010-01-05 05:31:55 +0000840 // Don't scan crazily complex things.
841 if (PotentiallyDeadPHIs.size() == 16)
842 return false;
843
Chandler Carruthcdf47882014-03-09 03:16:01 +0000844 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000845 return DeadPHICycle(PU, PotentiallyDeadPHIs);
846
847 return false;
848}
849
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000850/// Return true if this phi node is always equal to NonPhiInVal.
851/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000852/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000853static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000854 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000855 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000856 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000857 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000858
Chris Lattnerde1fede2010-01-05 05:31:55 +0000859 // Don't scan crazily complex things.
860 if (ValueEqualPHIs.size() == 16)
861 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000862
Chris Lattnerde1fede2010-01-05 05:31:55 +0000863 // Scan the operands to see if they are either phi nodes or are equal to
864 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000865 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000866 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
867 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
868 return false;
869 } else if (Op != NonPhiInVal)
870 return false;
871 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000872
Chris Lattnerde1fede2010-01-05 05:31:55 +0000873 return true;
874}
875
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000876/// Return an existing non-zero constant if this phi node has one, otherwise
877/// return constant 1.
Jun Bum Lim339e9722016-02-11 15:50:07 +0000878static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000879 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
Jun Bum Lim339e9722016-02-11 15:50:07 +0000880 for (Value *V : PN.operands())
881 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
Craig Topper79ab6432017-07-06 18:39:47 +0000882 if (!ConstVA->isZero())
Jun Bum Lim339e9722016-02-11 15:50:07 +0000883 return ConstVA;
884 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
885}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000886
887namespace {
888struct PHIUsageRecord {
889 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
890 unsigned Shift; // The amount shifted.
891 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000892
Chris Lattnerde1fede2010-01-05 05:31:55 +0000893 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
894 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000895
Chris Lattnerde1fede2010-01-05 05:31:55 +0000896 bool operator<(const PHIUsageRecord &RHS) const {
897 if (PHIId < RHS.PHIId) return true;
898 if (PHIId > RHS.PHIId) return false;
899 if (Shift < RHS.Shift) return true;
900 if (Shift > RHS.Shift) return false;
901 return Inst->getType()->getPrimitiveSizeInBits() <
902 RHS.Inst->getType()->getPrimitiveSizeInBits();
903 }
904};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000905
Chris Lattnerde1fede2010-01-05 05:31:55 +0000906struct LoweredPHIRecord {
907 PHINode *PN; // The PHI that was lowered.
908 unsigned Shift; // The amount shifted.
909 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000910
Chris Lattner229907c2011-07-18 04:54:35 +0000911 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000912 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000913
Chris Lattnerde1fede2010-01-05 05:31:55 +0000914 // Ctor form used by DenseMap.
915 LoweredPHIRecord(PHINode *pn, unsigned Sh)
916 : PN(pn), Shift(Sh), Width(0) {}
917};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000918}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000919
920namespace llvm {
921 template<>
922 struct DenseMapInfo<LoweredPHIRecord> {
923 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000924 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000925 }
926 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000928 }
929 static unsigned getHashValue(const LoweredPHIRecord &Val) {
930 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
931 (Val.Width>>3);
932 }
933 static bool isEqual(const LoweredPHIRecord &LHS,
934 const LoweredPHIRecord &RHS) {
935 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
936 LHS.Width == RHS.Width;
937 }
938 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000939}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000940
941
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000942/// This is an integer PHI and we know that it has an illegal type: see if it is
943/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
944/// the various pieces being extracted. This sort of thing is introduced when
945/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000946///
947/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
948/// inttoptr. We should produce new PHIs in the right type.
949///
950Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
951 // PHIUsers - Keep track of all of the truncated values extracted from a set
952 // of PHIs, along with their offset. These are the things we want to rewrite.
953 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000954
Chris Lattnerde1fede2010-01-05 05:31:55 +0000955 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
956 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
957 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
958 // check the uses of (to ensure they are all extracts).
959 SmallVector<PHINode*, 8> PHIsToSlice;
960 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000961
Chris Lattnerde1fede2010-01-05 05:31:55 +0000962 PHIsToSlice.push_back(&FirstPhi);
963 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000964
Chris Lattnerde1fede2010-01-05 05:31:55 +0000965 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
966 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000967
Chris Lattnerde1fede2010-01-05 05:31:55 +0000968 // Scan the input list of the PHI. If any input is an invoke, and if the
969 // input is defined in the predecessor, then we won't be split the critical
970 // edge which is required to insert a truncate. Because of this, we have to
971 // bail out.
972 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
973 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000974 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000975 if (II->getParent() != PN->getIncomingBlock(i))
976 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000977
Chris Lattnerde1fede2010-01-05 05:31:55 +0000978 // If we have a phi, and if it's directly in the predecessor, then we have
979 // a critical edge where we need to put the truncate. Since we can't
980 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000981 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000982 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000983
Chandler Carruthcdf47882014-03-09 03:16:01 +0000984 for (User *U : PN->users()) {
985 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000986
Chris Lattnerde1fede2010-01-05 05:31:55 +0000987 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000988 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000989 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000990 PHIsToSlice.push_back(UserPN);
991 continue;
992 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000993
Chris Lattnerde1fede2010-01-05 05:31:55 +0000994 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000995 if (isa<TruncInst>(UserI)) {
996 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000997 continue;
998 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000999
Chris Lattnerde1fede2010-01-05 05:31:55 +00001000 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001001 if (UserI->getOpcode() != Instruction::LShr ||
1002 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
1003 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001004 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001005
Chandler Carruthcdf47882014-03-09 03:16:01 +00001006 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1007 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001008 }
1009 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001010
Chris Lattnerde1fede2010-01-05 05:31:55 +00001011 // If we have no users, they must be all self uses, just nuke the PHI.
1012 if (PHIUsers.empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00001013 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001014
Chris Lattnerde1fede2010-01-05 05:31:55 +00001015 // If this phi node is transformable, create new PHIs for all the pieces
1016 // extracted out of it. First, sort the users by their offset and size.
1017 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001018
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001019 LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1020 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) dbgs()
1021 << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001022
Chris Lattnerde1fede2010-01-05 05:31:55 +00001023 // PredValues - This is a temporary used when rewriting PHI nodes. It is
1024 // hoisted out here to avoid construction/destruction thrashing.
1025 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001026
Chris Lattnerde1fede2010-01-05 05:31:55 +00001027 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1028 // introduce redundant PHIs.
1029 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001030
Chris Lattnerde1fede2010-01-05 05:31:55 +00001031 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1032 unsigned PHIId = PHIUsers[UserI].PHIId;
1033 PHINode *PN = PHIsToSlice[PHIId];
1034 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +00001035 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001036
Chris Lattnerde1fede2010-01-05 05:31:55 +00001037 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001038
Chris Lattnerde1fede2010-01-05 05:31:55 +00001039 // If we've already lowered a user like this, reuse the previously lowered
1040 // value.
Craig Topperf40110f2014-04-25 05:29:35 +00001041 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001042
Chris Lattnerde1fede2010-01-05 05:31:55 +00001043 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +00001044 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1045 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001046 assert(EltPHI->getType() != PN->getType() &&
1047 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001048
Chris Lattnerde1fede2010-01-05 05:31:55 +00001049 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1050 BasicBlock *Pred = PN->getIncomingBlock(i);
1051 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001052
Chris Lattnerde1fede2010-01-05 05:31:55 +00001053 // If we already have a value for this predecessor, reuse it.
1054 if (PredVal) {
1055 EltPHI->addIncoming(PredVal, Pred);
1056 continue;
1057 }
1058
1059 // Handle the PHI self-reuse case.
1060 Value *InVal = PN->getIncomingValue(i);
1061 if (InVal == PN) {
1062 PredVal = EltPHI;
1063 EltPHI->addIncoming(PredVal, Pred);
1064 continue;
1065 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001066
Chris Lattnerde1fede2010-01-05 05:31:55 +00001067 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1068 // If the incoming value was a PHI, and if it was one of the PHIs we
1069 // already rewrote it, just use the lowered value.
1070 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1071 PredVal = Res;
1072 EltPHI->addIncoming(PredVal, Pred);
1073 continue;
1074 }
1075 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001076
Chris Lattnerde1fede2010-01-05 05:31:55 +00001077 // Otherwise, do an extract in the predecessor.
Craig Topperbb4069e2017-07-07 23:16:26 +00001078 Builder.SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001079 Value *Res = InVal;
1080 if (Offset)
Craig Topperbb4069e2017-07-07 23:16:26 +00001081 Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
Chris Lattnerde1fede2010-01-05 05:31:55 +00001082 Offset), "extract");
Craig Topperbb4069e2017-07-07 23:16:26 +00001083 Res = Builder.CreateTrunc(Res, Ty, "extract.t");
Chris Lattnerde1fede2010-01-05 05:31:55 +00001084 PredVal = Res;
1085 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001086
Chris Lattnerde1fede2010-01-05 05:31:55 +00001087 // If the incoming value was a PHI, and if it was one of the PHIs we are
1088 // rewriting, we will ultimately delete the code we inserted. This
1089 // means we need to revisit that PHI to make sure we extract out the
1090 // needed piece.
1091 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1092 if (PHIsInspected.count(OldInVal)) {
David Majnemer42531262016-08-12 03:55:06 +00001093 unsigned RefPHIId =
1094 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001095 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +00001096 cast<Instruction>(Res)));
1097 ++UserE;
1098 }
1099 }
1100 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001101
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001102 LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
1103 << *EltPHI << '\n');
Chris Lattnerde1fede2010-01-05 05:31:55 +00001104 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1105 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001106
Chris Lattnerde1fede2010-01-05 05:31:55 +00001107 // Replace the use of this piece with the PHI node.
Sanjay Patel4b198802016-02-01 22:23:39 +00001108 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001109 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001110
Chris Lattnerde1fede2010-01-05 05:31:55 +00001111 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1112 // with undefs.
1113 Value *Undef = UndefValue::get(FirstPhi.getType());
1114 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +00001115 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1116 return replaceInstUsesWith(FirstPhi, Undef);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001117}
1118
1119// PHINode simplification
1120//
1121Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Craig Toppera4205622017-06-09 03:21:29 +00001122 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001123 return replaceInstUsesWith(PN, V);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001124
Sanjay Patel95334072015-09-27 20:34:31 +00001125 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1126 return Result;
1127
Chris Lattnerde1fede2010-01-05 05:31:55 +00001128 // If all PHI operands are the same operation, pull them through the PHI,
1129 // reducing code size.
1130 if (isa<Instruction>(PN.getIncomingValue(0)) &&
1131 isa<Instruction>(PN.getIncomingValue(1)) &&
1132 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1133 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1134 // FIXME: The hasOneUse check will fail for PHIs that use the value more
1135 // than themselves more than once.
1136 PN.getIncomingValue(0)->hasOneUse())
1137 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1138 return Result;
1139
1140 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
1141 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1142 // PHI)... break the cycle.
1143 if (PN.hasOneUse()) {
Xinliang David Li4cdc9da2017-10-10 05:07:54 +00001144 if (Instruction *Result = FoldIntegerTypedPHI(PN))
1145 return Result;
1146
Chandler Carruthcdf47882014-03-09 03:16:01 +00001147 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001148 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1149 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1150 PotentiallyDeadPHIs.insert(&PN);
1151 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001152 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001153 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001154
Chris Lattnerde1fede2010-01-05 05:31:55 +00001155 // If this phi has a single use, and if that use just computes a value for
1156 // the next iteration of a loop, delete the phi. This occurs with unused
1157 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
1158 // common case here is good because the only other things that catch this
1159 // are induction variable analysis (sometimes) and ADCE, which is only run
1160 // late.
1161 if (PHIUser->hasOneUse() &&
1162 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00001163 PHIUser->user_back() == &PN) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001164 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001165 }
Jun Bum Lim339e9722016-02-11 15:50:07 +00001166 // When a PHI is used only to be compared with zero, it is safe to replace
1167 // an incoming value proved as known nonzero with any non-zero constant.
Jun Bum Lim10e58e82016-02-11 16:46:13 +00001168 // For example, in the code below, the incoming value %v can be replaced
1169 // with any non-zero constant based on the fact that the PHI is only used to
1170 // be compared with zero and %v is a known non-zero value:
Jun Bum Lim339e9722016-02-11 15:50:07 +00001171 // %v = select %cond, 1, 2
1172 // %p = phi [%v, BB] ...
1173 // icmp eq, %p, 0
1174 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1175 // FIXME: To be simple, handle only integer type for now.
1176 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1177 match(CmpInst->getOperand(1), m_Zero())) {
1178 ConstantInt *NonZeroConst = nullptr;
1179 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1180 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1181 Value *VA = PN.getIncomingValue(i);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001182 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
Jun Bum Lim339e9722016-02-11 15:50:07 +00001183 if (!NonZeroConst)
1184 NonZeroConst = GetAnyNonZeroConstInt(PN);
1185 PN.setIncomingValue(i, NonZeroConst);
1186 }
1187 }
1188 }
Chris Lattnerde1fede2010-01-05 05:31:55 +00001189 }
1190
1191 // We sometimes end up with phi cycles that non-obviously end up being the
1192 // same value, for example:
1193 // z = some value; x = phi (y, z); y = phi (x, z)
1194 // where the phi nodes don't necessarily need to be in the same block. Do a
1195 // quick check to see if the PHI node only contains a single non-phi value, if
1196 // so, scan to see if the phi cycle is actually equal to that value.
1197 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001198 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +00001199 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001200 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +00001201 isa<PHINode>(PN.getIncomingValue(InValNo)))
1202 ++InValNo;
1203
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001204 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +00001205 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001206
Chris Lattnerde1fede2010-01-05 05:31:55 +00001207 // Scan the rest of the operands to see if there are any conflicts, if so
1208 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001209 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001210 Value *OpVal = PN.getIncomingValue(InValNo);
1211 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1212 break;
1213 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001214
Chris Lattnerde1fede2010-01-05 05:31:55 +00001215 // If we scanned over all operands, then we have one unique value plus
1216 // phi values. Scan PHI nodes to see if they all merge in each other or
1217 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001218 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001219 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1220 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001221 return replaceInstUsesWith(PN, NonPhiInVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001222 }
1223 }
1224 }
1225
1226 // If there are multiple PHIs, sort their operands so that they all list
1227 // the blocks in the same order. This will help identical PHIs be eliminated
1228 // by other passes. Other passes shouldn't depend on this for correctness
1229 // however.
1230 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1231 if (&PN != FirstPN)
1232 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1233 BasicBlock *BBA = PN.getIncomingBlock(i);
1234 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1235 if (BBA != BBB) {
1236 Value *VA = PN.getIncomingValue(i);
1237 unsigned j = PN.getBasicBlockIndex(BBB);
1238 Value *VB = PN.getIncomingValue(j);
1239 PN.setIncomingBlock(i, BBB);
1240 PN.setIncomingValue(i, VB);
1241 PN.setIncomingBlock(j, BBA);
1242 PN.setIncomingValue(j, VA);
1243 // NOTE: Instcombine normally would want us to "return &PN" if we
1244 // modified any of the operands of an instruction. However, since we
1245 // aren't adding or removing uses (just rearranging them) we don't do
1246 // this in this case.
1247 }
1248 }
1249
1250 // If this is an integer PHI and we know that it has an illegal type, see if
1251 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1252 // PHI into the various pieces being extracted. This sort of thing is
1253 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001254 if (PN.getType()->isIntegerTy() &&
1255 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +00001256 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1257 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001258
Craig Topperf40110f2014-04-25 05:29:35 +00001259 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +00001260}