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