LLVM 23.0.0git
BasicBlockUtils.cpp
Go to the documentation of this file.
1//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
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 family of functions perform manipulations on basic blocks, and
10// instructions contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/Analysis/CFG.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/CycleInfo.h"
28#include "llvm/IR/DebugInfo.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/ValueHandle.h"
43#include "llvm/Support/Debug.h"
46#include <cassert>
47#include <cstdint>
48#include <string>
49#include <utility>
50#include <vector>
51
52using namespace llvm;
53
54#define DEBUG_TYPE "basicblock-utils"
55
57 "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58 cl::desc("Set the maximum path length when checking whether a basic block "
59 "is followed by a block that either has a terminating "
60 "deoptimizing call or is terminated with an unreachable"));
61
62/// Zap all the instructions in the block and replace them with an unreachable
63/// instruction and notify the basic block's successors that one of their
64/// predecessors is going away.
65static void
68 bool KeepOneInputPHIs) {
69 // Loop through all of our successors and make sure they know that one
70 // of their predecessors is going away.
71 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
72 for (BasicBlock *Succ : successors(BB)) {
73 Succ->removePredecessor(BB, KeepOneInputPHIs);
74 if (Updates && UniqueSuccessors.insert(Succ).second)
75 Updates->push_back({DominatorTree::Delete, BB, Succ});
76 }
77
78 // Zap all the instructions in the block.
79 while (!BB->empty()) {
80 Instruction &I = BB->back();
81 // If this instruction is used, replace uses with an arbitrary value.
82 // Because control flow can't get here, we don't care what we replace the
83 // value with. Note that since this block is unreachable, and all values
84 // contained within it must dominate their uses, that all uses will
85 // eventually be removed (they are themselves dead).
86 if (!I.use_empty())
87 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
88 BB->back().eraseFromParent();
89 }
90 new UnreachableInst(BB->getContext(), BB);
91 assert(BB->size() == 1 && isa<UnreachableInst>(BB->getTerminator()) &&
92 "The successor list of BB isn't empty before "
93 "applying corresponding DTU updates.");
94}
95
97 for (const Instruction &I : *BB) {
99 if (CCI && (CCI->isLoop() || CCI->isEntry()))
100 return true;
101 }
102 return false;
103}
104
107 bool KeepOneInputPHIs) {
108 SmallPtrSet<BasicBlock *, 4> UniqueEHRetBlocksToDelete;
109 for (auto *BB : BBs) {
110 auto NonFirstPhiIt = BB->getFirstNonPHIIt();
111 if (NonFirstPhiIt != BB->end()) {
112 Instruction &I = *NonFirstPhiIt;
113 // Exception handling funclets need to be explicitly addressed.
114 // These funclets must begin with cleanuppad or catchpad and end with
115 // cleanupred or catchret. The return instructions can be in different
116 // basic blocks than the pad instruction. If we would only delete the
117 // first block, the we would have possible cleanupret and catchret
118 // instructions with poison arguments, which wouldn't be valid.
119 if (isa<FuncletPadInst>(I)) {
120 UniqueEHRetBlocksToDelete.clear();
121
122 for (User *User : I.users()) {
123 Instruction *ReturnInstr = dyn_cast<Instruction>(User);
124 // If we have a cleanupret or catchret block, replace it with just an
125 // unreachable. The other alternative, that may use a catchpad is a
126 // catchswitch. That does not need special handling for now.
127 if (isa<CatchReturnInst>(ReturnInstr) ||
128 isa<CleanupReturnInst>(ReturnInstr)) {
129 BasicBlock *ReturnInstrBB = ReturnInstr->getParent();
130 UniqueEHRetBlocksToDelete.insert(ReturnInstrBB);
131 }
132 }
133
134 for (BasicBlock *EHRetBB : UniqueEHRetBlocksToDelete)
135 emptyAndDetachBlock(EHRetBB, Updates, KeepOneInputPHIs);
136 }
137 }
138
139 UniqueEHRetBlocksToDelete.clear();
140
141 // Detaching and emptying the current basic block.
142 emptyAndDetachBlock(BB, Updates, KeepOneInputPHIs);
143 }
144}
145
147 bool KeepOneInputPHIs) {
148 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
149}
150
152 bool KeepOneInputPHIs) {
153#ifndef NDEBUG
154 // Make sure that all predecessors of each dead block is also dead.
156 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
157 for (auto *BB : Dead)
158 for (BasicBlock *Pred : predecessors(BB))
159 assert(Dead.count(Pred) && "All predecessors must be dead!");
160#endif
161
163 detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
164
165 if (DTU)
166 DTU->applyUpdates(Updates);
167
168 for (BasicBlock *BB : BBs)
169 if (DTU)
170 DTU->deleteBB(BB);
171 else
172 BB->eraseFromParent();
173}
174
176 bool KeepOneInputPHIs) {
178
179 // Mark all reachable blocks.
180 for (BasicBlock *BB : depth_first_ext(&F, Reachable))
181 (void)BB/* Mark all reachable blocks */;
182
183 // Collect all dead blocks.
184 std::vector<BasicBlock*> DeadBlocks;
185 for (BasicBlock &BB : F)
186 if (!Reachable.count(&BB))
187 DeadBlocks.push_back(&BB);
188
189 // Delete the dead blocks.
190 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
191
192 return !DeadBlocks.empty();
193}
194
196 MemoryDependenceResults *MemDep) {
197 if (!isa<PHINode>(BB->begin()))
198 return false;
199
200 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
201 if (PN->getIncomingValue(0) != PN)
202 PN->replaceAllUsesWith(PN->getIncomingValue(0));
203 else
204 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
205
206 if (MemDep)
207 MemDep->removeInstruction(PN); // Memdep updates AA itself.
208
209 PN->eraseFromParent();
210 }
211 return true;
212}
213
215 MemorySSAUpdater *MSSAU,
216 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs) {
217 // Recursively deleting a PHI may cause multiple PHIs to be deleted
218 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
220
221 SmallPtrSet<PHINode *, 32> LocalKnownNonDeadPHIs;
222 if (!KnownNonDeadPHIs)
223 KnownNonDeadPHIs = &LocalKnownNonDeadPHIs;
224
225 bool Changed = false;
226 for (const auto &PHI : PHIs) {
227 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHI.operator Value *())) {
228 bool PHIChanged = RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU, KnownNonDeadPHIs);
229 Changed |= PHIChanged;
230 if (PHIChanged && KnownNonDeadPHIs)
231 KnownNonDeadPHIs->clear();
232 }
233 }
234 return Changed;
235}
236
238 LoopInfo *LI, MemorySSAUpdater *MSSAU,
240 bool PredecessorWithTwoSuccessors,
241 DominatorTree *DT) {
242 if (BB->hasAddressTaken())
243 return false;
244
245 // Can't merge if there are multiple predecessors, or no predecessors.
246 BasicBlock *PredBB = BB->getUniquePredecessor();
247 if (!PredBB) return false;
248
249 // Don't break self-loops.
250 if (PredBB == BB) return false;
251
252 // Don't break unwinding instructions or terminators with other side-effects.
253 Instruction *PTI = PredBB->getTerminator();
254 if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
255 return false;
256
257 // Can't merge if there are multiple distinct successors.
258 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
259 return false;
260
261 // Currently only allow PredBB to have two predecessors, one being BB.
262 // Update BI to branch to BB's only successor instead of BB.
263 CondBrInst *PredBB_BI;
264 BasicBlock *NewSucc = nullptr;
265 unsigned FallThruPath;
266 if (PredecessorWithTwoSuccessors) {
267 if (!(PredBB_BI = dyn_cast<CondBrInst>(PTI)))
268 return false;
270 if (!BB_JmpI)
271 return false;
272 NewSucc = BB_JmpI->getSuccessor();
273 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
274 }
275
276 // Can't merge if there is PHI loop.
277 for (PHINode &PN : BB->phis())
278 if (llvm::is_contained(PN.incoming_values(), &PN))
279 return false;
280
281 // Don't break if both the basic block and the predecessor contain loop or
282 // entry convergent intrinsics, since there may only be one convergence token
283 // per block.
286 return false;
287
288 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
289 << PredBB->getName() << "\n");
290
291 // Begin by getting rid of unneeded PHIs.
292 SmallVector<AssertingVH<Value>, 4> IncomingValues;
293 if (isa<PHINode>(BB->front())) {
294 for (PHINode &PN : BB->phis())
295 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
296 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
297 IncomingValues.push_back(PN.getIncomingValue(0));
298 FoldSingleEntryPHINodes(BB, MemDep);
299 }
300
301 if (DT) {
302 assert(!DTU && "cannot use both DT and DTU for updates");
303 DomTreeNode *PredNode = DT->getNode(PredBB);
304 DomTreeNode *BBNode = DT->getNode(BB);
305 if (PredNode) {
306 assert(BBNode && "PredNode unreachable but BBNode reachable?");
307 for (DomTreeNode *C : to_vector(BBNode->children()))
308 C->setIDom(PredNode);
309 }
310 }
311 // DTU update: Collect all the edges that exit BB.
312 // These dominator edges will be redirected from Pred.
313 std::vector<DominatorTree::UpdateType> Updates;
314 if (DTU) {
315 assert(!DT && "cannot use both DT and DTU for updates");
316 // To avoid processing the same predecessor more than once.
319 successors(PredBB));
320 Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
321 // Add insert edges first. Experimentally, for the particular case of two
322 // blocks that can be merged, with a single successor and single predecessor
323 // respectively, it is beneficial to have all insert updates first. Deleting
324 // edges first may lead to unreachable blocks, followed by inserting edges
325 // making the blocks reachable again. Such DT updates lead to high compile
326 // times. We add inserts before deletes here to reduce compile time.
327 for (BasicBlock *SuccOfBB : successors(BB))
328 // This successor of BB may already be a PredBB's successor.
329 if (!SuccsOfPredBB.contains(SuccOfBB))
330 if (SeenSuccs.insert(SuccOfBB).second)
331 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
332 SeenSuccs.clear();
333 for (BasicBlock *SuccOfBB : successors(BB))
334 if (SeenSuccs.insert(SuccOfBB).second)
335 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
336 Updates.push_back({DominatorTree::Delete, PredBB, BB});
337 }
338
339 Instruction *STI = BB->getTerminator();
340 Instruction *Start = &*BB->begin();
341 // If there's nothing to move, mark the starting instruction as the last
342 // instruction in the block. Terminator instruction is handled separately.
343 if (Start == STI)
344 Start = PTI;
345
346 // Move all definitions in the successor to the predecessor...
347 PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
348
349 if (MSSAU)
350 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
351
352 // Make all PHI nodes that referred to BB now refer to Pred as their
353 // source...
354 BB->replaceAllUsesWith(PredBB);
355
356 if (PredecessorWithTwoSuccessors) {
357 // Delete the unconditional branch from BB.
358 BB->back().eraseFromParent();
359 // Add unreachable to now empty BB.
360 new UnreachableInst(BB->getContext(), BB);
361
362 // Update branch in the predecessor.
363 PredBB_BI->setSuccessor(FallThruPath, NewSucc);
364 } else {
365 // Delete the unconditional branch from the predecessor.
366 PredBB->back().eraseFromParent();
367
368 // Move terminator instruction.
369 BB->back().moveBeforePreserving(*PredBB, PredBB->end());
370 // Add unreachable to now empty BB.
371 new UnreachableInst(BB->getContext(), BB);
372
373 // Terminator may be a memory accessing instruction too.
374 if (MSSAU)
376 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
377 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
378 }
379
380 // Inherit predecessors name if it exists.
381 if (!PredBB->hasName())
382 PredBB->takeName(BB);
383
384 if (LI)
385 LI->removeBlock(BB);
386
387 if (MemDep)
389
390 if (DTU)
391 DTU->applyUpdates(Updates);
392
393 if (DT) {
394 assert(succ_empty(BB) &&
395 "successors should have been transferred to PredBB");
396 DT->eraseNode(BB);
397 }
398
399 // Finally, erase the old block and update dominator info.
400 DeleteDeadBlock(BB, DTU);
401
402 return true;
403}
404
407 LoopInfo *LI) {
408 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
409
410 bool BlocksHaveBeenMerged = false;
411 while (!MergeBlocks.empty()) {
412 BasicBlock *BB = *MergeBlocks.begin();
413 BasicBlock *Dest = BB->getSingleSuccessor();
414 if (Dest && (!L || L->contains(Dest))) {
415 BasicBlock *Fold = Dest->getUniquePredecessor();
416 (void)Fold;
417 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
418 assert(Fold == BB &&
419 "Expecting BB to be unique predecessor of the Dest block");
420 MergeBlocks.erase(Dest);
421 BlocksHaveBeenMerged = true;
422 } else
423 MergeBlocks.erase(BB);
424 } else
425 MergeBlocks.erase(BB);
426 }
427 return BlocksHaveBeenMerged;
428}
429
430/// Remove redundant instructions within sequences of consecutive dbg.value
431/// instructions. This is done using a backward scan to keep the last dbg.value
432/// describing a specific variable/fragment.
433///
434/// BackwardScan strategy:
435/// ----------------------
436/// Given a sequence of consecutive DbgValueInst like this
437///
438/// dbg.value ..., "x", FragmentX1 (*)
439/// dbg.value ..., "y", FragmentY1
440/// dbg.value ..., "x", FragmentX2
441/// dbg.value ..., "x", FragmentX1 (**)
442///
443/// then the instruction marked with (*) can be removed (it is guaranteed to be
444/// obsoleted by the instruction marked with (**) as the latter instruction is
445/// describing the same variable using the same fragment info).
446///
447/// Possible improvements:
448/// - Check fully overlapping fragments and not only identical fragments.
452 for (auto &I : reverse(*BB)) {
453 for (DbgVariableRecord &DVR :
454 reverse(filterDbgVars(I.getDbgRecordRange()))) {
455 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
456 DVR.getDebugLoc()->getInlinedAt());
457 auto R = VariableSet.insert(Key);
458 // If the same variable fragment is described more than once it is enough
459 // to keep the last one (i.e. the first found since we for reverse
460 // iteration).
461 if (R.second)
462 continue;
463
464 if (DVR.isDbgAssign()) {
465 // Don't delete dbg.assign intrinsics that are linked to instructions.
466 if (!at::getAssignmentInsts(&DVR).empty())
467 continue;
468 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
469 }
470
471 ToBeRemoved.push_back(&DVR);
472 }
473 // Sequence with consecutive dbg.value instrs ended. Clear the map to
474 // restart identifying redundant instructions if case we find another
475 // dbg.value sequence.
476 VariableSet.clear();
477 }
478
479 for (auto &DVR : ToBeRemoved)
480 DVR->eraseFromParent();
481
482 return !ToBeRemoved.empty();
483}
484
485/// Remove redundant dbg.value instructions using a forward scan. This can
486/// remove a dbg.value instruction that is redundant due to indicating that a
487/// variable has the same value as already being indicated by an earlier
488/// dbg.value.
489///
490/// ForwardScan strategy:
491/// ---------------------
492/// Given two identical dbg.value instructions, separated by a block of
493/// instructions that isn't describing the same variable, like this
494///
495/// dbg.value X1, "x", FragmentX1 (**)
496/// <block of instructions, none being "dbg.value ..., "x", ...">
497/// dbg.value X1, "x", FragmentX1 (*)
498///
499/// then the instruction marked with (*) can be removed. Variable "x" is already
500/// described as being mapped to the SSA value X1.
501///
502/// Possible improvements:
503/// - Keep track of non-overlapping fragments.
505 bool RemovedAny = false;
507 std::pair<SmallVector<Value *, 4>, DIExpression *>, 4>
508 VariableMap;
509 for (auto &I : *BB) {
510 for (DbgVariableRecord &DVR :
511 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
512 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
513 continue;
514 DebugVariable Key(DVR.getVariable(), std::nullopt,
515 DVR.getDebugLoc()->getInlinedAt());
516 auto [VMI, Inserted] = VariableMap.try_emplace(Key);
517 // A dbg.assign with no linked instructions can be treated like a
518 // dbg.value (i.e. can be deleted).
519 bool IsDbgValueKind =
520 (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
521
522 // Update the map if we found a new value/expression describing the
523 // variable, or if the variable wasn't mapped already.
524 SmallVector<Value *, 4> Values(DVR.location_ops());
525 if (Inserted || VMI->second.first != Values ||
526 VMI->second.second != DVR.getExpression()) {
527 if (IsDbgValueKind)
528 VMI->second = {Values, DVR.getExpression()};
529 else
530 VMI->second = {Values, nullptr};
531 continue;
532 }
533 // Don't delete dbg.assign intrinsics that are linked to instructions.
534 if (!IsDbgValueKind)
535 continue;
536 // Found an identical mapping. Remember the instruction for later removal.
537 DVR.eraseFromParent();
538 RemovedAny = true;
539 }
540 }
541
542 return RemovedAny;
543}
544
545/// Remove redundant undef dbg.assign intrinsic from an entry block using a
546/// forward scan.
547/// Strategy:
548/// ---------------------
549/// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
550/// linked to an intrinsic, and don't share an aggregate variable with a debug
551/// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
552/// that come before non-undef debug intrinsics for the variable are
553/// deleted. Given:
554///
555/// dbg.assign undef, "x", FragmentX1 (*)
556/// <block of instructions, none being "dbg.value ..., "x", ...">
557/// dbg.value %V, "x", FragmentX2
558/// <block of instructions, none being "dbg.value ..., "x", ...">
559/// dbg.assign undef, "x", FragmentX1
560///
561/// then (only) the instruction marked with (*) can be removed.
562/// Possible improvements:
563/// - Keep track of non-overlapping fragments.
565 assert(BB->isEntryBlock() && "expected entry block");
566 bool RemovedAny = false;
567 DenseSet<DebugVariableAggregate> SeenDefForAggregate;
568
569 // Remove undef dbg.assign intrinsics that are encountered before
570 // any non-undef intrinsics from the entry block.
571 for (auto &I : *BB) {
572 for (DbgVariableRecord &DVR :
573 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
574 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
575 continue;
576 bool IsDbgValueKind =
577 (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
578
579 DebugVariableAggregate Aggregate(&DVR);
580 if (!SeenDefForAggregate.contains(Aggregate)) {
581 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
582 if (!IsKill) {
583 SeenDefForAggregate.insert(Aggregate);
584 } else if (DVR.isDbgAssign()) {
585 DVR.eraseFromParent();
586 RemovedAny = true;
587 }
588 }
589 }
590 }
591
592 return RemovedAny;
593}
594
596 bool MadeChanges = false;
597 // By using the "backward scan" strategy before the "forward scan" strategy we
598 // can remove both dbg.value (2) and (3) in a situation like this:
599 //
600 // (1) dbg.value V1, "x", DIExpression()
601 // ...
602 // (2) dbg.value V2, "x", DIExpression()
603 // (3) dbg.value V1, "x", DIExpression()
604 //
605 // The backward scan will remove (2), it is made obsolete by (3). After
606 // getting (2) out of the way, the foward scan will remove (3) since "x"
607 // already is described as having the value V1 at (1).
609 if (BB->isEntryBlock() &&
611 MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
613
614 if (MadeChanges)
615 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
616 << BB->getName() << "\n");
617 return MadeChanges;
618}
619
621 Instruction &I = *BI;
622 // Replaces all of the uses of the instruction with uses of the value
623 I.replaceAllUsesWith(V);
624
625 // Make sure to propagate a name if there is one already.
626 if (I.hasName() && !V->hasName())
627 V->takeName(&I);
628
629 // Delete the unnecessary instruction now...
630 BI = BI->eraseFromParent();
631}
632
634 Instruction *I) {
635 assert(I->getParent() == nullptr &&
636 "ReplaceInstWithInst: Instruction already inserted into basic block!");
637
638 // Copy debug location to newly added instruction, if it wasn't already set
639 // by the caller.
640 if (!I->getDebugLoc())
641 I->setDebugLoc(BI->getDebugLoc());
642
643 // Insert the new instruction into the basic block...
644 BasicBlock::iterator New = I->insertInto(BB, BI);
645
646 // Replace all uses of the old instruction, and delete it.
648
649 // Move BI back to point to the newly inserted instruction
650 BI = New;
651}
652
654 // Remember visited blocks to avoid infinite loop
656 unsigned Depth = 0;
658 VisitedBlocks.insert(BB).second) {
661 return true;
662 BB = BB->getUniqueSuccessor();
663 }
664 return false;
665}
666
668 BasicBlock::iterator BI(From);
669 ReplaceInstWithInst(From->getParent(), BI, To);
670}
671
673 LoopInfo *LI, MemorySSAUpdater *MSSAU,
674 const Twine &BBName) {
675 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
676
677 Instruction *LatchTerm = BB->getTerminator();
678
681
682 if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
683 // If this is a critical edge, let SplitKnownCriticalEdge do it.
684 return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
685 }
686
687 // If the edge isn't critical, then BB has a single successor or Succ has a
688 // single pred. Split the block.
689 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
690 // If the successor only has a single pred, split the top of the successor
691 // block.
692 assert(SP == BB && "CFG broken");
693 (void)SP;
694 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
695 return splitBlockBefore(Succ, &Succ->front(), &DTU, LI, MSSAU, BBName);
696 }
697
698 // Otherwise, if BB has a single successor, split it at the bottom of the
699 // block.
700 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
701 "Should have a single succ!");
702 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
703}
704
705/// Helper function to update the cycle or loop information after inserting a
706/// new block between a callbr instruction and one of its target blocks. Adds
707/// the new block to the innermost cycle or loop that the callbr instruction and
708/// the original target block share.
709/// \p LCI cycle or loop information to update
710/// \p CallBrBlock block containing the callbr instruction
711/// \p CallBrTarget new target block of the callbr instruction
712/// \p Succ original target block of the callbr instruction
713template <typename TI, typename T>
714static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock,
715 BasicBlock *CallBrTarget, BasicBlock *Succ) {
716 static_assert(std::is_same_v<TI, CycleInfo> || std::is_same_v<TI, LoopInfo>,
717 "type must be CycleInfo or LoopInfo");
718 if (!LCI)
719 return false;
720
721 T *LC;
722 if constexpr (std::is_same_v<TI, CycleInfo>)
723 LC = LCI->getSmallestCommonCycle(CallBrBlock, Succ);
724 else
725 LC = LCI->getSmallestCommonLoop(CallBrBlock, Succ);
726 if (!LC)
727 return false;
728
729 if constexpr (std::is_same_v<TI, CycleInfo>)
730 LCI->addBlockToCycle(CallBrTarget, LC);
731 else
732 LC->addBasicBlockToLoop(CallBrTarget, *LCI);
733
734 return true;
735}
736
738 unsigned SuccIdx, BasicBlock *CallBrTarget,
739 DomTreeUpdater *DTU, CycleInfo *CI,
740 LoopInfo *LI, bool *UpdatedLI) {
741 CallBrInst *CallBr = dyn_cast<CallBrInst>(CallBrBlock->getTerminator());
742 assert(CallBr && "expected callbr terminator");
743 assert(SuccIdx < CallBr->getNumSuccessors() &&
744 Succ == CallBr->getSuccessor(SuccIdx) && "invalid successor index");
745
746 if (UpdatedLI)
747 *UpdatedLI = false;
748
749 bool ReusesCallBrTarget = CallBrTarget;
750 // Create a new block between callbr and the specified successor.
751 // splitBlockBefore cannot be re-used here since it cannot split if the split
752 // point is a PHI node (because BasicBlock::splitBasicBlockBefore cannot
753 // handle that). But we don't need to rewire every part of a potential PHI
754 // node. We only care about the edge between CallBrBlock and the original
755 // successor.
756 if (!ReusesCallBrTarget) {
757 CallBrTarget = BasicBlock::Create(CallBrBlock->getContext(),
758 CallBrBlock->getName() + ".target." +
759 Succ->getName(),
760 CallBrBlock->getParent());
761 // Jump from the new target block to the original successor.
762 UncondBrInst::Create(Succ, CallBrTarget);
763 // Replace a single incoming value with the callbr target block. We cannot
764 // use replacePhiUsesWith, as this would replace the value for every edge
765 // from the callbr block to succ.
766 for (PHINode &PN : Succ->phis()) {
767 int BBIdx = PN.getBasicBlockIndex(CallBrBlock);
768 assert(BBIdx != -1 && "expected incoming value form callbr block");
769 PN.setIncomingBlock(BBIdx, CallBrTarget);
770 }
771
772 bool Updated = updateCycleLoopInfo<LoopInfo, Loop>(LI, CallBrBlock,
773 CallBrTarget, Succ);
774 if (UpdatedLI)
775 *UpdatedLI = Updated;
776 updateCycleLoopInfo<CycleInfo, Cycle>(CI, CallBrBlock, CallBrTarget, Succ);
777 } else {
778 for (PHINode &PN : Succ->phis())
779 PN.removeIncomingValue(CallBrBlock, false);
780 }
781
782 // Rewire control flow from callbr to the new target block.
783 CallBr->setSuccessor(SuccIdx, CallBrTarget);
784
785 if (DTU) {
786 if (!ReusesCallBrTarget)
787 DTU->applyUpdates({{DominatorTree::Insert, CallBrBlock, CallBrTarget}});
788 if (DTU->getDomTree().dominates(CallBrBlock, Succ)) {
789 if (!is_contained(successors(CallBrBlock), Succ))
790 DTU->applyUpdates({{DominatorTree::Delete, CallBrBlock, Succ}});
791 if (!ReusesCallBrTarget)
792 DTU->applyUpdates({{DominatorTree::Insert, CallBrTarget, Succ}});
793 }
794 }
795
796 return CallBrTarget;
797}
798
800 if (auto *II = dyn_cast<InvokeInst>(TI))
801 II->setUnwindDest(Succ);
802 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
803 CS->setUnwindDest(Succ);
804 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
805 CR->setUnwindDest(Succ);
806 else
807 llvm_unreachable("unexpected terminator instruction");
808}
809
811 BasicBlock *NewPred, PHINode *Until) {
812 int BBIdx = 0;
813 for (PHINode &PN : DestBB->phis()) {
814 // We manually update the LandingPadReplacement PHINode and it is the last
815 // PHI Node. So, if we find it, we are done.
816 if (Until == &PN)
817 break;
818
819 // Reuse the previous value of BBIdx if it lines up. In cases where we
820 // have multiple phi nodes with *lots* of predecessors, this is a speed
821 // win because we don't have to scan the PHI looking for TIBB. This
822 // happens because the BB list of PHI nodes are usually in the same
823 // order.
824 if (PN.getIncomingBlock(BBIdx) != OldPred)
825 BBIdx = PN.getBasicBlockIndex(OldPred);
826
827 assert(BBIdx != -1 && "Invalid PHI Index!");
828 PN.setIncomingBlock(BBIdx, NewPred);
829 }
830}
831
833 LandingPadInst *OriginalPad,
834 PHINode *LandingPadReplacement,
836 const Twine &BBName) {
837
838 auto PadInst = Succ->getFirstNonPHIIt();
839 if (!LandingPadReplacement && !PadInst->isEHPad())
840 return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
841
842 auto *LI = Options.LI;
844 // Check if extra modifications will be required to preserve loop-simplify
845 // form after splitting. If it would require splitting blocks with IndirectBr
846 // terminators, bail out if preserving loop-simplify form is requested.
847 if (Options.PreserveLoopSimplify && LI) {
848 if (Loop *BBLoop = LI->getLoopFor(BB)) {
849
850 // The only way that we can break LoopSimplify form by splitting a
851 // critical edge is when there exists some edge from BBLoop to Succ *and*
852 // the only edge into Succ from outside of BBLoop is that of NewBB after
853 // the split. If the first isn't true, then LoopSimplify still holds,
854 // NewBB is the new exit block and it has no non-loop predecessors. If the
855 // second isn't true, then Succ was not in LoopSimplify form prior to
856 // the split as it had a non-loop predecessor. In both of these cases,
857 // the predecessor must be directly in BBLoop, not in a subloop, or again
858 // LoopSimplify doesn't hold.
859 for (BasicBlock *P : predecessors(Succ)) {
860 if (P == BB)
861 continue; // The new block is known.
862 if (LI->getLoopFor(P) != BBLoop) {
863 // Loop is not in LoopSimplify form, no need to re simplify after
864 // splitting edge.
865 LoopPreds.clear();
866 break;
867 }
868 LoopPreds.push_back(P);
869 }
870 // Loop-simplify form can be preserved, if we can split all in-loop
871 // predecessors.
872 if (any_of(LoopPreds, [](BasicBlock *Pred) {
873 return isa<IndirectBrInst>(Pred->getTerminator());
874 })) {
875 return nullptr;
876 }
877 }
878 }
879
880 auto *NewBB =
881 BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
882 setUnwindEdgeTo(BB->getTerminator(), NewBB);
883 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
884
885 if (LandingPadReplacement) {
886 auto *NewLP = OriginalPad->clone();
887 auto *Terminator = UncondBrInst::Create(Succ, NewBB);
888 NewLP->insertBefore(Terminator->getIterator());
889 LandingPadReplacement->addIncoming(NewLP, NewBB);
890 } else {
891 Value *ParentPad = nullptr;
892 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
893 ParentPad = FuncletPad->getParentPad();
894 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
895 ParentPad = CatchSwitch->getParentPad();
896 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
897 ParentPad = CleanupPad->getParentPad();
898 else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
899 ParentPad = LandingPad->getParent();
900 else
901 llvm_unreachable("handling for other EHPads not implemented yet");
902
903 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
904 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
905 }
906
907 auto *DT = Options.DT;
908 auto *MSSAU = Options.MSSAU;
909 if (!DT && !LI)
910 return NewBB;
911
912 if (DT) {
913 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
915
916 Updates.push_back({DominatorTree::Insert, BB, NewBB});
917 Updates.push_back({DominatorTree::Insert, NewBB, Succ});
918 Updates.push_back({DominatorTree::Delete, BB, Succ});
919
920 DTU.applyUpdates(Updates);
921 DTU.flush();
922
923 if (MSSAU) {
924 MSSAU->applyUpdates(Updates, *DT);
925 if (VerifyMemorySSA)
926 MSSAU->getMemorySSA()->verifyMemorySSA();
927 }
928 }
929
930 if (LI) {
931 if (Loop *BBLoop = LI->getLoopFor(BB)) {
932 // If one or the other blocks were not in a loop, the new block is not
933 // either, and thus LI doesn't need to be updated.
934 if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
935 if (BBLoop == SuccLoop) {
936 // Both in the same loop, the NewBB joins loop.
937 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
938 } else if (BBLoop->contains(SuccLoop)) {
939 // Edge from an outer loop to an inner loop. Add to the outer loop.
940 BBLoop->addBasicBlockToLoop(NewBB, *LI);
941 } else if (SuccLoop->contains(BBLoop)) {
942 // Edge from an inner loop to an outer loop. Add to the outer loop.
943 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
944 } else {
945 // Edge from two loops with no containment relation. Because these
946 // are natural loops, we know that the destination block must be the
947 // header of its loop (adding a branch into a loop elsewhere would
948 // create an irreducible loop).
949 assert(SuccLoop->getHeader() == Succ &&
950 "Should not create irreducible loops!");
951 if (Loop *P = SuccLoop->getParentLoop())
952 P->addBasicBlockToLoop(NewBB, *LI);
953 }
954 }
955
956 // If BB is in a loop and Succ is outside of that loop, we may need to
957 // update LoopSimplify form and LCSSA form.
958 if (!BBLoop->contains(Succ)) {
959 assert(!BBLoop->contains(NewBB) &&
960 "Split point for loop exit is contained in loop!");
961
962 // Update LCSSA form in the newly created exit block.
963 if (Options.PreserveLCSSA) {
964 createPHIsForSplitLoopExit(BB, NewBB, Succ);
965 }
966
967 if (!LoopPreds.empty()) {
969 Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
970 if (Options.PreserveLCSSA)
971 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
972 }
973 }
974 }
975 }
976
977 return NewBB;
978}
979
981 BasicBlock *SplitBB, BasicBlock *DestBB) {
982 // SplitBB shouldn't have anything non-trivial in it yet.
983 assert((&*SplitBB->getFirstNonPHIIt() == SplitBB->getTerminator() ||
984 SplitBB->isLandingPad()) &&
985 "SplitBB has non-PHI nodes!");
986
987 // For each PHI in the destination block.
988 for (PHINode &PN : DestBB->phis()) {
989 int Idx = PN.getBasicBlockIndex(SplitBB);
990 assert(Idx >= 0 && "Invalid Block Index");
991 Value *V = PN.getIncomingValue(Idx);
992
993 // If the input is a PHI which already satisfies LCSSA, don't create
994 // a new one.
995 if (const PHINode *VP = dyn_cast<PHINode>(V))
996 if (VP->getParent() == SplitBB)
997 continue;
998
999 // Otherwise a new PHI is needed. Create one and populate it.
1000 PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
1001 BasicBlock::iterator InsertPos =
1002 SplitBB->isLandingPad() ? SplitBB->begin()
1003 : SplitBB->getTerminator()->getIterator();
1004 NewPN->insertBefore(InsertPos);
1005 for (BasicBlock *BB : Preds)
1006 NewPN->addIncoming(V, BB);
1007
1008 // Update the original PHI.
1009 PN.setIncomingValue(Idx, NewPN);
1010 }
1011}
1012
1013unsigned
1016 unsigned NumBroken = 0;
1017 for (BasicBlock &BB : F) {
1018 Instruction *TI = BB.getTerminator();
1019 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
1020 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1021 if (SplitCriticalEdge(TI, i, Options))
1022 ++NumBroken;
1023 }
1024 return NumBroken;
1025}
1026
1028 DomTreeUpdater *DTU, DominatorTree *DT,
1029 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1030 const Twine &BBName) {
1031 BasicBlock::iterator SplitIt = SplitPt;
1032 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
1033 ++SplitIt;
1034 assert(SplitIt != SplitPt->getParent()->end());
1035 }
1036 std::string Name = BBName.str();
1037 BasicBlock *New = Old->splitBasicBlock(
1038 SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
1039
1040 // The new block lives in whichever loop the old one did. This preserves
1041 // LCSSA as well, because we force the split point to be after any PHI nodes.
1042 if (LI)
1043 if (Loop *L = LI->getLoopFor(Old))
1044 L->addBasicBlockToLoop(New, *LI);
1045
1046 if (DTU) {
1048 // Old dominates New. New node dominates all other nodes dominated by Old.
1049 SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1050 Updates.push_back({DominatorTree::Insert, Old, New});
1051 Updates.reserve(Updates.size() + 2 * succ_size(New));
1052 for (BasicBlock *SuccessorOfOld : successors(New))
1053 if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
1054 Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
1055 Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1056 }
1057
1058 DTU->applyUpdates(Updates);
1059 } else if (DT)
1060 // Old dominates New. New node dominates all other nodes dominated by Old.
1061 if (DomTreeNode *OldNode = DT->getNode(Old)) {
1062 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1063
1064 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
1065 for (DomTreeNode *I : Children)
1066 DT->changeImmediateDominator(I, NewNode);
1067 }
1068
1069 // Move MemoryAccesses still tracked in Old, but part of New now.
1070 // Update accesses in successor blocks accordingly.
1071 if (MSSAU)
1072 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
1073
1074 return New;
1075}
1076
1078 DominatorTree *DT, LoopInfo *LI,
1079 MemorySSAUpdater *MSSAU, const Twine &BBName) {
1080 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName);
1081}
1083 DomTreeUpdater *DTU, LoopInfo *LI,
1084 MemorySSAUpdater *MSSAU, const Twine &BBName) {
1085 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName);
1086}
1087
1089 const DominatorTree &DT) {
1090 for (const BasicBlock *Pred : predecessors(L.getHeader()))
1091 if (!L.contains(Pred) && DT.isReachableFromEntry(Pred))
1092 return true;
1093
1094 return false;
1095}
1096
1097/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1098/// Invalidates DFS Numbering when DTU or DT is provided.
1101 DomTreeUpdater *DTU, DominatorTree *DT,
1102 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1103 bool PreserveLCSSA, bool &HasLoopExit) {
1104 // Update dominator tree if available.
1105 if (DTU) {
1106 // Recalculation of DomTree is needed when updating a forward DomTree and
1107 // the Entry BB is replaced.
1108 if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1109 // The entry block was removed and there is no external interface for
1110 // the dominator tree to be notified of this change. In this corner-case
1111 // we recalculate the entire tree.
1112 DTU->recalculate(*NewBB->getParent());
1113 } else {
1114 // Split block expects NewBB to have a non-empty set of predecessors.
1116 SmallPtrSet<BasicBlock *, 8> UniquePreds;
1117 Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1118 Updates.reserve(Updates.size() + 2 * Preds.size());
1119 for (auto *Pred : Preds)
1120 if (UniquePreds.insert(Pred).second) {
1121 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1122 Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1123 }
1124 DTU->applyUpdates(Updates);
1125 }
1126 } else if (DT) {
1127 if (OldBB == DT->getRootNode()->getBlock()) {
1128 assert(NewBB->isEntryBlock());
1129 DT->setNewRoot(NewBB);
1130 } else {
1131 // Split block expects NewBB to have a non-empty set of predecessors.
1132 DT->splitBlock(NewBB);
1133 }
1134 }
1135
1136 // Update MemoryPhis after split if MemorySSA is available
1137 if (MSSAU)
1138 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1139
1140 // The rest of the logic is only relevant for updating the loop structures.
1141 if (!LI)
1142 return;
1143
1144 if (DTU && DTU->hasDomTree())
1145 DT = &DTU->getDomTree();
1146 assert(DT && "DT should be available to update LoopInfo!");
1147 Loop *L = LI->getLoopFor(OldBB);
1148
1149 // If we need to preserve loop analyses, collect some information about how
1150 // this split will affect loops.
1151 bool IsLoopEntry = !!L;
1152 bool SplitMakesNewLoopHeader = false;
1153 for (BasicBlock *Pred : Preds) {
1154 // Preds that are not reachable from entry should not be used to identify if
1155 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1156 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1157 // as true and make the NewBB the header of some loop. This breaks LI.
1158 if (!DT->isReachableFromEntry(Pred))
1159 continue;
1160 // If we need to preserve LCSSA, determine if any of the preds is a loop
1161 // exit.
1162 if (PreserveLCSSA)
1163 if (Loop *PL = LI->getLoopFor(Pred))
1164 if (!PL->contains(OldBB))
1165 HasLoopExit = true;
1166
1167 // If we need to preserve LoopInfo, note whether any of the preds crosses
1168 // an interesting loop boundary.
1169 if (!L)
1170 continue;
1171 if (L->contains(Pred))
1172 IsLoopEntry = false;
1173 else
1174 SplitMakesNewLoopHeader = true;
1175 }
1176
1177 // Unless we have a loop for OldBB, nothing else to do here.
1178 if (!L)
1179 return;
1180
1181 if (IsLoopEntry) {
1182 // Add the new block to the nearest enclosing loop (and not an adjacent
1183 // loop). To find this, examine each of the predecessors and determine which
1184 // loops enclose them, and select the most-nested loop which contains the
1185 // loop containing the block being split.
1186 Loop *InnermostPredLoop = nullptr;
1187 for (BasicBlock *Pred : Preds) {
1188 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1189 // Seek a loop which actually contains the block being split (to avoid
1190 // adjacent loops).
1191 while (PredLoop && !PredLoop->contains(OldBB))
1192 PredLoop = PredLoop->getParentLoop();
1193
1194 // Select the most-nested of these loops which contains the block.
1195 if (PredLoop && PredLoop->contains(OldBB) &&
1196 (!InnermostPredLoop ||
1197 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1198 InnermostPredLoop = PredLoop;
1199 }
1200 }
1201
1202 if (InnermostPredLoop)
1203 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1204 } else {
1205 L->addBasicBlockToLoop(NewBB, *LI);
1206 if (SplitMakesNewLoopHeader) {
1207 // The old header might still have a loop entry. If so the loop becomes
1208 // irreducible and must be erased. Otherwise the NewBB becomes the loop
1209 // header.
1210 if (hasReachableLoopEntryToHeader(*L, *DT))
1211 LI->erase(L);
1212 else
1213 L->moveToHeader(NewBB);
1214 }
1215 }
1216}
1217
1219 BasicBlock::iterator SplitPt,
1220 DomTreeUpdater *DTU, LoopInfo *LI,
1221 MemorySSAUpdater *MSSAU,
1222 const Twine &BBName) {
1223 BasicBlock::iterator SplitIt = SplitPt;
1224 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1225 ++SplitIt;
1228 SplitIt, BBName.isTriviallyEmpty() ? Old->getName() + ".split" : BBName);
1229
1230 bool HasLoopExit = false;
1231 UpdateAnalysisInformation(Old, New, Preds, DTU, nullptr, LI, MSSAU, false,
1232 HasLoopExit);
1233
1234 return New;
1235}
1236
1237/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1238/// This also updates AliasAnalysis, if available.
1239static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1241 bool HasLoopExit) {
1242 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1244 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1245 PHINode *PN = cast<PHINode>(I++);
1246
1247 // Check to see if all of the values coming in are the same. If so, we
1248 // don't need to create a new PHI node, unless it's needed for LCSSA.
1249 Value *InVal = nullptr;
1250 if (!HasLoopExit) {
1251 InVal = PN->getIncomingValueForBlock(Preds[0]);
1252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1253 if (!PredSet.count(PN->getIncomingBlock(i)))
1254 continue;
1255 if (!InVal)
1256 InVal = PN->getIncomingValue(i);
1257 else if (InVal != PN->getIncomingValue(i)) {
1258 InVal = nullptr;
1259 break;
1260 }
1261 }
1262 }
1263
1264 if (InVal) {
1265 // If all incoming values for the new PHI would be the same, just don't
1266 // make a new PHI. Instead, just remove the incoming values from the old
1267 // PHI.
1269 [&](unsigned Idx) {
1270 return PredSet.contains(PN->getIncomingBlock(Idx));
1271 },
1272 /* DeletePHIIfEmpty */ false);
1273
1274 // Add an incoming value to the PHI node in the loop for the preheader
1275 // edge.
1276 PN->addIncoming(InVal, NewBB);
1277 continue;
1278 }
1279
1280 // If the values coming into the block are not the same, we need a new
1281 // PHI.
1282 // Create the new PHI node, insert it into NewBB at the end of the block
1283 PHINode *NewPHI =
1284 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
1285
1286 // NOTE! This loop walks backwards for a reason! First off, this minimizes
1287 // the cost of removal if we end up removing a large number of values, and
1288 // second off, this ensures that the indices for the incoming values aren't
1289 // invalidated when we remove one.
1290 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1291 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1292 if (PredSet.count(IncomingBB)) {
1293 Value *V = PN->removeIncomingValue(i, false);
1294 NewPHI->addIncoming(V, IncomingBB);
1295 }
1296 }
1297
1298 PN->addIncoming(NewPHI, NewBB);
1299 }
1300}
1301
1303 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1304 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1305 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1306 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1307
1308static BasicBlock *
1310 const char *Suffix, DomTreeUpdater *DTU,
1311 DominatorTree *DT, LoopInfo *LI,
1312 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1313 // Do not attempt to split that which cannot be split.
1314 if (!BB->canSplitPredecessors())
1315 return nullptr;
1316
1317 // For the landingpads we need to act a bit differently.
1318 // Delegate this work to the SplitLandingPadPredecessors.
1319 if (BB->isLandingPad()) {
1321 std::string NewName = std::string(Suffix) + ".split-lp";
1322
1323 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1324 DTU, DT, LI, MSSAU, PreserveLCSSA);
1325 return NewBBs[0];
1326 }
1327
1328 // Create new basic block, insert right before the original block.
1330 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1331
1332 // The new block unconditionally branches to the old block.
1333 UncondBrInst *BI = UncondBrInst::Create(BB, NewBB);
1334
1335 Loop *L = nullptr;
1336 BasicBlock *OldLatch = nullptr;
1337 // Splitting the predecessors of a loop header creates a preheader block.
1338 if (LI && LI->isLoopHeader(BB)) {
1339 L = LI->getLoopFor(BB);
1340 // Using the loop start line number prevents debuggers stepping into the
1341 // loop body for this instruction.
1342 BI->setDebugLoc(L->getStartLoc());
1343
1344 // If BB is the header of the Loop, it is possible that the loop is
1345 // modified, such that the current latch does not remain the latch of the
1346 // loop. If that is the case, the loop metadata from the current latch needs
1347 // to be applied to the new latch.
1348 OldLatch = L->getLoopLatch();
1349 } else
1350 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1351
1352 // Move the edges from Preds to point to NewBB instead of BB.
1353 for (BasicBlock *Pred : Preds) {
1354 // This is slightly more strict than necessary; the minimum requirement
1355 // is that there be no more than one indirectbr branching to BB. And
1356 // all BlockAddress uses would need to be updated.
1357 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1358 "Cannot split an edge from an IndirectBrInst");
1359 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1360 }
1361
1362 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1363 // node becomes an incoming value for BB's phi node. However, if the Preds
1364 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1365 // account for the newly created predecessor.
1366 if (Preds.empty()) {
1367 // Insert dummy values as the incoming value.
1368 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1369 cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1370 }
1371
1372 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1373 bool HasLoopExit = false;
1374 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1375 HasLoopExit);
1376
1377 if (!Preds.empty()) {
1378 // Update the PHI nodes in BB with the values coming from NewBB.
1379 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1380 }
1381
1382 if (OldLatch) {
1383 BasicBlock *NewLatch = L->getLoopLatch();
1384 if (NewLatch != OldLatch) {
1385 MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1386 NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
1387 // It's still possible that OldLatch is the latch of another inner loop,
1388 // in which case we do not remove the metadata.
1389 Loop *IL = LI->getLoopFor(OldLatch);
1390 if (IL && IL->getLoopLatch() != OldLatch)
1391 OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1392 }
1393 }
1394
1395 return NewBB;
1396}
1397
1400 const char *Suffix, DominatorTree *DT,
1401 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1402 bool PreserveLCSSA) {
1403 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1404 MSSAU, PreserveLCSSA);
1405}
1408 const char *Suffix,
1409 DomTreeUpdater *DTU, LoopInfo *LI,
1410 MemorySSAUpdater *MSSAU,
1411 bool PreserveLCSSA) {
1412 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1413 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1414}
1415
1417 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1418 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1419 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1420 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1421 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1422
1423 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1424 // it right before the original block.
1425 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1426 OrigBB->getName() + Suffix1,
1427 OrigBB->getParent(), OrigBB);
1428 NewBBs.push_back(NewBB1);
1429
1430 // The new block unconditionally branches to the old block.
1431 UncondBrInst *BI1 = UncondBrInst::Create(OrigBB, NewBB1);
1432 BI1->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1433
1434 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1435 for (BasicBlock *Pred : Preds) {
1436 // This is slightly more strict than necessary; the minimum requirement
1437 // is that there be no more than one indirectbr branching to BB. And
1438 // all BlockAddress uses would need to be updated.
1439 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1440 "Cannot split an edge from an IndirectBrInst");
1441 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1442 }
1443
1444 bool HasLoopExit = false;
1445 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1446 PreserveLCSSA, HasLoopExit);
1447
1448 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1449 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1450
1451 // Move the remaining edges from OrigBB to point to NewBB2.
1452 SmallVector<BasicBlock*, 8> NewBB2Preds;
1453 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1454 i != e; ) {
1455 BasicBlock *Pred = *i++;
1456 if (Pred == NewBB1) continue;
1457 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1458 "Cannot split an edge from an IndirectBrInst");
1459 NewBB2Preds.push_back(Pred);
1460 e = pred_end(OrigBB);
1461 }
1462
1463 BasicBlock *NewBB2 = nullptr;
1464 if (!NewBB2Preds.empty()) {
1465 // Create another basic block for the rest of OrigBB's predecessors.
1466 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1467 OrigBB->getName() + Suffix2,
1468 OrigBB->getParent(), OrigBB);
1469 NewBBs.push_back(NewBB2);
1470
1471 // The new block unconditionally branches to the old block.
1472 UncondBrInst *BI2 = UncondBrInst::Create(OrigBB, NewBB2);
1473 BI2->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1474
1475 // Move the remaining edges from OrigBB to point to NewBB2.
1476 for (BasicBlock *NewBB2Pred : NewBB2Preds)
1477 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1478
1479 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1480 HasLoopExit = false;
1481 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1482 PreserveLCSSA, HasLoopExit);
1483
1484 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1485 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1486 }
1487
1488 LandingPadInst *LPad = OrigBB->getLandingPadInst();
1489 Instruction *Clone1 = LPad->clone();
1490 Clone1->setName(Twine("lpad") + Suffix1);
1491 Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1492
1493 if (NewBB2) {
1494 Instruction *Clone2 = LPad->clone();
1495 Clone2->setName(Twine("lpad") + Suffix2);
1496 Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1497
1498 // Create a PHI node for the two cloned landingpad instructions only
1499 // if the original landingpad instruction has some uses.
1500 if (!LPad->use_empty()) {
1501 assert(!LPad->getType()->isTokenTy() &&
1502 "Split cannot be applied if LPad is token type. Otherwise an "
1503 "invalid PHINode of token type would be created.");
1504 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
1505 PN->addIncoming(Clone1, NewBB1);
1506 PN->addIncoming(Clone2, NewBB2);
1507 LPad->replaceAllUsesWith(PN);
1508 }
1509 LPad->eraseFromParent();
1510 } else {
1511 // There is no second clone. Just replace the landing pad with the first
1512 // clone.
1513 LPad->replaceAllUsesWith(Clone1);
1514 LPad->eraseFromParent();
1515 }
1516}
1517
1520 const char *Suffix1, const char *Suffix2,
1522 DomTreeUpdater *DTU, LoopInfo *LI,
1523 MemorySSAUpdater *MSSAU,
1524 bool PreserveLCSSA) {
1525 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1526 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1527 PreserveLCSSA);
1528}
1529
1531 BasicBlock *Pred,
1532 DomTreeUpdater *DTU) {
1533 Instruction *UncondBranch = Pred->getTerminator();
1534 // Clone the return and add it to the end of the predecessor.
1535 Instruction *NewRet = RI->clone();
1536 NewRet->insertInto(Pred, Pred->end());
1537
1538 // If the return instruction returns a value, and if the value was a
1539 // PHI node in "BB", propagate the right value into the return.
1540 for (Use &Op : NewRet->operands()) {
1541 Value *V = Op;
1542 Instruction *NewBC = nullptr;
1543 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1544 // Return value might be bitcasted. Clone and insert it before the
1545 // return instruction.
1546 V = BCI->getOperand(0);
1547 NewBC = BCI->clone();
1548 NewBC->insertInto(Pred, NewRet->getIterator());
1549 Op = NewBC;
1550 }
1551
1552 Instruction *NewEV = nullptr;
1554 V = EVI->getOperand(0);
1555 NewEV = EVI->clone();
1556 if (NewBC) {
1557 NewBC->setOperand(0, NewEV);
1558 NewEV->insertInto(Pred, NewBC->getIterator());
1559 } else {
1560 NewEV->insertInto(Pred, NewRet->getIterator());
1561 Op = NewEV;
1562 }
1563 }
1564
1565 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1566 if (PN->getParent() == BB) {
1567 if (NewEV) {
1568 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1569 } else if (NewBC)
1570 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1571 else
1572 Op = PN->getIncomingValueForBlock(Pred);
1573 }
1574 }
1575 }
1576
1577 // Update any PHI nodes in the returning block to realize that we no
1578 // longer branch to them.
1579 BB->removePredecessor(Pred);
1580 UncondBranch->eraseFromParent();
1581
1582 if (DTU)
1583 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1584
1585 return cast<ReturnInst>(NewRet);
1586}
1587
1589 BasicBlock::iterator SplitBefore,
1590 bool Unreachable,
1591 MDNode *BranchWeights,
1592 DomTreeUpdater *DTU, LoopInfo *LI,
1593 BasicBlock *ThenBlock) {
1595 Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1596 /* UnreachableThen */ Unreachable,
1597 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1598 return ThenBlock->getTerminator();
1599}
1600
1602 BasicBlock::iterator SplitBefore,
1603 bool Unreachable,
1604 MDNode *BranchWeights,
1605 DomTreeUpdater *DTU, LoopInfo *LI,
1606 BasicBlock *ElseBlock) {
1608 Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1609 /* UnreachableThen */ false,
1610 /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1611 return ElseBlock->getTerminator();
1612}
1613
1615 Instruction **ThenTerm,
1616 Instruction **ElseTerm,
1617 MDNode *BranchWeights,
1618 DomTreeUpdater *DTU, LoopInfo *LI) {
1619 BasicBlock *ThenBlock = nullptr;
1620 BasicBlock *ElseBlock = nullptr;
1622 Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1623 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1624
1625 *ThenTerm = ThenBlock->getTerminator();
1626 *ElseTerm = ElseBlock->getTerminator();
1627}
1628
1630 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1631 BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1632 MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1633 assert((ThenBlock || ElseBlock) &&
1634 "At least one branch block must be created");
1635 assert((!UnreachableThen || !UnreachableElse) &&
1636 "Split block tail must be reachable");
1637
1639 SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1640 BasicBlock *Head = SplitBefore->getParent();
1641 if (DTU) {
1642 UniqueOrigSuccessors.insert_range(successors(Head));
1643 Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1644 }
1645
1646 LLVMContext &C = Head->getContext();
1647 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1648 BasicBlock *TrueBlock = Tail;
1649 BasicBlock *FalseBlock = Tail;
1650 bool ThenToTailEdge = false;
1651 bool ElseToTailEdge = false;
1652
1653 // Encapsulate the logic around creation/insertion/etc of a new block.
1654 auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1655 bool &ToTailEdge) {
1656 if (PBB == nullptr)
1657 return; // Do not create/insert a block.
1658
1659 if (*PBB)
1660 BB = *PBB; // Caller supplied block, use it.
1661 else {
1662 // Create a new block.
1663 BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1664 if (Unreachable)
1665 (void)new UnreachableInst(C, BB);
1666 else {
1667 (void)UncondBrInst::Create(Tail, BB);
1668 ToTailEdge = true;
1669 }
1670 BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1671 // Pass the new block back to the caller.
1672 *PBB = BB;
1673 }
1674 };
1675
1676 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1677 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1678
1679 Instruction *HeadOldTerm = Head->getTerminator();
1680 CondBrInst *HeadNewTerm = CondBrInst::Create(Cond, TrueBlock, FalseBlock);
1681 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1682 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1683
1684 if (DTU) {
1685 Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1686 Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1687 if (ThenToTailEdge)
1688 Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1689 if (ElseToTailEdge)
1690 Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1691 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1692 Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1693 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1694 Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1695 DTU->applyUpdates(Updates);
1696 }
1697
1698 if (LI) {
1699 if (Loop *L = LI->getLoopFor(Head); L) {
1700 if (ThenToTailEdge)
1701 L->addBasicBlockToLoop(TrueBlock, *LI);
1702 if (ElseToTailEdge)
1703 L->addBasicBlockToLoop(FalseBlock, *LI);
1704 L->addBasicBlockToLoop(Tail, *LI);
1705 }
1706 }
1707}
1708
1709std::pair<Instruction *, Value *>
1711 BasicBlock::iterator SplitBefore) {
1712 BasicBlock *LoopPred = SplitBefore->getParent();
1713 BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1714 BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1715
1716 auto *Ty = End->getType();
1717 auto &DL = SplitBefore->getDataLayout();
1718 const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1719
1720 IRBuilder<> Builder(LoopBody->getTerminator());
1721 auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1722 auto *IVNext =
1723 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1724 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1725 auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1726 IV->getName() + ".check");
1727 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1728 LoopBody->getTerminator()->eraseFromParent();
1729
1730 // Populate the IV PHI.
1731 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1732 IV->addIncoming(IVNext, LoopBody);
1733
1734 return std::make_pair(&*LoopBody->getFirstNonPHIIt(), IV);
1735}
1736
1738 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
1739 std::function<void(IRBuilderBase &, Value *)> Func) {
1740
1741 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1742
1743 if (EC.isScalable()) {
1744 Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1745
1746 auto [BodyIP, Index] =
1747 SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1748
1749 IRB.SetInsertPoint(BodyIP);
1750 Func(IRB, Index);
1751 return;
1752 }
1753
1754 unsigned Num = EC.getFixedValue();
1755 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1756 IRB.SetInsertPoint(InsertBefore);
1757 Func(IRB, ConstantInt::get(IndexTy, Idx));
1758 }
1759}
1760
1762 Value *EVL, BasicBlock::iterator InsertBefore,
1763 std::function<void(IRBuilderBase &, Value *)> Func) {
1764
1765 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1766 Type *Ty = EVL->getType();
1767
1768 if (!isa<ConstantInt>(EVL)) {
1769 auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1770 IRB.SetInsertPoint(BodyIP);
1771 Func(IRB, Index);
1772 return;
1773 }
1774
1775 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1776 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1777 IRB.SetInsertPoint(InsertBefore);
1778 Func(IRB, ConstantInt::get(Ty, Idx));
1779 }
1780}
1781
1783 BasicBlock *&IfFalse) {
1784 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1785 BasicBlock *Pred1 = nullptr;
1786 BasicBlock *Pred2 = nullptr;
1787
1788 if (SomePHI) {
1789 if (SomePHI->getNumIncomingValues() != 2)
1790 return nullptr;
1791 Pred1 = SomePHI->getIncomingBlock(0);
1792 Pred2 = SomePHI->getIncomingBlock(1);
1793 } else {
1794 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1795 if (PI == PE) // No predecessor
1796 return nullptr;
1797 Pred1 = *PI++;
1798 if (PI == PE) // Only one predecessor
1799 return nullptr;
1800 Pred2 = *PI++;
1801 if (PI != PE) // More than two predecessors
1802 return nullptr;
1803 }
1804
1805 Instruction *Pred1Term = Pred1->getTerminator();
1806 Instruction *Pred2Term = Pred2->getTerminator();
1807
1808 // Eliminate code duplication by ensuring that Pred1Br is conditional if
1809 // either are.
1810 if (isa<CondBrInst>(Pred2Term)) {
1811 // If both branches are conditional, we don't have an "if statement". In
1812 // reality, we could transform this case, but since the condition will be
1813 // required anyway, we stand no chance of eliminating it, so the xform is
1814 // probably not profitable.
1815 if (isa<CondBrInst>(Pred1Term))
1816 return nullptr;
1817
1818 std::swap(Pred1, Pred2);
1819 std::swap(Pred1Term, Pred2Term);
1820 }
1821
1822 // We can only handle branches. Other control flow will be lowered to
1823 // branches if possible anyway.
1824 if (!isa<UncondBrInst>(Pred2Term))
1825 return nullptr;
1826
1827 if (auto *Pred1Br = dyn_cast<CondBrInst>(Pred1Term)) {
1828 // The only thing we have to watch out for here is to make sure that Pred2
1829 // doesn't have incoming edges from other blocks. If it does, the condition
1830 // doesn't dominate BB.
1831 if (!Pred2->getSinglePredecessor())
1832 return nullptr;
1833
1834 // If we found a conditional branch predecessor, make sure that it branches
1835 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
1836 if (Pred1Br->getSuccessor(0) == BB &&
1837 Pred1Br->getSuccessor(1) == Pred2) {
1838 IfTrue = Pred1;
1839 IfFalse = Pred2;
1840 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1841 Pred1Br->getSuccessor(1) == BB) {
1842 IfTrue = Pred2;
1843 IfFalse = Pred1;
1844 } else {
1845 // We know that one arm of the conditional goes to BB, so the other must
1846 // go somewhere unrelated, and this must not be an "if statement".
1847 return nullptr;
1848 }
1849
1850 return Pred1Br;
1851 }
1852
1853 if (!isa<UncondBrInst>(Pred1Term))
1854 return nullptr;
1855
1856 // Ok, if we got here, both predecessors end with an unconditional branch to
1857 // BB. Don't panic! If both blocks only have a single (identical)
1858 // predecessor, and THAT is a conditional branch, then we're all ok!
1859 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1860 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1861 return nullptr;
1862
1863 // Otherwise, if this is a conditional branch, then we can use it!
1864 CondBrInst *BI = dyn_cast<CondBrInst>(CommonPred->getTerminator());
1865 if (!BI) return nullptr;
1866
1867 if (BI->getSuccessor(0) == Pred1) {
1868 IfTrue = Pred1;
1869 IfFalse = Pred2;
1870 } else {
1871 IfTrue = Pred2;
1872 IfFalse = Pred1;
1873 }
1874 return BI;
1875}
1876
1878 Value *NewCond = PBI->getCondition();
1879 // If this is a "cmp" instruction, only used for branching (and nowhere
1880 // else), then we can simply invert the predicate.
1881 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1882 CmpInst *CI = cast<CmpInst>(NewCond);
1884 } else
1885 NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
1886
1887 PBI->setCondition(NewCond);
1888 PBI->swapSuccessors();
1889}
1890
1892 for (auto &BB : F) {
1893 auto *Term = BB.getTerminator();
1895 return false;
1896 }
1897 return true;
1898}
1899
1901 return Printable([BB](raw_ostream &OS) {
1902 if (!BB) {
1903 OS << "<nullptr>";
1904 return;
1905 }
1906 BB->printAsOperand(OS);
1907 });
1908}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static BasicBlock * SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB)
Remove redundant instructions within sequences of consecutive dbg.value instructions.
static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB)
Remove redundant undef dbg.assign intrinsic from an entry block using a forward scan.
static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock, BasicBlock *CallBrTarget, BasicBlock *Succ)
Helper function to update the cycle or loop information after inserting a new block between a callbr ...
static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, bool &HasLoopExit)
Update DominatorTree, LoopInfo, and LCCSA analysis information.
static BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName)
static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB)
Remove redundant dbg.value instructions using a forward scan.
static void SplitLandingPadPredecessorsImpl(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix1, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static cl::opt< unsigned > MaxDeoptOrUnreachableSuccessorCheckDepth("max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden, cl::desc("Set the maximum path length when checking whether a basic block " "is followed by a block that either has a terminating " "deoptimizing call or is terminated with an unreachable"))
static void emptyAndDetachBlock(BasicBlock *BB, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs)
Zap all the instructions in the block and replace them with an unreachable instruction and notify the...
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, Instruction *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
static bool hasReachableLoopEntryToHeader(const Loop &L, const DominatorTree &DT)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const uint32_t IV[8]
Definition blake3_impl.h:83
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
LLVM_ABI const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
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...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool empty() const
Definition BasicBlock.h:483
const Instruction & back() const
Definition BasicBlock.h:486
LLVM_ABI BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:687
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:484
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:482
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:659
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class represents a no-op cast from one type to another.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
void setSuccessor(unsigned i, BasicBlock *NewSucc)
BasicBlock * getSuccessor(unsigned i) const
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
Represents calls to the llvm.experimintal.convergence.* intrinsics.
DWARF expression.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Identifies a unique instance of a whole variable (discards/ignores fragment information).
Identifies a unique instance of a variable.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
iterator_range< iterator > children()
NodeT * getBlock() const
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
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:151
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.
This instruction extracts a struct member or array element value from an aggregate value.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
Module * getParent()
Get the module that this global value is contained inside of...
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool isSpecialTerminator() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:914
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
Provides a lazy, caching interface for making common memory aliasing information queries,...
LLVM_ABI void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
LLVM_ABI void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
LLVM_ABI void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was merged into To.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
LLVM_ABI void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:250
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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.
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
Return a value (possibly void), from a function.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
bool use_empty() const
Definition Value.h:346
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
@ Dead
Unused definition.
auto pred_end(const MachineBasicBlock *BB)
LLVM_ABI void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool hasOnlySimpleTerminator(const Function &F)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
constexpr from_range_t from_range
LLVM_ABI std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, BasicBlock::iterator SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
LLVM_ABI BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1746
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool HasLoopOrEntryConvergenceToken(const BasicBlock *BB)
Check if the given basic block contains any loop or entry convergent intrinsic instructions.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
LLVM_ABI bool MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl< BasicBlock * > &MergeBlocks, Loop *L=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
Merge block(s) sucessors, if possible.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad=nullptr, PHINode *LandingPadReplacement=nullptr, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
Split the edge connect the specficed blocks in the case that Succ is an Exception Handling Block.
auto succ_size(const MachineBasicBlock *BB)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:643
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 void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
LLVM_ABI void createPHIsForSplitLoopExit(ArrayRef< BasicBlock * > Preds, BasicBlock *SplitBB, BasicBlock *DestBB)
When a loop exit edge is split, LCSSA form may require new PHIs in the new exit block.
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *Until=nullptr)
Replaces all uses of OldPred with the NewPred block in all PHINodes in a block.
LLVM_ABI Printable printBasicBlock(const BasicBlock *BB)
Print BasicBlock BB as an operand or print "<nullptr>" if BB is a nullptr.
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
LLVM_ABI BasicBlock * SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx, BasicBlock *CallBrTarget=nullptr, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr edge.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()