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 // Recursively deleting a PHI may cause multiple PHIs to be deleted
217 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
219
220 bool Changed = false;
221 for (const auto &PHI : PHIs)
222 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHI.operator Value *()))
223 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
224
225 return Changed;
226}
227
229 LoopInfo *LI, MemorySSAUpdater *MSSAU,
231 bool PredecessorWithTwoSuccessors,
232 DominatorTree *DT) {
233 if (BB->hasAddressTaken())
234 return false;
235
236 // Can't merge if there are multiple predecessors, or no predecessors.
237 BasicBlock *PredBB = BB->getUniquePredecessor();
238 if (!PredBB) return false;
239
240 // Don't break self-loops.
241 if (PredBB == BB) return false;
242
243 // Don't break unwinding instructions or terminators with other side-effects.
244 Instruction *PTI = PredBB->getTerminator();
245 if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
246 return false;
247
248 // Can't merge if there are multiple distinct successors.
249 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
250 return false;
251
252 // Currently only allow PredBB to have two predecessors, one being BB.
253 // Update BI to branch to BB's only successor instead of BB.
254 CondBrInst *PredBB_BI;
255 BasicBlock *NewSucc = nullptr;
256 unsigned FallThruPath;
257 if (PredecessorWithTwoSuccessors) {
258 if (!(PredBB_BI = dyn_cast<CondBrInst>(PTI)))
259 return false;
261 if (!BB_JmpI)
262 return false;
263 NewSucc = BB_JmpI->getSuccessor();
264 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
265 }
266
267 // Can't merge if there is PHI loop.
268 for (PHINode &PN : BB->phis())
269 if (llvm::is_contained(PN.incoming_values(), &PN))
270 return false;
271
272 // Don't break if both the basic block and the predecessor contain loop or
273 // entry convergent intrinsics, since there may only be one convergence token
274 // per block.
277 return false;
278
279 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
280 << PredBB->getName() << "\n");
281
282 // Begin by getting rid of unneeded PHIs.
283 SmallVector<AssertingVH<Value>, 4> IncomingValues;
284 if (isa<PHINode>(BB->front())) {
285 for (PHINode &PN : BB->phis())
286 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
287 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
288 IncomingValues.push_back(PN.getIncomingValue(0));
289 FoldSingleEntryPHINodes(BB, MemDep);
290 }
291
292 if (DT) {
293 assert(!DTU && "cannot use both DT and DTU for updates");
294 DomTreeNode *PredNode = DT->getNode(PredBB);
295 DomTreeNode *BBNode = DT->getNode(BB);
296 if (PredNode) {
297 assert(BBNode && "PredNode unreachable but BBNode reachable?");
298 for (DomTreeNode *C : to_vector(BBNode->children()))
299 C->setIDom(PredNode);
300 }
301 }
302 // DTU update: Collect all the edges that exit BB.
303 // These dominator edges will be redirected from Pred.
304 std::vector<DominatorTree::UpdateType> Updates;
305 if (DTU) {
306 assert(!DT && "cannot use both DT and DTU for updates");
307 // To avoid processing the same predecessor more than once.
310 successors(PredBB));
311 Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
312 // Add insert edges first. Experimentally, for the particular case of two
313 // blocks that can be merged, with a single successor and single predecessor
314 // respectively, it is beneficial to have all insert updates first. Deleting
315 // edges first may lead to unreachable blocks, followed by inserting edges
316 // making the blocks reachable again. Such DT updates lead to high compile
317 // times. We add inserts before deletes here to reduce compile time.
318 for (BasicBlock *SuccOfBB : successors(BB))
319 // This successor of BB may already be a PredBB's successor.
320 if (!SuccsOfPredBB.contains(SuccOfBB))
321 if (SeenSuccs.insert(SuccOfBB).second)
322 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
323 SeenSuccs.clear();
324 for (BasicBlock *SuccOfBB : successors(BB))
325 if (SeenSuccs.insert(SuccOfBB).second)
326 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
327 Updates.push_back({DominatorTree::Delete, PredBB, BB});
328 }
329
330 Instruction *STI = BB->getTerminator();
331 Instruction *Start = &*BB->begin();
332 // If there's nothing to move, mark the starting instruction as the last
333 // instruction in the block. Terminator instruction is handled separately.
334 if (Start == STI)
335 Start = PTI;
336
337 // Move all definitions in the successor to the predecessor...
338 PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
339
340 if (MSSAU)
341 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
342
343 // Make all PHI nodes that referred to BB now refer to Pred as their
344 // source...
345 BB->replaceAllUsesWith(PredBB);
346
347 if (PredecessorWithTwoSuccessors) {
348 // Delete the unconditional branch from BB.
349 BB->back().eraseFromParent();
350 // Add unreachable to now empty BB.
351 new UnreachableInst(BB->getContext(), BB);
352
353 // Update branch in the predecessor.
354 PredBB_BI->setSuccessor(FallThruPath, NewSucc);
355 } else {
356 // Delete the unconditional branch from the predecessor.
357 PredBB->back().eraseFromParent();
358
359 // Move terminator instruction.
360 BB->back().moveBeforePreserving(*PredBB, PredBB->end());
361 // Add unreachable to now empty BB.
362 new UnreachableInst(BB->getContext(), BB);
363
364 // Terminator may be a memory accessing instruction too.
365 if (MSSAU)
367 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
368 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
369 }
370
371 // Inherit predecessors name if it exists.
372 if (!PredBB->hasName())
373 PredBB->takeName(BB);
374
375 if (LI)
376 LI->removeBlock(BB);
377
378 if (MemDep)
380
381 if (DTU)
382 DTU->applyUpdates(Updates);
383
384 if (DT) {
385 assert(succ_empty(BB) &&
386 "successors should have been transferred to PredBB");
387 DT->eraseNode(BB);
388 }
389
390 // Finally, erase the old block and update dominator info.
391 DeleteDeadBlock(BB, DTU);
392
393 return true;
394}
395
398 LoopInfo *LI) {
399 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
400
401 bool BlocksHaveBeenMerged = false;
402 while (!MergeBlocks.empty()) {
403 BasicBlock *BB = *MergeBlocks.begin();
404 BasicBlock *Dest = BB->getSingleSuccessor();
405 if (Dest && (!L || L->contains(Dest))) {
406 BasicBlock *Fold = Dest->getUniquePredecessor();
407 (void)Fold;
408 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
409 assert(Fold == BB &&
410 "Expecting BB to be unique predecessor of the Dest block");
411 MergeBlocks.erase(Dest);
412 BlocksHaveBeenMerged = true;
413 } else
414 MergeBlocks.erase(BB);
415 } else
416 MergeBlocks.erase(BB);
417 }
418 return BlocksHaveBeenMerged;
419}
420
421/// Remove redundant instructions within sequences of consecutive dbg.value
422/// instructions. This is done using a backward scan to keep the last dbg.value
423/// describing a specific variable/fragment.
424///
425/// BackwardScan strategy:
426/// ----------------------
427/// Given a sequence of consecutive DbgValueInst like this
428///
429/// dbg.value ..., "x", FragmentX1 (*)
430/// dbg.value ..., "y", FragmentY1
431/// dbg.value ..., "x", FragmentX2
432/// dbg.value ..., "x", FragmentX1 (**)
433///
434/// then the instruction marked with (*) can be removed (it is guaranteed to be
435/// obsoleted by the instruction marked with (**) as the latter instruction is
436/// describing the same variable using the same fragment info).
437///
438/// Possible improvements:
439/// - Check fully overlapping fragments and not only identical fragments.
443 for (auto &I : reverse(*BB)) {
444 for (DbgVariableRecord &DVR :
445 reverse(filterDbgVars(I.getDbgRecordRange()))) {
446 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
447 DVR.getDebugLoc()->getInlinedAt());
448 auto R = VariableSet.insert(Key);
449 // If the same variable fragment is described more than once it is enough
450 // to keep the last one (i.e. the first found since we for reverse
451 // iteration).
452 if (R.second)
453 continue;
454
455 if (DVR.isDbgAssign()) {
456 // Don't delete dbg.assign intrinsics that are linked to instructions.
457 if (!at::getAssignmentInsts(&DVR).empty())
458 continue;
459 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
460 }
461
462 ToBeRemoved.push_back(&DVR);
463 }
464 // Sequence with consecutive dbg.value instrs ended. Clear the map to
465 // restart identifying redundant instructions if case we find another
466 // dbg.value sequence.
467 VariableSet.clear();
468 }
469
470 for (auto &DVR : ToBeRemoved)
471 DVR->eraseFromParent();
472
473 return !ToBeRemoved.empty();
474}
475
476/// Remove redundant dbg.value instructions using a forward scan. This can
477/// remove a dbg.value instruction that is redundant due to indicating that a
478/// variable has the same value as already being indicated by an earlier
479/// dbg.value.
480///
481/// ForwardScan strategy:
482/// ---------------------
483/// Given two identical dbg.value instructions, separated by a block of
484/// instructions that isn't describing the same variable, like this
485///
486/// dbg.value X1, "x", FragmentX1 (**)
487/// <block of instructions, none being "dbg.value ..., "x", ...">
488/// dbg.value X1, "x", FragmentX1 (*)
489///
490/// then the instruction marked with (*) can be removed. Variable "x" is already
491/// described as being mapped to the SSA value X1.
492///
493/// Possible improvements:
494/// - Keep track of non-overlapping fragments.
496 bool RemovedAny = false;
498 std::pair<SmallVector<Value *, 4>, DIExpression *>, 4>
499 VariableMap;
500 for (auto &I : *BB) {
501 for (DbgVariableRecord &DVR :
502 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
503 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
504 continue;
505 DebugVariable Key(DVR.getVariable(), std::nullopt,
506 DVR.getDebugLoc()->getInlinedAt());
507 auto [VMI, Inserted] = VariableMap.try_emplace(Key);
508 // A dbg.assign with no linked instructions can be treated like a
509 // dbg.value (i.e. can be deleted).
510 bool IsDbgValueKind =
511 (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
512
513 // Update the map if we found a new value/expression describing the
514 // variable, or if the variable wasn't mapped already.
515 SmallVector<Value *, 4> Values(DVR.location_ops());
516 if (Inserted || VMI->second.first != Values ||
517 VMI->second.second != DVR.getExpression()) {
518 if (IsDbgValueKind)
519 VMI->second = {Values, DVR.getExpression()};
520 else
521 VMI->second = {Values, nullptr};
522 continue;
523 }
524 // Don't delete dbg.assign intrinsics that are linked to instructions.
525 if (!IsDbgValueKind)
526 continue;
527 // Found an identical mapping. Remember the instruction for later removal.
528 DVR.eraseFromParent();
529 RemovedAny = true;
530 }
531 }
532
533 return RemovedAny;
534}
535
536/// Remove redundant undef dbg.assign intrinsic from an entry block using a
537/// forward scan.
538/// Strategy:
539/// ---------------------
540/// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
541/// linked to an intrinsic, and don't share an aggregate variable with a debug
542/// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
543/// that come before non-undef debug intrinsics for the variable are
544/// deleted. Given:
545///
546/// dbg.assign undef, "x", FragmentX1 (*)
547/// <block of instructions, none being "dbg.value ..., "x", ...">
548/// dbg.value %V, "x", FragmentX2
549/// <block of instructions, none being "dbg.value ..., "x", ...">
550/// dbg.assign undef, "x", FragmentX1
551///
552/// then (only) the instruction marked with (*) can be removed.
553/// Possible improvements:
554/// - Keep track of non-overlapping fragments.
556 assert(BB->isEntryBlock() && "expected entry block");
557 bool RemovedAny = false;
558 DenseSet<DebugVariableAggregate> SeenDefForAggregate;
559
560 // Remove undef dbg.assign intrinsics that are encountered before
561 // any non-undef intrinsics from the entry block.
562 for (auto &I : *BB) {
563 for (DbgVariableRecord &DVR :
564 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
565 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
566 continue;
567 bool IsDbgValueKind =
568 (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
569
570 DebugVariableAggregate Aggregate(&DVR);
571 if (!SeenDefForAggregate.contains(Aggregate)) {
572 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
573 if (!IsKill) {
574 SeenDefForAggregate.insert(Aggregate);
575 } else if (DVR.isDbgAssign()) {
576 DVR.eraseFromParent();
577 RemovedAny = true;
578 }
579 }
580 }
581 }
582
583 return RemovedAny;
584}
585
587 bool MadeChanges = false;
588 // By using the "backward scan" strategy before the "forward scan" strategy we
589 // can remove both dbg.value (2) and (3) in a situation like this:
590 //
591 // (1) dbg.value V1, "x", DIExpression()
592 // ...
593 // (2) dbg.value V2, "x", DIExpression()
594 // (3) dbg.value V1, "x", DIExpression()
595 //
596 // The backward scan will remove (2), it is made obsolete by (3). After
597 // getting (2) out of the way, the foward scan will remove (3) since "x"
598 // already is described as having the value V1 at (1).
600 if (BB->isEntryBlock() &&
602 MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
604
605 if (MadeChanges)
606 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
607 << BB->getName() << "\n");
608 return MadeChanges;
609}
610
612 Instruction &I = *BI;
613 // Replaces all of the uses of the instruction with uses of the value
614 I.replaceAllUsesWith(V);
615
616 // Make sure to propagate a name if there is one already.
617 if (I.hasName() && !V->hasName())
618 V->takeName(&I);
619
620 // Delete the unnecessary instruction now...
621 BI = BI->eraseFromParent();
622}
623
625 Instruction *I) {
626 assert(I->getParent() == nullptr &&
627 "ReplaceInstWithInst: Instruction already inserted into basic block!");
628
629 // Copy debug location to newly added instruction, if it wasn't already set
630 // by the caller.
631 if (!I->getDebugLoc())
632 I->setDebugLoc(BI->getDebugLoc());
633
634 // Insert the new instruction into the basic block...
635 BasicBlock::iterator New = I->insertInto(BB, BI);
636
637 // Replace all uses of the old instruction, and delete it.
639
640 // Move BI back to point to the newly inserted instruction
641 BI = New;
642}
643
645 // Remember visited blocks to avoid infinite loop
647 unsigned Depth = 0;
649 VisitedBlocks.insert(BB).second) {
652 return true;
653 BB = BB->getUniqueSuccessor();
654 }
655 return false;
656}
657
659 BasicBlock::iterator BI(From);
660 ReplaceInstWithInst(From->getParent(), BI, To);
661}
662
664 LoopInfo *LI, MemorySSAUpdater *MSSAU,
665 const Twine &BBName) {
666 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
667
668 Instruction *LatchTerm = BB->getTerminator();
669
672
673 if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
674 // If this is a critical edge, let SplitKnownCriticalEdge do it.
675 return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
676 }
677
678 // If the edge isn't critical, then BB has a single successor or Succ has a
679 // single pred. Split the block.
680 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
681 // If the successor only has a single pred, split the top of the successor
682 // block.
683 assert(SP == BB && "CFG broken");
684 (void)SP;
685 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
686 return splitBlockBefore(Succ, &Succ->front(), &DTU, LI, MSSAU, BBName);
687 }
688
689 // Otherwise, if BB has a single successor, split it at the bottom of the
690 // block.
691 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
692 "Should have a single succ!");
693 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
694}
695
696/// Helper function to update the cycle or loop information after inserting a
697/// new block between a callbr instruction and one of its target blocks. Adds
698/// the new block to the innermost cycle or loop that the callbr instruction and
699/// the original target block share.
700/// \p LCI cycle or loop information to update
701/// \p CallBrBlock block containing the callbr instruction
702/// \p CallBrTarget new target block of the callbr instruction
703/// \p Succ original target block of the callbr instruction
704template <typename TI, typename T>
705static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock,
706 BasicBlock *CallBrTarget, BasicBlock *Succ) {
707 static_assert(std::is_same_v<TI, CycleInfo> || std::is_same_v<TI, LoopInfo>,
708 "type must be CycleInfo or LoopInfo");
709 if (!LCI)
710 return false;
711
712 T *LC;
713 if constexpr (std::is_same_v<TI, CycleInfo>)
714 LC = LCI->getSmallestCommonCycle(CallBrBlock, Succ);
715 else
716 LC = LCI->getSmallestCommonLoop(CallBrBlock, Succ);
717 if (!LC)
718 return false;
719
720 if constexpr (std::is_same_v<TI, CycleInfo>)
721 LCI->addBlockToCycle(CallBrTarget, LC);
722 else
723 LC->addBasicBlockToLoop(CallBrTarget, *LCI);
724
725 return true;
726}
727
729 unsigned SuccIdx, DomTreeUpdater *DTU,
730 CycleInfo *CI, LoopInfo *LI,
731 bool *UpdatedLI) {
732 CallBrInst *CallBr = dyn_cast<CallBrInst>(CallBrBlock->getTerminator());
733 assert(CallBr && "expected callbr terminator");
734 assert(SuccIdx < CallBr->getNumSuccessors() &&
735 Succ == CallBr->getSuccessor(SuccIdx) && "invalid successor index");
736
737 // Create a new block between callbr and the specified successor.
738 // splitBlockBefore cannot be re-used here since it cannot split if the split
739 // point is a PHI node (because BasicBlock::splitBasicBlockBefore cannot
740 // handle that). But we don't need to rewire every part of a potential PHI
741 // node. We only care about the edge between CallBrBlock and the original
742 // successor.
743 BasicBlock *CallBrTarget =
744 BasicBlock::Create(CallBrBlock->getContext(),
745 CallBrBlock->getName() + ".target." + Succ->getName(),
746 CallBrBlock->getParent());
747 // Rewire control flow from the new target block to the original successor.
748 Succ->replacePhiUsesWith(CallBrBlock, CallBrTarget);
749 // Rewire control flow from callbr to the new target block.
750 CallBr->setSuccessor(SuccIdx, CallBrTarget);
751 // Jump from the new target block to the original successor.
752 UncondBrInst::Create(Succ, CallBrTarget);
753
754 bool Updated =
755 updateCycleLoopInfo<LoopInfo, Loop>(LI, CallBrBlock, CallBrTarget, Succ);
756 if (UpdatedLI)
757 *UpdatedLI = Updated;
758 updateCycleLoopInfo<CycleInfo, Cycle>(CI, CallBrBlock, CallBrTarget, Succ);
759 if (DTU) {
760 DTU->applyUpdates({{DominatorTree::Insert, CallBrBlock, CallBrTarget}});
761 if (DTU->getDomTree().dominates(CallBrBlock, Succ)) {
762 if (!is_contained(successors(CallBrBlock), Succ))
763 DTU->applyUpdates({{DominatorTree::Delete, CallBrBlock, Succ}});
764 DTU->applyUpdates({{DominatorTree::Insert, CallBrTarget, Succ}});
765 }
766 }
767
768 return CallBrTarget;
769}
770
772 if (auto *II = dyn_cast<InvokeInst>(TI))
773 II->setUnwindDest(Succ);
774 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
775 CS->setUnwindDest(Succ);
776 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
777 CR->setUnwindDest(Succ);
778 else
779 llvm_unreachable("unexpected terminator instruction");
780}
781
783 BasicBlock *NewPred, PHINode *Until) {
784 int BBIdx = 0;
785 for (PHINode &PN : DestBB->phis()) {
786 // We manually update the LandingPadReplacement PHINode and it is the last
787 // PHI Node. So, if we find it, we are done.
788 if (Until == &PN)
789 break;
790
791 // Reuse the previous value of BBIdx if it lines up. In cases where we
792 // have multiple phi nodes with *lots* of predecessors, this is a speed
793 // win because we don't have to scan the PHI looking for TIBB. This
794 // happens because the BB list of PHI nodes are usually in the same
795 // order.
796 if (PN.getIncomingBlock(BBIdx) != OldPred)
797 BBIdx = PN.getBasicBlockIndex(OldPred);
798
799 assert(BBIdx != -1 && "Invalid PHI Index!");
800 PN.setIncomingBlock(BBIdx, NewPred);
801 }
802}
803
805 LandingPadInst *OriginalPad,
806 PHINode *LandingPadReplacement,
808 const Twine &BBName) {
809
810 auto PadInst = Succ->getFirstNonPHIIt();
811 if (!LandingPadReplacement && !PadInst->isEHPad())
812 return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
813
814 auto *LI = Options.LI;
816 // Check if extra modifications will be required to preserve loop-simplify
817 // form after splitting. If it would require splitting blocks with IndirectBr
818 // terminators, bail out if preserving loop-simplify form is requested.
819 if (Options.PreserveLoopSimplify && LI) {
820 if (Loop *BBLoop = LI->getLoopFor(BB)) {
821
822 // The only way that we can break LoopSimplify form by splitting a
823 // critical edge is when there exists some edge from BBLoop to Succ *and*
824 // the only edge into Succ from outside of BBLoop is that of NewBB after
825 // the split. If the first isn't true, then LoopSimplify still holds,
826 // NewBB is the new exit block and it has no non-loop predecessors. If the
827 // second isn't true, then Succ was not in LoopSimplify form prior to
828 // the split as it had a non-loop predecessor. In both of these cases,
829 // the predecessor must be directly in BBLoop, not in a subloop, or again
830 // LoopSimplify doesn't hold.
831 for (BasicBlock *P : predecessors(Succ)) {
832 if (P == BB)
833 continue; // The new block is known.
834 if (LI->getLoopFor(P) != BBLoop) {
835 // Loop is not in LoopSimplify form, no need to re simplify after
836 // splitting edge.
837 LoopPreds.clear();
838 break;
839 }
840 LoopPreds.push_back(P);
841 }
842 // Loop-simplify form can be preserved, if we can split all in-loop
843 // predecessors.
844 if (any_of(LoopPreds, [](BasicBlock *Pred) {
845 return isa<IndirectBrInst>(Pred->getTerminator());
846 })) {
847 return nullptr;
848 }
849 }
850 }
851
852 auto *NewBB =
853 BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
854 setUnwindEdgeTo(BB->getTerminator(), NewBB);
855 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
856
857 if (LandingPadReplacement) {
858 auto *NewLP = OriginalPad->clone();
859 auto *Terminator = UncondBrInst::Create(Succ, NewBB);
860 NewLP->insertBefore(Terminator->getIterator());
861 LandingPadReplacement->addIncoming(NewLP, NewBB);
862 } else {
863 Value *ParentPad = nullptr;
864 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
865 ParentPad = FuncletPad->getParentPad();
866 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
867 ParentPad = CatchSwitch->getParentPad();
868 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
869 ParentPad = CleanupPad->getParentPad();
870 else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
871 ParentPad = LandingPad->getParent();
872 else
873 llvm_unreachable("handling for other EHPads not implemented yet");
874
875 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
876 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
877 }
878
879 auto *DT = Options.DT;
880 auto *MSSAU = Options.MSSAU;
881 if (!DT && !LI)
882 return NewBB;
883
884 if (DT) {
885 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
887
888 Updates.push_back({DominatorTree::Insert, BB, NewBB});
889 Updates.push_back({DominatorTree::Insert, NewBB, Succ});
890 Updates.push_back({DominatorTree::Delete, BB, Succ});
891
892 DTU.applyUpdates(Updates);
893 DTU.flush();
894
895 if (MSSAU) {
896 MSSAU->applyUpdates(Updates, *DT);
897 if (VerifyMemorySSA)
898 MSSAU->getMemorySSA()->verifyMemorySSA();
899 }
900 }
901
902 if (LI) {
903 if (Loop *BBLoop = LI->getLoopFor(BB)) {
904 // If one or the other blocks were not in a loop, the new block is not
905 // either, and thus LI doesn't need to be updated.
906 if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
907 if (BBLoop == SuccLoop) {
908 // Both in the same loop, the NewBB joins loop.
909 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
910 } else if (BBLoop->contains(SuccLoop)) {
911 // Edge from an outer loop to an inner loop. Add to the outer loop.
912 BBLoop->addBasicBlockToLoop(NewBB, *LI);
913 } else if (SuccLoop->contains(BBLoop)) {
914 // Edge from an inner loop to an outer loop. Add to the outer loop.
915 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
916 } else {
917 // Edge from two loops with no containment relation. Because these
918 // are natural loops, we know that the destination block must be the
919 // header of its loop (adding a branch into a loop elsewhere would
920 // create an irreducible loop).
921 assert(SuccLoop->getHeader() == Succ &&
922 "Should not create irreducible loops!");
923 if (Loop *P = SuccLoop->getParentLoop())
924 P->addBasicBlockToLoop(NewBB, *LI);
925 }
926 }
927
928 // If BB is in a loop and Succ is outside of that loop, we may need to
929 // update LoopSimplify form and LCSSA form.
930 if (!BBLoop->contains(Succ)) {
931 assert(!BBLoop->contains(NewBB) &&
932 "Split point for loop exit is contained in loop!");
933
934 // Update LCSSA form in the newly created exit block.
935 if (Options.PreserveLCSSA) {
936 createPHIsForSplitLoopExit(BB, NewBB, Succ);
937 }
938
939 if (!LoopPreds.empty()) {
941 Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
942 if (Options.PreserveLCSSA)
943 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
944 }
945 }
946 }
947 }
948
949 return NewBB;
950}
951
953 BasicBlock *SplitBB, BasicBlock *DestBB) {
954 // SplitBB shouldn't have anything non-trivial in it yet.
955 assert((&*SplitBB->getFirstNonPHIIt() == SplitBB->getTerminator() ||
956 SplitBB->isLandingPad()) &&
957 "SplitBB has non-PHI nodes!");
958
959 // For each PHI in the destination block.
960 for (PHINode &PN : DestBB->phis()) {
961 int Idx = PN.getBasicBlockIndex(SplitBB);
962 assert(Idx >= 0 && "Invalid Block Index");
963 Value *V = PN.getIncomingValue(Idx);
964
965 // If the input is a PHI which already satisfies LCSSA, don't create
966 // a new one.
967 if (const PHINode *VP = dyn_cast<PHINode>(V))
968 if (VP->getParent() == SplitBB)
969 continue;
970
971 // Otherwise a new PHI is needed. Create one and populate it.
972 PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
973 BasicBlock::iterator InsertPos =
974 SplitBB->isLandingPad() ? SplitBB->begin()
975 : SplitBB->getTerminator()->getIterator();
976 NewPN->insertBefore(InsertPos);
977 for (BasicBlock *BB : Preds)
978 NewPN->addIncoming(V, BB);
979
980 // Update the original PHI.
981 PN.setIncomingValue(Idx, NewPN);
982 }
983}
984
985unsigned
988 unsigned NumBroken = 0;
989 for (BasicBlock &BB : F) {
990 Instruction *TI = BB.getTerminator();
991 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
992 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
993 if (SplitCriticalEdge(TI, i, Options))
994 ++NumBroken;
995 }
996 return NumBroken;
997}
998
1000 DomTreeUpdater *DTU, DominatorTree *DT,
1001 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1002 const Twine &BBName) {
1003 BasicBlock::iterator SplitIt = SplitPt;
1004 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
1005 ++SplitIt;
1006 assert(SplitIt != SplitPt->getParent()->end());
1007 }
1008 std::string Name = BBName.str();
1009 BasicBlock *New = Old->splitBasicBlock(
1010 SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
1011
1012 // The new block lives in whichever loop the old one did. This preserves
1013 // LCSSA as well, because we force the split point to be after any PHI nodes.
1014 if (LI)
1015 if (Loop *L = LI->getLoopFor(Old))
1016 L->addBasicBlockToLoop(New, *LI);
1017
1018 if (DTU) {
1020 // Old dominates New. New node dominates all other nodes dominated by Old.
1021 SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1022 Updates.push_back({DominatorTree::Insert, Old, New});
1023 Updates.reserve(Updates.size() + 2 * succ_size(New));
1024 for (BasicBlock *SuccessorOfOld : successors(New))
1025 if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
1026 Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
1027 Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1028 }
1029
1030 DTU->applyUpdates(Updates);
1031 } else if (DT)
1032 // Old dominates New. New node dominates all other nodes dominated by Old.
1033 if (DomTreeNode *OldNode = DT->getNode(Old)) {
1034 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1035
1036 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
1037 for (DomTreeNode *I : Children)
1038 DT->changeImmediateDominator(I, NewNode);
1039 }
1040
1041 // Move MemoryAccesses still tracked in Old, but part of New now.
1042 // Update accesses in successor blocks accordingly.
1043 if (MSSAU)
1044 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
1045
1046 return New;
1047}
1048
1050 DominatorTree *DT, LoopInfo *LI,
1051 MemorySSAUpdater *MSSAU, const Twine &BBName) {
1052 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName);
1053}
1055 DomTreeUpdater *DTU, LoopInfo *LI,
1056 MemorySSAUpdater *MSSAU, const Twine &BBName) {
1057 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName);
1058}
1059
1061 const DominatorTree &DT) {
1062 for (const BasicBlock *Pred : predecessors(L.getHeader()))
1063 if (!L.contains(Pred) && DT.isReachableFromEntry(Pred))
1064 return true;
1065
1066 return false;
1067}
1068
1069/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1070/// Invalidates DFS Numbering when DTU or DT is provided.
1073 DomTreeUpdater *DTU, DominatorTree *DT,
1074 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1075 bool PreserveLCSSA, bool &HasLoopExit) {
1076 // Update dominator tree if available.
1077 if (DTU) {
1078 // Recalculation of DomTree is needed when updating a forward DomTree and
1079 // the Entry BB is replaced.
1080 if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1081 // The entry block was removed and there is no external interface for
1082 // the dominator tree to be notified of this change. In this corner-case
1083 // we recalculate the entire tree.
1084 DTU->recalculate(*NewBB->getParent());
1085 } else {
1086 // Split block expects NewBB to have a non-empty set of predecessors.
1088 SmallPtrSet<BasicBlock *, 8> UniquePreds;
1089 Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1090 Updates.reserve(Updates.size() + 2 * Preds.size());
1091 for (auto *Pred : Preds)
1092 if (UniquePreds.insert(Pred).second) {
1093 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1094 Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1095 }
1096 DTU->applyUpdates(Updates);
1097 }
1098 } else if (DT) {
1099 if (OldBB == DT->getRootNode()->getBlock()) {
1100 assert(NewBB->isEntryBlock());
1101 DT->setNewRoot(NewBB);
1102 } else {
1103 // Split block expects NewBB to have a non-empty set of predecessors.
1104 DT->splitBlock(NewBB);
1105 }
1106 }
1107
1108 // Update MemoryPhis after split if MemorySSA is available
1109 if (MSSAU)
1110 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1111
1112 // The rest of the logic is only relevant for updating the loop structures.
1113 if (!LI)
1114 return;
1115
1116 if (DTU && DTU->hasDomTree())
1117 DT = &DTU->getDomTree();
1118 assert(DT && "DT should be available to update LoopInfo!");
1119 Loop *L = LI->getLoopFor(OldBB);
1120
1121 // If we need to preserve loop analyses, collect some information about how
1122 // this split will affect loops.
1123 bool IsLoopEntry = !!L;
1124 bool SplitMakesNewLoopHeader = false;
1125 for (BasicBlock *Pred : Preds) {
1126 // Preds that are not reachable from entry should not be used to identify if
1127 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1128 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1129 // as true and make the NewBB the header of some loop. This breaks LI.
1130 if (!DT->isReachableFromEntry(Pred))
1131 continue;
1132 // If we need to preserve LCSSA, determine if any of the preds is a loop
1133 // exit.
1134 if (PreserveLCSSA)
1135 if (Loop *PL = LI->getLoopFor(Pred))
1136 if (!PL->contains(OldBB))
1137 HasLoopExit = true;
1138
1139 // If we need to preserve LoopInfo, note whether any of the preds crosses
1140 // an interesting loop boundary.
1141 if (!L)
1142 continue;
1143 if (L->contains(Pred))
1144 IsLoopEntry = false;
1145 else
1146 SplitMakesNewLoopHeader = true;
1147 }
1148
1149 // Unless we have a loop for OldBB, nothing else to do here.
1150 if (!L)
1151 return;
1152
1153 if (IsLoopEntry) {
1154 // Add the new block to the nearest enclosing loop (and not an adjacent
1155 // loop). To find this, examine each of the predecessors and determine which
1156 // loops enclose them, and select the most-nested loop which contains the
1157 // loop containing the block being split.
1158 Loop *InnermostPredLoop = nullptr;
1159 for (BasicBlock *Pred : Preds) {
1160 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1161 // Seek a loop which actually contains the block being split (to avoid
1162 // adjacent loops).
1163 while (PredLoop && !PredLoop->contains(OldBB))
1164 PredLoop = PredLoop->getParentLoop();
1165
1166 // Select the most-nested of these loops which contains the block.
1167 if (PredLoop && PredLoop->contains(OldBB) &&
1168 (!InnermostPredLoop ||
1169 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1170 InnermostPredLoop = PredLoop;
1171 }
1172 }
1173
1174 if (InnermostPredLoop)
1175 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1176 } else {
1177 L->addBasicBlockToLoop(NewBB, *LI);
1178 if (SplitMakesNewLoopHeader) {
1179 // The old header might still have a loop entry. If so the loop becomes
1180 // irreducible and must be erased. Otherwise the NewBB becomes the loop
1181 // header.
1182 if (hasReachableLoopEntryToHeader(*L, *DT))
1183 LI->erase(L);
1184 else
1185 L->moveToHeader(NewBB);
1186 }
1187 }
1188}
1189
1191 BasicBlock::iterator SplitPt,
1192 DomTreeUpdater *DTU, LoopInfo *LI,
1193 MemorySSAUpdater *MSSAU,
1194 const Twine &BBName) {
1195 BasicBlock::iterator SplitIt = SplitPt;
1196 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1197 ++SplitIt;
1200 SplitIt, BBName.isTriviallyEmpty() ? Old->getName() + ".split" : BBName);
1201
1202 bool HasLoopExit = false;
1203 UpdateAnalysisInformation(Old, New, Preds, DTU, nullptr, LI, MSSAU, false,
1204 HasLoopExit);
1205
1206 return New;
1207}
1208
1209/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1210/// This also updates AliasAnalysis, if available.
1211static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1213 bool HasLoopExit) {
1214 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1216 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1217 PHINode *PN = cast<PHINode>(I++);
1218
1219 // Check to see if all of the values coming in are the same. If so, we
1220 // don't need to create a new PHI node, unless it's needed for LCSSA.
1221 Value *InVal = nullptr;
1222 if (!HasLoopExit) {
1223 InVal = PN->getIncomingValueForBlock(Preds[0]);
1224 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1225 if (!PredSet.count(PN->getIncomingBlock(i)))
1226 continue;
1227 if (!InVal)
1228 InVal = PN->getIncomingValue(i);
1229 else if (InVal != PN->getIncomingValue(i)) {
1230 InVal = nullptr;
1231 break;
1232 }
1233 }
1234 }
1235
1236 if (InVal) {
1237 // If all incoming values for the new PHI would be the same, just don't
1238 // make a new PHI. Instead, just remove the incoming values from the old
1239 // PHI.
1241 [&](unsigned Idx) {
1242 return PredSet.contains(PN->getIncomingBlock(Idx));
1243 },
1244 /* DeletePHIIfEmpty */ false);
1245
1246 // Add an incoming value to the PHI node in the loop for the preheader
1247 // edge.
1248 PN->addIncoming(InVal, NewBB);
1249 continue;
1250 }
1251
1252 // If the values coming into the block are not the same, we need a new
1253 // PHI.
1254 // Create the new PHI node, insert it into NewBB at the end of the block
1255 PHINode *NewPHI =
1256 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
1257
1258 // NOTE! This loop walks backwards for a reason! First off, this minimizes
1259 // the cost of removal if we end up removing a large number of values, and
1260 // second off, this ensures that the indices for the incoming values aren't
1261 // invalidated when we remove one.
1262 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1263 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1264 if (PredSet.count(IncomingBB)) {
1265 Value *V = PN->removeIncomingValue(i, false);
1266 NewPHI->addIncoming(V, IncomingBB);
1267 }
1268 }
1269
1270 PN->addIncoming(NewPHI, NewBB);
1271 }
1272}
1273
1275 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1276 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1277 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1278 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1279
1280static BasicBlock *
1282 const char *Suffix, DomTreeUpdater *DTU,
1283 DominatorTree *DT, LoopInfo *LI,
1284 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1285 // Do not attempt to split that which cannot be split.
1286 if (!BB->canSplitPredecessors())
1287 return nullptr;
1288
1289 // For the landingpads we need to act a bit differently.
1290 // Delegate this work to the SplitLandingPadPredecessors.
1291 if (BB->isLandingPad()) {
1293 std::string NewName = std::string(Suffix) + ".split-lp";
1294
1295 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1296 DTU, DT, LI, MSSAU, PreserveLCSSA);
1297 return NewBBs[0];
1298 }
1299
1300 // Create new basic block, insert right before the original block.
1302 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1303
1304 // The new block unconditionally branches to the old block.
1305 UncondBrInst *BI = UncondBrInst::Create(BB, NewBB);
1306
1307 Loop *L = nullptr;
1308 BasicBlock *OldLatch = nullptr;
1309 // Splitting the predecessors of a loop header creates a preheader block.
1310 if (LI && LI->isLoopHeader(BB)) {
1311 L = LI->getLoopFor(BB);
1312 // Using the loop start line number prevents debuggers stepping into the
1313 // loop body for this instruction.
1314 BI->setDebugLoc(L->getStartLoc());
1315
1316 // If BB is the header of the Loop, it is possible that the loop is
1317 // modified, such that the current latch does not remain the latch of the
1318 // loop. If that is the case, the loop metadata from the current latch needs
1319 // to be applied to the new latch.
1320 OldLatch = L->getLoopLatch();
1321 } else
1322 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1323
1324 // Move the edges from Preds to point to NewBB instead of BB.
1325 for (BasicBlock *Pred : Preds) {
1326 // This is slightly more strict than necessary; the minimum requirement
1327 // is that there be no more than one indirectbr branching to BB. And
1328 // all BlockAddress uses would need to be updated.
1329 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1330 "Cannot split an edge from an IndirectBrInst");
1331 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1332 }
1333
1334 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1335 // node becomes an incoming value for BB's phi node. However, if the Preds
1336 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1337 // account for the newly created predecessor.
1338 if (Preds.empty()) {
1339 // Insert dummy values as the incoming value.
1340 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1341 cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1342 }
1343
1344 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1345 bool HasLoopExit = false;
1346 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1347 HasLoopExit);
1348
1349 if (!Preds.empty()) {
1350 // Update the PHI nodes in BB with the values coming from NewBB.
1351 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1352 }
1353
1354 if (OldLatch) {
1355 BasicBlock *NewLatch = L->getLoopLatch();
1356 if (NewLatch != OldLatch) {
1357 MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1358 NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
1359 // It's still possible that OldLatch is the latch of another inner loop,
1360 // in which case we do not remove the metadata.
1361 Loop *IL = LI->getLoopFor(OldLatch);
1362 if (IL && IL->getLoopLatch() != OldLatch)
1363 OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1364 }
1365 }
1366
1367 return NewBB;
1368}
1369
1372 const char *Suffix, DominatorTree *DT,
1373 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1374 bool PreserveLCSSA) {
1375 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1376 MSSAU, PreserveLCSSA);
1377}
1380 const char *Suffix,
1381 DomTreeUpdater *DTU, LoopInfo *LI,
1382 MemorySSAUpdater *MSSAU,
1383 bool PreserveLCSSA) {
1384 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1385 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1386}
1387
1389 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1390 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1391 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1392 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1393 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1394
1395 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1396 // it right before the original block.
1397 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1398 OrigBB->getName() + Suffix1,
1399 OrigBB->getParent(), OrigBB);
1400 NewBBs.push_back(NewBB1);
1401
1402 // The new block unconditionally branches to the old block.
1403 UncondBrInst *BI1 = UncondBrInst::Create(OrigBB, NewBB1);
1404 BI1->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1405
1406 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1407 for (BasicBlock *Pred : Preds) {
1408 // This is slightly more strict than necessary; the minimum requirement
1409 // is that there be no more than one indirectbr branching to BB. And
1410 // all BlockAddress uses would need to be updated.
1411 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1412 "Cannot split an edge from an IndirectBrInst");
1413 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1414 }
1415
1416 bool HasLoopExit = false;
1417 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1418 PreserveLCSSA, HasLoopExit);
1419
1420 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1421 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1422
1423 // Move the remaining edges from OrigBB to point to NewBB2.
1424 SmallVector<BasicBlock*, 8> NewBB2Preds;
1425 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1426 i != e; ) {
1427 BasicBlock *Pred = *i++;
1428 if (Pred == NewBB1) continue;
1429 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1430 "Cannot split an edge from an IndirectBrInst");
1431 NewBB2Preds.push_back(Pred);
1432 e = pred_end(OrigBB);
1433 }
1434
1435 BasicBlock *NewBB2 = nullptr;
1436 if (!NewBB2Preds.empty()) {
1437 // Create another basic block for the rest of OrigBB's predecessors.
1438 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1439 OrigBB->getName() + Suffix2,
1440 OrigBB->getParent(), OrigBB);
1441 NewBBs.push_back(NewBB2);
1442
1443 // The new block unconditionally branches to the old block.
1444 UncondBrInst *BI2 = UncondBrInst::Create(OrigBB, NewBB2);
1445 BI2->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1446
1447 // Move the remaining edges from OrigBB to point to NewBB2.
1448 for (BasicBlock *NewBB2Pred : NewBB2Preds)
1449 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1450
1451 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1452 HasLoopExit = false;
1453 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1454 PreserveLCSSA, HasLoopExit);
1455
1456 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1457 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1458 }
1459
1460 LandingPadInst *LPad = OrigBB->getLandingPadInst();
1461 Instruction *Clone1 = LPad->clone();
1462 Clone1->setName(Twine("lpad") + Suffix1);
1463 Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1464
1465 if (NewBB2) {
1466 Instruction *Clone2 = LPad->clone();
1467 Clone2->setName(Twine("lpad") + Suffix2);
1468 Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1469
1470 // Create a PHI node for the two cloned landingpad instructions only
1471 // if the original landingpad instruction has some uses.
1472 if (!LPad->use_empty()) {
1473 assert(!LPad->getType()->isTokenTy() &&
1474 "Split cannot be applied if LPad is token type. Otherwise an "
1475 "invalid PHINode of token type would be created.");
1476 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
1477 PN->addIncoming(Clone1, NewBB1);
1478 PN->addIncoming(Clone2, NewBB2);
1479 LPad->replaceAllUsesWith(PN);
1480 }
1481 LPad->eraseFromParent();
1482 } else {
1483 // There is no second clone. Just replace the landing pad with the first
1484 // clone.
1485 LPad->replaceAllUsesWith(Clone1);
1486 LPad->eraseFromParent();
1487 }
1488}
1489
1492 const char *Suffix1, const char *Suffix2,
1494 DomTreeUpdater *DTU, LoopInfo *LI,
1495 MemorySSAUpdater *MSSAU,
1496 bool PreserveLCSSA) {
1497 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1498 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1499 PreserveLCSSA);
1500}
1501
1503 BasicBlock *Pred,
1504 DomTreeUpdater *DTU) {
1505 Instruction *UncondBranch = Pred->getTerminator();
1506 // Clone the return and add it to the end of the predecessor.
1507 Instruction *NewRet = RI->clone();
1508 NewRet->insertInto(Pred, Pred->end());
1509
1510 // If the return instruction returns a value, and if the value was a
1511 // PHI node in "BB", propagate the right value into the return.
1512 for (Use &Op : NewRet->operands()) {
1513 Value *V = Op;
1514 Instruction *NewBC = nullptr;
1515 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1516 // Return value might be bitcasted. Clone and insert it before the
1517 // return instruction.
1518 V = BCI->getOperand(0);
1519 NewBC = BCI->clone();
1520 NewBC->insertInto(Pred, NewRet->getIterator());
1521 Op = NewBC;
1522 }
1523
1524 Instruction *NewEV = nullptr;
1526 V = EVI->getOperand(0);
1527 NewEV = EVI->clone();
1528 if (NewBC) {
1529 NewBC->setOperand(0, NewEV);
1530 NewEV->insertInto(Pred, NewBC->getIterator());
1531 } else {
1532 NewEV->insertInto(Pred, NewRet->getIterator());
1533 Op = NewEV;
1534 }
1535 }
1536
1537 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1538 if (PN->getParent() == BB) {
1539 if (NewEV) {
1540 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1541 } else if (NewBC)
1542 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1543 else
1544 Op = PN->getIncomingValueForBlock(Pred);
1545 }
1546 }
1547 }
1548
1549 // Update any PHI nodes in the returning block to realize that we no
1550 // longer branch to them.
1551 BB->removePredecessor(Pred);
1552 UncondBranch->eraseFromParent();
1553
1554 if (DTU)
1555 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1556
1557 return cast<ReturnInst>(NewRet);
1558}
1559
1561 BasicBlock::iterator SplitBefore,
1562 bool Unreachable,
1563 MDNode *BranchWeights,
1564 DomTreeUpdater *DTU, LoopInfo *LI,
1565 BasicBlock *ThenBlock) {
1567 Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1568 /* UnreachableThen */ Unreachable,
1569 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1570 return ThenBlock->getTerminator();
1571}
1572
1574 BasicBlock::iterator SplitBefore,
1575 bool Unreachable,
1576 MDNode *BranchWeights,
1577 DomTreeUpdater *DTU, LoopInfo *LI,
1578 BasicBlock *ElseBlock) {
1580 Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1581 /* UnreachableThen */ false,
1582 /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1583 return ElseBlock->getTerminator();
1584}
1585
1587 Instruction **ThenTerm,
1588 Instruction **ElseTerm,
1589 MDNode *BranchWeights,
1590 DomTreeUpdater *DTU, LoopInfo *LI) {
1591 BasicBlock *ThenBlock = nullptr;
1592 BasicBlock *ElseBlock = nullptr;
1594 Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1595 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1596
1597 *ThenTerm = ThenBlock->getTerminator();
1598 *ElseTerm = ElseBlock->getTerminator();
1599}
1600
1602 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1603 BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1604 MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1605 assert((ThenBlock || ElseBlock) &&
1606 "At least one branch block must be created");
1607 assert((!UnreachableThen || !UnreachableElse) &&
1608 "Split block tail must be reachable");
1609
1611 SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1612 BasicBlock *Head = SplitBefore->getParent();
1613 if (DTU) {
1614 UniqueOrigSuccessors.insert_range(successors(Head));
1615 Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1616 }
1617
1618 LLVMContext &C = Head->getContext();
1619 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1620 BasicBlock *TrueBlock = Tail;
1621 BasicBlock *FalseBlock = Tail;
1622 bool ThenToTailEdge = false;
1623 bool ElseToTailEdge = false;
1624
1625 // Encapsulate the logic around creation/insertion/etc of a new block.
1626 auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1627 bool &ToTailEdge) {
1628 if (PBB == nullptr)
1629 return; // Do not create/insert a block.
1630
1631 if (*PBB)
1632 BB = *PBB; // Caller supplied block, use it.
1633 else {
1634 // Create a new block.
1635 BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1636 if (Unreachable)
1637 (void)new UnreachableInst(C, BB);
1638 else {
1639 (void)UncondBrInst::Create(Tail, BB);
1640 ToTailEdge = true;
1641 }
1642 BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1643 // Pass the new block back to the caller.
1644 *PBB = BB;
1645 }
1646 };
1647
1648 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1649 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1650
1651 Instruction *HeadOldTerm = Head->getTerminator();
1652 CondBrInst *HeadNewTerm = CondBrInst::Create(Cond, TrueBlock, FalseBlock);
1653 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1654 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1655
1656 if (DTU) {
1657 Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1658 Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1659 if (ThenToTailEdge)
1660 Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1661 if (ElseToTailEdge)
1662 Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1663 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1664 Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1665 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1666 Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1667 DTU->applyUpdates(Updates);
1668 }
1669
1670 if (LI) {
1671 if (Loop *L = LI->getLoopFor(Head); L) {
1672 if (ThenToTailEdge)
1673 L->addBasicBlockToLoop(TrueBlock, *LI);
1674 if (ElseToTailEdge)
1675 L->addBasicBlockToLoop(FalseBlock, *LI);
1676 L->addBasicBlockToLoop(Tail, *LI);
1677 }
1678 }
1679}
1680
1681std::pair<Instruction *, Value *>
1683 BasicBlock::iterator SplitBefore) {
1684 BasicBlock *LoopPred = SplitBefore->getParent();
1685 BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1686 BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1687
1688 auto *Ty = End->getType();
1689 auto &DL = SplitBefore->getDataLayout();
1690 const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1691
1692 IRBuilder<> Builder(LoopBody->getTerminator());
1693 auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1694 auto *IVNext =
1695 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1696 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1697 auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1698 IV->getName() + ".check");
1699 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1700 LoopBody->getTerminator()->eraseFromParent();
1701
1702 // Populate the IV PHI.
1703 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1704 IV->addIncoming(IVNext, LoopBody);
1705
1706 return std::make_pair(&*LoopBody->getFirstNonPHIIt(), IV);
1707}
1708
1710 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
1711 std::function<void(IRBuilderBase &, Value *)> Func) {
1712
1713 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1714
1715 if (EC.isScalable()) {
1716 Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1717
1718 auto [BodyIP, Index] =
1719 SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1720
1721 IRB.SetInsertPoint(BodyIP);
1722 Func(IRB, Index);
1723 return;
1724 }
1725
1726 unsigned Num = EC.getFixedValue();
1727 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1728 IRB.SetInsertPoint(InsertBefore);
1729 Func(IRB, ConstantInt::get(IndexTy, Idx));
1730 }
1731}
1732
1734 Value *EVL, BasicBlock::iterator InsertBefore,
1735 std::function<void(IRBuilderBase &, Value *)> Func) {
1736
1737 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1738 Type *Ty = EVL->getType();
1739
1740 if (!isa<ConstantInt>(EVL)) {
1741 auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1742 IRB.SetInsertPoint(BodyIP);
1743 Func(IRB, Index);
1744 return;
1745 }
1746
1747 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1748 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1749 IRB.SetInsertPoint(InsertBefore);
1750 Func(IRB, ConstantInt::get(Ty, Idx));
1751 }
1752}
1753
1755 BasicBlock *&IfFalse) {
1756 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1757 BasicBlock *Pred1 = nullptr;
1758 BasicBlock *Pred2 = nullptr;
1759
1760 if (SomePHI) {
1761 if (SomePHI->getNumIncomingValues() != 2)
1762 return nullptr;
1763 Pred1 = SomePHI->getIncomingBlock(0);
1764 Pred2 = SomePHI->getIncomingBlock(1);
1765 } else {
1766 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1767 if (PI == PE) // No predecessor
1768 return nullptr;
1769 Pred1 = *PI++;
1770 if (PI == PE) // Only one predecessor
1771 return nullptr;
1772 Pred2 = *PI++;
1773 if (PI != PE) // More than two predecessors
1774 return nullptr;
1775 }
1776
1777 Instruction *Pred1Term = Pred1->getTerminator();
1778 Instruction *Pred2Term = Pred2->getTerminator();
1779
1780 // Eliminate code duplication by ensuring that Pred1Br is conditional if
1781 // either are.
1782 if (isa<CondBrInst>(Pred2Term)) {
1783 // If both branches are conditional, we don't have an "if statement". In
1784 // reality, we could transform this case, but since the condition will be
1785 // required anyway, we stand no chance of eliminating it, so the xform is
1786 // probably not profitable.
1787 if (isa<CondBrInst>(Pred1Term))
1788 return nullptr;
1789
1790 std::swap(Pred1, Pred2);
1791 std::swap(Pred1Term, Pred2Term);
1792 }
1793
1794 // We can only handle branches. Other control flow will be lowered to
1795 // branches if possible anyway.
1796 if (!isa<UncondBrInst>(Pred2Term))
1797 return nullptr;
1798
1799 if (auto *Pred1Br = dyn_cast<CondBrInst>(Pred1Term)) {
1800 // The only thing we have to watch out for here is to make sure that Pred2
1801 // doesn't have incoming edges from other blocks. If it does, the condition
1802 // doesn't dominate BB.
1803 if (!Pred2->getSinglePredecessor())
1804 return nullptr;
1805
1806 // If we found a conditional branch predecessor, make sure that it branches
1807 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
1808 if (Pred1Br->getSuccessor(0) == BB &&
1809 Pred1Br->getSuccessor(1) == Pred2) {
1810 IfTrue = Pred1;
1811 IfFalse = Pred2;
1812 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1813 Pred1Br->getSuccessor(1) == BB) {
1814 IfTrue = Pred2;
1815 IfFalse = Pred1;
1816 } else {
1817 // We know that one arm of the conditional goes to BB, so the other must
1818 // go somewhere unrelated, and this must not be an "if statement".
1819 return nullptr;
1820 }
1821
1822 return Pred1Br;
1823 }
1824
1825 if (!isa<UncondBrInst>(Pred1Term))
1826 return nullptr;
1827
1828 // Ok, if we got here, both predecessors end with an unconditional branch to
1829 // BB. Don't panic! If both blocks only have a single (identical)
1830 // predecessor, and THAT is a conditional branch, then we're all ok!
1831 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1832 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1833 return nullptr;
1834
1835 // Otherwise, if this is a conditional branch, then we can use it!
1836 CondBrInst *BI = dyn_cast<CondBrInst>(CommonPred->getTerminator());
1837 if (!BI) return nullptr;
1838
1839 if (BI->getSuccessor(0) == Pred1) {
1840 IfTrue = Pred1;
1841 IfFalse = Pred2;
1842 } else {
1843 IfTrue = Pred2;
1844 IfFalse = Pred1;
1845 }
1846 return BI;
1847}
1848
1850 Value *NewCond = PBI->getCondition();
1851 // If this is a "cmp" instruction, only used for branching (and nowhere
1852 // else), then we can simply invert the predicate.
1853 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1854 CmpInst *CI = cast<CmpInst>(NewCond);
1856 } else
1857 NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
1858
1859 PBI->setCondition(NewCond);
1860 PBI->swapSuccessors();
1861}
1862
1864 for (auto &BB : F) {
1865 auto *Term = BB.getTerminator();
1867 return false;
1868 }
1869 return true;
1870}
1871
1873 return Printable([BB](raw_ostream &OS) {
1874 if (!BB) {
1875 OS << "<nullptr>";
1876 return;
1877 }
1878 BB->printAsOperand(OS);
1879 });
1880}
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:114
static const uint32_t IV[8]
Definition blake3_impl.h:83
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
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 void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
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:664
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:768
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
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:256
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
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:159
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:207
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:2811
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:908
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1080
Provides a lazy, caching interface for making common memory aliasing information queries,...
void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
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:291
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:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:440
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:347
bool hasName() const
Definition Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
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:153
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 @...
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 BasicBlock * SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr edge.
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:634
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 bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Examine each PHI in the given block and delete it if it is dead.
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:408
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:207
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...
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:84
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:105
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 bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=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
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()