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