LLVM 22.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/DebugInfo.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/Debug.h"
45#include <cassert>
46#include <cstdint>
47#include <string>
48#include <utility>
49#include <vector>
50
51using namespace llvm;
52
53#define DEBUG_TYPE "basicblock-utils"
54
56 "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
57 cl::desc("Set the maximum path length when checking whether a basic block "
58 "is followed by a block that either has a terminating "
59 "deoptimizing call or is terminated with an unreachable"));
60
64 bool KeepOneInputPHIs) {
65 for (auto *BB : BBs) {
66 // Loop through all of our successors and make sure they know that one
67 // of their predecessors is going away.
68 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
69 for (BasicBlock *Succ : successors(BB)) {
70 Succ->removePredecessor(BB, KeepOneInputPHIs);
71 if (Updates && UniqueSuccessors.insert(Succ).second)
72 Updates->push_back({DominatorTree::Delete, BB, Succ});
73 }
74
75 // Zap all the instructions in the block.
76 while (!BB->empty()) {
77 Instruction &I = BB->back();
78 // If this instruction is used, replace uses with an arbitrary value.
79 // Because control flow can't get here, we don't care what we replace the
80 // value with. Note that since this block is unreachable, and all values
81 // contained within it must dominate their uses, that all uses will
82 // eventually be removed (they are themselves dead).
83 if (!I.use_empty())
84 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
85 BB->back().eraseFromParent();
86 }
87 new UnreachableInst(BB->getContext(), BB);
88 assert(BB->size() == 1 &&
89 isa<UnreachableInst>(BB->getTerminator()) &&
90 "The successor list of BB isn't empty before "
91 "applying corresponding DTU updates.");
92 }
93}
94
96 bool KeepOneInputPHIs) {
97 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
98}
99
100void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
101 bool KeepOneInputPHIs) {
102#ifndef NDEBUG
103 // Make sure that all predecessors of each dead block is also dead.
105 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
106 for (auto *BB : Dead)
107 for (BasicBlock *Pred : predecessors(BB))
108 assert(Dead.count(Pred) && "All predecessors must be dead!");
109#endif
110
112 detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
113
114 if (DTU)
115 DTU->applyUpdates(Updates);
116
117 for (BasicBlock *BB : BBs)
118 if (DTU)
119 DTU->deleteBB(BB);
120 else
121 BB->eraseFromParent();
122}
123
125 bool KeepOneInputPHIs) {
127
128 // Mark all reachable blocks.
129 for (BasicBlock *BB : depth_first_ext(&F, Reachable))
130 (void)BB/* Mark all reachable blocks */;
131
132 // Collect all dead blocks.
133 std::vector<BasicBlock*> DeadBlocks;
134 for (BasicBlock &BB : F)
135 if (!Reachable.count(&BB))
136 DeadBlocks.push_back(&BB);
137
138 // Delete the dead blocks.
139 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
140
141 return !DeadBlocks.empty();
142}
143
145 MemoryDependenceResults *MemDep) {
146 if (!isa<PHINode>(BB->begin()))
147 return false;
148
149 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
150 if (PN->getIncomingValue(0) != PN)
151 PN->replaceAllUsesWith(PN->getIncomingValue(0));
152 else
153 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
154
155 if (MemDep)
156 MemDep->removeInstruction(PN); // Memdep updates AA itself.
157
158 PN->eraseFromParent();
159 }
160 return true;
161}
162
164 MemorySSAUpdater *MSSAU) {
165 // Recursively deleting a PHI may cause multiple PHIs to be deleted
166 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
168
169 bool Changed = false;
170 for (const auto &PHI : PHIs)
171 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHI.operator Value *()))
172 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
173
174 return Changed;
175}
176
178 LoopInfo *LI, MemorySSAUpdater *MSSAU,
180 bool PredecessorWithTwoSuccessors,
181 DominatorTree *DT) {
182 if (BB->hasAddressTaken())
183 return false;
184
185 // Can't merge if there are multiple predecessors, or no predecessors.
186 BasicBlock *PredBB = BB->getUniquePredecessor();
187 if (!PredBB) return false;
188
189 // Don't break self-loops.
190 if (PredBB == BB) return false;
191
192 // Don't break unwinding instructions or terminators with other side-effects.
193 Instruction *PTI = PredBB->getTerminator();
194 if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
195 return false;
196
197 // Can't merge if there are multiple distinct successors.
198 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
199 return false;
200
201 // Currently only allow PredBB to have two predecessors, one being BB.
202 // Update BI to branch to BB's only successor instead of BB.
203 BranchInst *PredBB_BI;
204 BasicBlock *NewSucc = nullptr;
205 unsigned FallThruPath;
206 if (PredecessorWithTwoSuccessors) {
207 if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
208 return false;
209 BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
210 if (!BB_JmpI || !BB_JmpI->isUnconditional())
211 return false;
212 NewSucc = BB_JmpI->getSuccessor(0);
213 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
214 }
215
216 // Can't merge if there is PHI loop.
217 for (PHINode &PN : BB->phis())
218 if (llvm::is_contained(PN.incoming_values(), &PN))
219 return false;
220
221 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
222 << PredBB->getName() << "\n");
223
224 // Begin by getting rid of unneeded PHIs.
225 SmallVector<AssertingVH<Value>, 4> IncomingValues;
226 if (isa<PHINode>(BB->front())) {
227 for (PHINode &PN : BB->phis())
228 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
229 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
230 IncomingValues.push_back(PN.getIncomingValue(0));
231 FoldSingleEntryPHINodes(BB, MemDep);
232 }
233
234 if (DT) {
235 assert(!DTU && "cannot use both DT and DTU for updates");
236 DomTreeNode *PredNode = DT->getNode(PredBB);
237 DomTreeNode *BBNode = DT->getNode(BB);
238 if (PredNode) {
239 assert(BBNode && "PredNode unreachable but BBNode reachable?");
240 for (DomTreeNode *C : to_vector(BBNode->children()))
241 C->setIDom(PredNode);
242 }
243 }
244 // DTU update: Collect all the edges that exit BB.
245 // These dominator edges will be redirected from Pred.
246 std::vector<DominatorTree::UpdateType> Updates;
247 if (DTU) {
248 assert(!DT && "cannot use both DT and DTU for updates");
249 // To avoid processing the same predecessor more than once.
252 successors(PredBB));
253 Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
254 // Add insert edges first. Experimentally, for the particular case of two
255 // blocks that can be merged, with a single successor and single predecessor
256 // respectively, it is beneficial to have all insert updates first. Deleting
257 // edges first may lead to unreachable blocks, followed by inserting edges
258 // making the blocks reachable again. Such DT updates lead to high compile
259 // times. We add inserts before deletes here to reduce compile time.
260 for (BasicBlock *SuccOfBB : successors(BB))
261 // This successor of BB may already be a PredBB's successor.
262 if (!SuccsOfPredBB.contains(SuccOfBB))
263 if (SeenSuccs.insert(SuccOfBB).second)
264 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
265 SeenSuccs.clear();
266 for (BasicBlock *SuccOfBB : successors(BB))
267 if (SeenSuccs.insert(SuccOfBB).second)
268 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
269 Updates.push_back({DominatorTree::Delete, PredBB, BB});
270 }
271
272 Instruction *STI = BB->getTerminator();
273 Instruction *Start = &*BB->begin();
274 // If there's nothing to move, mark the starting instruction as the last
275 // instruction in the block. Terminator instruction is handled separately.
276 if (Start == STI)
277 Start = PTI;
278
279 // Move all definitions in the successor to the predecessor...
280 PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
281
282 if (MSSAU)
283 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
284
285 // Make all PHI nodes that referred to BB now refer to Pred as their
286 // source...
287 BB->replaceAllUsesWith(PredBB);
288
289 if (PredecessorWithTwoSuccessors) {
290 // Delete the unconditional branch from BB.
291 BB->back().eraseFromParent();
292
293 // Update branch in the predecessor.
294 PredBB_BI->setSuccessor(FallThruPath, NewSucc);
295 } else {
296 // Delete the unconditional branch from the predecessor.
297 PredBB->back().eraseFromParent();
298
299 // Move terminator instruction.
300 BB->back().moveBeforePreserving(*PredBB, PredBB->end());
301
302 // Terminator may be a memory accessing instruction too.
303 if (MSSAU)
304 if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
305 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
306 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
307 }
308 // Add unreachable to now empty BB.
309 new UnreachableInst(BB->getContext(), BB);
310
311 // Inherit predecessors name if it exists.
312 if (!PredBB->hasName())
313 PredBB->takeName(BB);
314
315 if (LI)
316 LI->removeBlock(BB);
317
318 if (MemDep)
320
321 if (DTU)
322 DTU->applyUpdates(Updates);
323
324 if (DT) {
325 assert(succ_empty(BB) &&
326 "successors should have been transferred to PredBB");
327 DT->eraseNode(BB);
328 }
329
330 // Finally, erase the old block and update dominator info.
331 DeleteDeadBlock(BB, DTU);
332
333 return true;
334}
335
338 LoopInfo *LI) {
339 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
340
341 bool BlocksHaveBeenMerged = false;
342 while (!MergeBlocks.empty()) {
343 BasicBlock *BB = *MergeBlocks.begin();
344 BasicBlock *Dest = BB->getSingleSuccessor();
345 if (Dest && (!L || L->contains(Dest))) {
346 BasicBlock *Fold = Dest->getUniquePredecessor();
347 (void)Fold;
348 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
349 assert(Fold == BB &&
350 "Expecting BB to be unique predecessor of the Dest block");
351 MergeBlocks.erase(Dest);
352 BlocksHaveBeenMerged = true;
353 } else
354 MergeBlocks.erase(BB);
355 } else
356 MergeBlocks.erase(BB);
357 }
358 return BlocksHaveBeenMerged;
359}
360
361/// Remove redundant instructions within sequences of consecutive dbg.value
362/// instructions. This is done using a backward scan to keep the last dbg.value
363/// describing a specific variable/fragment.
364///
365/// BackwardScan strategy:
366/// ----------------------
367/// Given a sequence of consecutive DbgValueInst like this
368///
369/// dbg.value ..., "x", FragmentX1 (*)
370/// dbg.value ..., "y", FragmentY1
371/// dbg.value ..., "x", FragmentX2
372/// dbg.value ..., "x", FragmentX1 (**)
373///
374/// then the instruction marked with (*) can be removed (it is guaranteed to be
375/// obsoleted by the instruction marked with (**) as the latter instruction is
376/// describing the same variable using the same fragment info).
377///
378/// Possible improvements:
379/// - Check fully overlapping fragments and not only identical fragments.
383 for (auto &I : reverse(*BB)) {
384 for (DbgVariableRecord &DVR :
385 reverse(filterDbgVars(I.getDbgRecordRange()))) {
386 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
387 DVR.getDebugLoc()->getInlinedAt());
388 auto R = VariableSet.insert(Key);
389 // If the same variable fragment is described more than once it is enough
390 // to keep the last one (i.e. the first found since we for reverse
391 // iteration).
392 if (R.second)
393 continue;
394
395 if (DVR.isDbgAssign()) {
396 // Don't delete dbg.assign intrinsics that are linked to instructions.
397 if (!at::getAssignmentInsts(&DVR).empty())
398 continue;
399 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
400 }
401
402 ToBeRemoved.push_back(&DVR);
403 }
404 // Sequence with consecutive dbg.value instrs ended. Clear the map to
405 // restart identifying redundant instructions if case we find another
406 // dbg.value sequence.
407 VariableSet.clear();
408 }
409
410 for (auto &DVR : ToBeRemoved)
411 DVR->eraseFromParent();
412
413 return !ToBeRemoved.empty();
414}
415
416/// Remove redundant dbg.value instructions using a forward scan. This can
417/// remove a dbg.value instruction that is redundant due to indicating that a
418/// variable has the same value as already being indicated by an earlier
419/// dbg.value.
420///
421/// ForwardScan strategy:
422/// ---------------------
423/// Given two identical dbg.value instructions, separated by a block of
424/// instructions that isn't describing the same variable, like this
425///
426/// dbg.value X1, "x", FragmentX1 (**)
427/// <block of instructions, none being "dbg.value ..., "x", ...">
428/// dbg.value X1, "x", FragmentX1 (*)
429///
430/// then the instruction marked with (*) can be removed. Variable "x" is already
431/// described as being mapped to the SSA value X1.
432///
433/// Possible improvements:
434/// - Keep track of non-overlapping fragments.
436 bool RemovedAny = false;
438 std::pair<SmallVector<Value *, 4>, DIExpression *>, 4>
439 VariableMap;
440 for (auto &I : *BB) {
441 for (DbgVariableRecord &DVR :
442 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
443 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
444 continue;
445 DebugVariable Key(DVR.getVariable(), std::nullopt,
446 DVR.getDebugLoc()->getInlinedAt());
447 auto [VMI, Inserted] = VariableMap.try_emplace(Key);
448 // A dbg.assign with no linked instructions can be treated like a
449 // dbg.value (i.e. can be deleted).
450 bool IsDbgValueKind =
451 (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
452
453 // Update the map if we found a new value/expression describing the
454 // variable, or if the variable wasn't mapped already.
455 SmallVector<Value *, 4> Values(DVR.location_ops());
456 if (Inserted || VMI->second.first != Values ||
457 VMI->second.second != DVR.getExpression()) {
458 if (IsDbgValueKind)
459 VMI->second = {Values, DVR.getExpression()};
460 else
461 VMI->second = {Values, nullptr};
462 continue;
463 }
464 // Don't delete dbg.assign intrinsics that are linked to instructions.
465 if (!IsDbgValueKind)
466 continue;
467 // Found an identical mapping. Remember the instruction for later removal.
468 DVR.eraseFromParent();
469 RemovedAny = true;
470 }
471 }
472
473 return RemovedAny;
474}
475
476/// Remove redundant undef dbg.assign intrinsic from an entry block using a
477/// forward scan.
478/// Strategy:
479/// ---------------------
480/// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
481/// linked to an intrinsic, and don't share an aggregate variable with a debug
482/// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
483/// that come before non-undef debug intrinsics for the variable are
484/// deleted. Given:
485///
486/// dbg.assign undef, "x", FragmentX1 (*)
487/// <block of instructions, none being "dbg.value ..., "x", ...">
488/// dbg.value %V, "x", FragmentX2
489/// <block of instructions, none being "dbg.value ..., "x", ...">
490/// dbg.assign undef, "x", FragmentX1
491///
492/// then (only) the instruction marked with (*) can be removed.
493/// Possible improvements:
494/// - Keep track of non-overlapping fragments.
496 assert(BB->isEntryBlock() && "expected entry block");
497 bool RemovedAny = false;
498 DenseSet<DebugVariableAggregate> SeenDefForAggregate;
499
500 // Remove undef dbg.assign intrinsics that are encountered before
501 // any non-undef intrinsics from the entry block.
502 for (auto &I : *BB) {
503 for (DbgVariableRecord &DVR :
504 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
505 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
506 continue;
507 bool IsDbgValueKind =
508 (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
509
510 DebugVariableAggregate Aggregate(&DVR);
511 if (!SeenDefForAggregate.contains(Aggregate)) {
512 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
513 if (!IsKill) {
514 SeenDefForAggregate.insert(Aggregate);
515 } else if (DVR.isDbgAssign()) {
516 DVR.eraseFromParent();
517 RemovedAny = true;
518 }
519 }
520 }
521 }
522
523 return RemovedAny;
524}
525
527 bool MadeChanges = false;
528 // By using the "backward scan" strategy before the "forward scan" strategy we
529 // can remove both dbg.value (2) and (3) in a situation like this:
530 //
531 // (1) dbg.value V1, "x", DIExpression()
532 // ...
533 // (2) dbg.value V2, "x", DIExpression()
534 // (3) dbg.value V1, "x", DIExpression()
535 //
536 // The backward scan will remove (2), it is made obsolete by (3). After
537 // getting (2) out of the way, the foward scan will remove (3) since "x"
538 // already is described as having the value V1 at (1).
540 if (BB->isEntryBlock() &&
542 MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
544
545 if (MadeChanges)
546 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
547 << BB->getName() << "\n");
548 return MadeChanges;
549}
550
552 Instruction &I = *BI;
553 // Replaces all of the uses of the instruction with uses of the value
554 I.replaceAllUsesWith(V);
555
556 // Make sure to propagate a name if there is one already.
557 if (I.hasName() && !V->hasName())
558 V->takeName(&I);
559
560 // Delete the unnecessary instruction now...
561 BI = BI->eraseFromParent();
562}
563
565 Instruction *I) {
566 assert(I->getParent() == nullptr &&
567 "ReplaceInstWithInst: Instruction already inserted into basic block!");
568
569 // Copy debug location to newly added instruction, if it wasn't already set
570 // by the caller.
571 if (!I->getDebugLoc())
572 I->setDebugLoc(BI->getDebugLoc());
573
574 // Insert the new instruction into the basic block...
575 BasicBlock::iterator New = I->insertInto(BB, BI);
576
577 // Replace all uses of the old instruction, and delete it.
579
580 // Move BI back to point to the newly inserted instruction
581 BI = New;
582}
583
585 // Remember visited blocks to avoid infinite loop
587 unsigned Depth = 0;
589 VisitedBlocks.insert(BB).second) {
590 if (isa<UnreachableInst>(BB->getTerminator()) ||
592 return true;
593 BB = BB->getUniqueSuccessor();
594 }
595 return false;
596}
597
600 ReplaceInstWithInst(From->getParent(), BI, To);
601}
602
604 LoopInfo *LI, MemorySSAUpdater *MSSAU,
605 const Twine &BBName) {
606 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
607
608 Instruction *LatchTerm = BB->getTerminator();
609
612
613 if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
614 // If this is a critical edge, let SplitKnownCriticalEdge do it.
615 return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
616 }
617
618 // If the edge isn't critical, then BB has a single successor or Succ has a
619 // single pred. Split the block.
620 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
621 // If the successor only has a single pred, split the top of the successor
622 // block.
623 assert(SP == BB && "CFG broken");
624 (void)SP;
625 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
626 /*Before=*/true);
627 }
628
629 // Otherwise, if BB has a single successor, split it at the bottom of the
630 // block.
631 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
632 "Should have a single succ!");
633 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
634}
635
637 if (auto *II = dyn_cast<InvokeInst>(TI))
638 II->setUnwindDest(Succ);
639 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
640 CS->setUnwindDest(Succ);
641 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
642 CR->setUnwindDest(Succ);
643 else
644 llvm_unreachable("unexpected terminator instruction");
645}
646
648 BasicBlock *NewPred, PHINode *Until) {
649 int BBIdx = 0;
650 for (PHINode &PN : DestBB->phis()) {
651 // We manually update the LandingPadReplacement PHINode and it is the last
652 // PHI Node. So, if we find it, we are done.
653 if (Until == &PN)
654 break;
655
656 // Reuse the previous value of BBIdx if it lines up. In cases where we
657 // have multiple phi nodes with *lots* of predecessors, this is a speed
658 // win because we don't have to scan the PHI looking for TIBB. This
659 // happens because the BB list of PHI nodes are usually in the same
660 // order.
661 if (PN.getIncomingBlock(BBIdx) != OldPred)
662 BBIdx = PN.getBasicBlockIndex(OldPred);
663
664 assert(BBIdx != -1 && "Invalid PHI Index!");
665 PN.setIncomingBlock(BBIdx, NewPred);
666 }
667}
668
670 LandingPadInst *OriginalPad,
671 PHINode *LandingPadReplacement,
673 const Twine &BBName) {
674
675 auto PadInst = Succ->getFirstNonPHIIt();
676 if (!LandingPadReplacement && !PadInst->isEHPad())
677 return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
678
679 auto *LI = Options.LI;
681 // Check if extra modifications will be required to preserve loop-simplify
682 // form after splitting. If it would require splitting blocks with IndirectBr
683 // terminators, bail out if preserving loop-simplify form is requested.
684 if (Options.PreserveLoopSimplify && LI) {
685 if (Loop *BBLoop = LI->getLoopFor(BB)) {
686
687 // The only way that we can break LoopSimplify form by splitting a
688 // critical edge is when there exists some edge from BBLoop to Succ *and*
689 // the only edge into Succ from outside of BBLoop is that of NewBB after
690 // the split. If the first isn't true, then LoopSimplify still holds,
691 // NewBB is the new exit block and it has no non-loop predecessors. If the
692 // second isn't true, then Succ was not in LoopSimplify form prior to
693 // the split as it had a non-loop predecessor. In both of these cases,
694 // the predecessor must be directly in BBLoop, not in a subloop, or again
695 // LoopSimplify doesn't hold.
696 for (BasicBlock *P : predecessors(Succ)) {
697 if (P == BB)
698 continue; // The new block is known.
699 if (LI->getLoopFor(P) != BBLoop) {
700 // Loop is not in LoopSimplify form, no need to re simplify after
701 // splitting edge.
702 LoopPreds.clear();
703 break;
704 }
705 LoopPreds.push_back(P);
706 }
707 // Loop-simplify form can be preserved, if we can split all in-loop
708 // predecessors.
709 if (any_of(LoopPreds, [](BasicBlock *Pred) {
710 return isa<IndirectBrInst>(Pred->getTerminator());
711 })) {
712 return nullptr;
713 }
714 }
715 }
716
717 auto *NewBB =
718 BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
719 setUnwindEdgeTo(BB->getTerminator(), NewBB);
720 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
721
722 if (LandingPadReplacement) {
723 auto *NewLP = OriginalPad->clone();
724 auto *Terminator = BranchInst::Create(Succ, NewBB);
725 NewLP->insertBefore(Terminator->getIterator());
726 LandingPadReplacement->addIncoming(NewLP, NewBB);
727 } else {
728 Value *ParentPad = nullptr;
729 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
730 ParentPad = FuncletPad->getParentPad();
731 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
732 ParentPad = CatchSwitch->getParentPad();
733 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
734 ParentPad = CleanupPad->getParentPad();
735 else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
736 ParentPad = LandingPad->getParent();
737 else
738 llvm_unreachable("handling for other EHPads not implemented yet");
739
740 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
741 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
742 }
743
744 auto *DT = Options.DT;
745 auto *MSSAU = Options.MSSAU;
746 if (!DT && !LI)
747 return NewBB;
748
749 if (DT) {
750 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
752
753 Updates.push_back({DominatorTree::Insert, BB, NewBB});
754 Updates.push_back({DominatorTree::Insert, NewBB, Succ});
755 Updates.push_back({DominatorTree::Delete, BB, Succ});
756
757 DTU.applyUpdates(Updates);
758 DTU.flush();
759
760 if (MSSAU) {
761 MSSAU->applyUpdates(Updates, *DT);
762 if (VerifyMemorySSA)
763 MSSAU->getMemorySSA()->verifyMemorySSA();
764 }
765 }
766
767 if (LI) {
768 if (Loop *BBLoop = LI->getLoopFor(BB)) {
769 // If one or the other blocks were not in a loop, the new block is not
770 // either, and thus LI doesn't need to be updated.
771 if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
772 if (BBLoop == SuccLoop) {
773 // Both in the same loop, the NewBB joins loop.
774 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
775 } else if (BBLoop->contains(SuccLoop)) {
776 // Edge from an outer loop to an inner loop. Add to the outer loop.
777 BBLoop->addBasicBlockToLoop(NewBB, *LI);
778 } else if (SuccLoop->contains(BBLoop)) {
779 // Edge from an inner loop to an outer loop. Add to the outer loop.
780 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
781 } else {
782 // Edge from two loops with no containment relation. Because these
783 // are natural loops, we know that the destination block must be the
784 // header of its loop (adding a branch into a loop elsewhere would
785 // create an irreducible loop).
786 assert(SuccLoop->getHeader() == Succ &&
787 "Should not create irreducible loops!");
788 if (Loop *P = SuccLoop->getParentLoop())
789 P->addBasicBlockToLoop(NewBB, *LI);
790 }
791 }
792
793 // If BB is in a loop and Succ is outside of that loop, we may need to
794 // update LoopSimplify form and LCSSA form.
795 if (!BBLoop->contains(Succ)) {
796 assert(!BBLoop->contains(NewBB) &&
797 "Split point for loop exit is contained in loop!");
798
799 // Update LCSSA form in the newly created exit block.
800 if (Options.PreserveLCSSA) {
801 createPHIsForSplitLoopExit(BB, NewBB, Succ);
802 }
803
804 if (!LoopPreds.empty()) {
806 Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
807 if (Options.PreserveLCSSA)
808 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
809 }
810 }
811 }
812 }
813
814 return NewBB;
815}
816
818 BasicBlock *SplitBB, BasicBlock *DestBB) {
819 // SplitBB shouldn't have anything non-trivial in it yet.
820 assert((&*SplitBB->getFirstNonPHIIt() == SplitBB->getTerminator() ||
821 SplitBB->isLandingPad()) &&
822 "SplitBB has non-PHI nodes!");
823
824 // For each PHI in the destination block.
825 for (PHINode &PN : DestBB->phis()) {
826 int Idx = PN.getBasicBlockIndex(SplitBB);
827 assert(Idx >= 0 && "Invalid Block Index");
828 Value *V = PN.getIncomingValue(Idx);
829
830 // If the input is a PHI which already satisfies LCSSA, don't create
831 // a new one.
832 if (const PHINode *VP = dyn_cast<PHINode>(V))
833 if (VP->getParent() == SplitBB)
834 continue;
835
836 // Otherwise a new PHI is needed. Create one and populate it.
837 PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
838 BasicBlock::iterator InsertPos =
839 SplitBB->isLandingPad() ? SplitBB->begin()
840 : SplitBB->getTerminator()->getIterator();
841 NewPN->insertBefore(InsertPos);
842 for (BasicBlock *BB : Preds)
843 NewPN->addIncoming(V, BB);
844
845 // Update the original PHI.
846 PN.setIncomingValue(Idx, NewPN);
847 }
848}
849
850unsigned
853 unsigned NumBroken = 0;
854 for (BasicBlock &BB : F) {
855 Instruction *TI = BB.getTerminator();
856 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
857 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
858 if (SplitCriticalEdge(TI, i, Options))
859 ++NumBroken;
860 }
861 return NumBroken;
862}
863
866 LoopInfo *LI, MemorySSAUpdater *MSSAU,
867 const Twine &BBName, bool Before) {
868 if (Before) {
869 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
870 return splitBlockBefore(Old, SplitPt,
871 DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
872 BBName);
873 }
874 BasicBlock::iterator SplitIt = SplitPt;
875 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
876 ++SplitIt;
877 assert(SplitIt != SplitPt->getParent()->end());
878 }
879 std::string Name = BBName.str();
880 BasicBlock *New = Old->splitBasicBlock(
881 SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
882
883 // The new block lives in whichever loop the old one did. This preserves
884 // LCSSA as well, because we force the split point to be after any PHI nodes.
885 if (LI)
886 if (Loop *L = LI->getLoopFor(Old))
887 L->addBasicBlockToLoop(New, *LI);
888
889 if (DTU) {
891 // Old dominates New. New node dominates all other nodes dominated by Old.
892 SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
893 Updates.push_back({DominatorTree::Insert, Old, New});
894 Updates.reserve(Updates.size() + 2 * succ_size(New));
895 for (BasicBlock *SuccessorOfOld : successors(New))
896 if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
897 Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
898 Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
899 }
900
901 DTU->applyUpdates(Updates);
902 } else if (DT)
903 // Old dominates New. New node dominates all other nodes dominated by Old.
904 if (DomTreeNode *OldNode = DT->getNode(Old)) {
905 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
906
907 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
908 for (DomTreeNode *I : Children)
909 DT->changeImmediateDominator(I, NewNode);
910 }
911
912 // Move MemoryAccesses still tracked in Old, but part of New now.
913 // Update accesses in successor blocks accordingly.
914 if (MSSAU)
915 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
916
917 return New;
918}
919
921 DominatorTree *DT, LoopInfo *LI,
922 MemorySSAUpdater *MSSAU, const Twine &BBName,
923 bool Before) {
924 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
925 Before);
926}
928 DomTreeUpdater *DTU, LoopInfo *LI,
929 MemorySSAUpdater *MSSAU, const Twine &BBName,
930 bool Before) {
931 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
932 Before);
933}
934
936 DomTreeUpdater *DTU, LoopInfo *LI,
937 MemorySSAUpdater *MSSAU,
938 const Twine &BBName) {
939
940 BasicBlock::iterator SplitIt = SplitPt;
941 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
942 ++SplitIt;
943 std::string Name = BBName.str();
944 BasicBlock *New = Old->splitBasicBlock(
945 SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
946 /* Before=*/true);
947
948 // The new block lives in whichever loop the old one did. This preserves
949 // LCSSA as well, because we force the split point to be after any PHI nodes.
950 if (LI)
951 if (Loop *L = LI->getLoopFor(Old))
952 L->addBasicBlockToLoop(New, *LI);
953
954 if (DTU) {
956 // New dominates Old. The predecessor nodes of the Old node dominate
957 // New node.
958 SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
959 DTUpdates.push_back({DominatorTree::Insert, New, Old});
960 DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
961 for (BasicBlock *PredecessorOfOld : predecessors(New))
962 if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
963 DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
964 DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
965 }
966
967 DTU->applyUpdates(DTUpdates);
968
969 // Move MemoryAccesses still tracked in Old, but part of New now.
970 // Update accesses in successor blocks accordingly.
971 if (MSSAU) {
972 MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
973 if (VerifyMemorySSA)
974 MSSAU->getMemorySSA()->verifyMemorySSA();
975 }
976 }
977 return New;
978}
979
980/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
981/// Invalidates DFS Numbering when DTU or DT is provided.
985 LoopInfo *LI, MemorySSAUpdater *MSSAU,
986 bool PreserveLCSSA, bool &HasLoopExit) {
987 // Update dominator tree if available.
988 if (DTU) {
989 // Recalculation of DomTree is needed when updating a forward DomTree and
990 // the Entry BB is replaced.
991 if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
992 // The entry block was removed and there is no external interface for
993 // the dominator tree to be notified of this change. In this corner-case
994 // we recalculate the entire tree.
995 DTU->recalculate(*NewBB->getParent());
996 } else {
997 // Split block expects NewBB to have a non-empty set of predecessors.
1000 Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1001 Updates.reserve(Updates.size() + 2 * Preds.size());
1002 for (auto *Pred : Preds)
1003 if (UniquePreds.insert(Pred).second) {
1004 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1005 Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1006 }
1007 DTU->applyUpdates(Updates);
1008 }
1009 } else if (DT) {
1010 if (OldBB == DT->getRootNode()->getBlock()) {
1011 assert(NewBB->isEntryBlock());
1012 DT->setNewRoot(NewBB);
1013 } else {
1014 // Split block expects NewBB to have a non-empty set of predecessors.
1015 DT->splitBlock(NewBB);
1016 }
1017 }
1018
1019 // Update MemoryPhis after split if MemorySSA is available
1020 if (MSSAU)
1021 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1022
1023 // The rest of the logic is only relevant for updating the loop structures.
1024 if (!LI)
1025 return;
1026
1027 if (DTU && DTU->hasDomTree())
1028 DT = &DTU->getDomTree();
1029 assert(DT && "DT should be available to update LoopInfo!");
1030 Loop *L = LI->getLoopFor(OldBB);
1031
1032 // If we need to preserve loop analyses, collect some information about how
1033 // this split will affect loops.
1034 bool IsLoopEntry = !!L;
1035 bool SplitMakesNewLoopHeader = false;
1036 for (BasicBlock *Pred : Preds) {
1037 // Preds that are not reachable from entry should not be used to identify if
1038 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1039 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1040 // as true and make the NewBB the header of some loop. This breaks LI.
1041 if (!DT->isReachableFromEntry(Pred))
1042 continue;
1043 // If we need to preserve LCSSA, determine if any of the preds is a loop
1044 // exit.
1045 if (PreserveLCSSA)
1046 if (Loop *PL = LI->getLoopFor(Pred))
1047 if (!PL->contains(OldBB))
1048 HasLoopExit = true;
1049
1050 // If we need to preserve LoopInfo, note whether any of the preds crosses
1051 // an interesting loop boundary.
1052 if (!L)
1053 continue;
1054 if (L->contains(Pred))
1055 IsLoopEntry = false;
1056 else
1057 SplitMakesNewLoopHeader = true;
1058 }
1059
1060 // Unless we have a loop for OldBB, nothing else to do here.
1061 if (!L)
1062 return;
1063
1064 if (IsLoopEntry) {
1065 // Add the new block to the nearest enclosing loop (and not an adjacent
1066 // loop). To find this, examine each of the predecessors and determine which
1067 // loops enclose them, and select the most-nested loop which contains the
1068 // loop containing the block being split.
1069 Loop *InnermostPredLoop = nullptr;
1070 for (BasicBlock *Pred : Preds) {
1071 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1072 // Seek a loop which actually contains the block being split (to avoid
1073 // adjacent loops).
1074 while (PredLoop && !PredLoop->contains(OldBB))
1075 PredLoop = PredLoop->getParentLoop();
1076
1077 // Select the most-nested of these loops which contains the block.
1078 if (PredLoop && PredLoop->contains(OldBB) &&
1079 (!InnermostPredLoop ||
1080 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1081 InnermostPredLoop = PredLoop;
1082 }
1083 }
1084
1085 if (InnermostPredLoop)
1086 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1087 } else {
1088 L->addBasicBlockToLoop(NewBB, *LI);
1089 if (SplitMakesNewLoopHeader)
1090 L->moveToHeader(NewBB);
1091 }
1092}
1093
1094/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1095/// This also updates AliasAnalysis, if available.
1096static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1098 bool HasLoopExit) {
1099 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1101 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1102 PHINode *PN = cast<PHINode>(I++);
1103
1104 // Check to see if all of the values coming in are the same. If so, we
1105 // don't need to create a new PHI node, unless it's needed for LCSSA.
1106 Value *InVal = nullptr;
1107 if (!HasLoopExit) {
1108 InVal = PN->getIncomingValueForBlock(Preds[0]);
1109 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1110 if (!PredSet.count(PN->getIncomingBlock(i)))
1111 continue;
1112 if (!InVal)
1113 InVal = PN->getIncomingValue(i);
1114 else if (InVal != PN->getIncomingValue(i)) {
1115 InVal = nullptr;
1116 break;
1117 }
1118 }
1119 }
1120
1121 if (InVal) {
1122 // If all incoming values for the new PHI would be the same, just don't
1123 // make a new PHI. Instead, just remove the incoming values from the old
1124 // PHI.
1126 [&](unsigned Idx) {
1127 return PredSet.contains(PN->getIncomingBlock(Idx));
1128 },
1129 /* DeletePHIIfEmpty */ false);
1130
1131 // Add an incoming value to the PHI node in the loop for the preheader
1132 // edge.
1133 PN->addIncoming(InVal, NewBB);
1134 continue;
1135 }
1136
1137 // If the values coming into the block are not the same, we need a new
1138 // PHI.
1139 // Create the new PHI node, insert it into NewBB at the end of the block
1140 PHINode *NewPHI =
1141 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
1142
1143 // NOTE! This loop walks backwards for a reason! First off, this minimizes
1144 // the cost of removal if we end up removing a large number of values, and
1145 // second off, this ensures that the indices for the incoming values aren't
1146 // invalidated when we remove one.
1147 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1148 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1149 if (PredSet.count(IncomingBB)) {
1150 Value *V = PN->removeIncomingValue(i, false);
1151 NewPHI->addIncoming(V, IncomingBB);
1152 }
1153 }
1154
1155 PN->addIncoming(NewPHI, NewBB);
1156 }
1157}
1158
1160 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1161 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1162 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1163 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1164
1165static BasicBlock *
1167 const char *Suffix, DomTreeUpdater *DTU,
1168 DominatorTree *DT, LoopInfo *LI,
1169 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1170 // Do not attempt to split that which cannot be split.
1171 if (!BB->canSplitPredecessors())
1172 return nullptr;
1173
1174 // For the landingpads we need to act a bit differently.
1175 // Delegate this work to the SplitLandingPadPredecessors.
1176 if (BB->isLandingPad()) {
1178 std::string NewName = std::string(Suffix) + ".split-lp";
1179
1180 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1181 DTU, DT, LI, MSSAU, PreserveLCSSA);
1182 return NewBBs[0];
1183 }
1184
1185 // Create new basic block, insert right before the original block.
1187 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1188
1189 // The new block unconditionally branches to the old block.
1190 BranchInst *BI = BranchInst::Create(BB, NewBB);
1191
1192 Loop *L = nullptr;
1193 BasicBlock *OldLatch = nullptr;
1194 // Splitting the predecessors of a loop header creates a preheader block.
1195 if (LI && LI->isLoopHeader(BB)) {
1196 L = LI->getLoopFor(BB);
1197 // Using the loop start line number prevents debuggers stepping into the
1198 // loop body for this instruction.
1199 BI->setDebugLoc(L->getStartLoc());
1200
1201 // If BB is the header of the Loop, it is possible that the loop is
1202 // modified, such that the current latch does not remain the latch of the
1203 // loop. If that is the case, the loop metadata from the current latch needs
1204 // to be applied to the new latch.
1205 OldLatch = L->getLoopLatch();
1206 } else
1207 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1208
1209 // Move the edges from Preds to point to NewBB instead of BB.
1210 for (BasicBlock *Pred : Preds) {
1211 // This is slightly more strict than necessary; the minimum requirement
1212 // is that there be no more than one indirectbr branching to BB. And
1213 // all BlockAddress uses would need to be updated.
1214 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1215 "Cannot split an edge from an IndirectBrInst");
1216 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1217 }
1218
1219 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1220 // node becomes an incoming value for BB's phi node. However, if the Preds
1221 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1222 // account for the newly created predecessor.
1223 if (Preds.empty()) {
1224 // Insert dummy values as the incoming value.
1225 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1226 cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1227 }
1228
1229 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1230 bool HasLoopExit = false;
1231 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1232 HasLoopExit);
1233
1234 if (!Preds.empty()) {
1235 // Update the PHI nodes in BB with the values coming from NewBB.
1236 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1237 }
1238
1239 if (OldLatch) {
1240 BasicBlock *NewLatch = L->getLoopLatch();
1241 if (NewLatch != OldLatch) {
1242 MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1243 NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
1244 // It's still possible that OldLatch is the latch of another inner loop,
1245 // in which case we do not remove the metadata.
1246 Loop *IL = LI->getLoopFor(OldLatch);
1247 if (IL && IL->getLoopLatch() != OldLatch)
1248 OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1249 }
1250 }
1251
1252 return NewBB;
1253}
1254
1257 const char *Suffix, DominatorTree *DT,
1258 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1259 bool PreserveLCSSA) {
1260 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1261 MSSAU, PreserveLCSSA);
1262}
1265 const char *Suffix,
1266 DomTreeUpdater *DTU, LoopInfo *LI,
1267 MemorySSAUpdater *MSSAU,
1268 bool PreserveLCSSA) {
1269 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1270 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1271}
1272
1274 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1275 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1276 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1277 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1278 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1279
1280 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1281 // it right before the original block.
1282 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1283 OrigBB->getName() + Suffix1,
1284 OrigBB->getParent(), OrigBB);
1285 NewBBs.push_back(NewBB1);
1286
1287 // The new block unconditionally branches to the old block.
1288 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
1289 BI1->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1290
1291 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1292 for (BasicBlock *Pred : Preds) {
1293 // This is slightly more strict than necessary; the minimum requirement
1294 // is that there be no more than one indirectbr branching to BB. And
1295 // all BlockAddress uses would need to be updated.
1296 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1297 "Cannot split an edge from an IndirectBrInst");
1298 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1299 }
1300
1301 bool HasLoopExit = false;
1302 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1303 PreserveLCSSA, HasLoopExit);
1304
1305 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1306 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1307
1308 // Move the remaining edges from OrigBB to point to NewBB2.
1309 SmallVector<BasicBlock*, 8> NewBB2Preds;
1310 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1311 i != e; ) {
1312 BasicBlock *Pred = *i++;
1313 if (Pred == NewBB1) continue;
1314 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1315 "Cannot split an edge from an IndirectBrInst");
1316 NewBB2Preds.push_back(Pred);
1317 e = pred_end(OrigBB);
1318 }
1319
1320 BasicBlock *NewBB2 = nullptr;
1321 if (!NewBB2Preds.empty()) {
1322 // Create another basic block for the rest of OrigBB's predecessors.
1323 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1324 OrigBB->getName() + Suffix2,
1325 OrigBB->getParent(), OrigBB);
1326 NewBBs.push_back(NewBB2);
1327
1328 // The new block unconditionally branches to the old block.
1329 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
1330 BI2->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1331
1332 // Move the remaining edges from OrigBB to point to NewBB2.
1333 for (BasicBlock *NewBB2Pred : NewBB2Preds)
1334 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1335
1336 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1337 HasLoopExit = false;
1338 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1339 PreserveLCSSA, HasLoopExit);
1340
1341 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1342 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1343 }
1344
1345 LandingPadInst *LPad = OrigBB->getLandingPadInst();
1346 Instruction *Clone1 = LPad->clone();
1347 Clone1->setName(Twine("lpad") + Suffix1);
1348 Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1349
1350 if (NewBB2) {
1351 Instruction *Clone2 = LPad->clone();
1352 Clone2->setName(Twine("lpad") + Suffix2);
1353 Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1354
1355 // Create a PHI node for the two cloned landingpad instructions only
1356 // if the original landingpad instruction has some uses.
1357 if (!LPad->use_empty()) {
1358 assert(!LPad->getType()->isTokenTy() &&
1359 "Split cannot be applied if LPad is token type. Otherwise an "
1360 "invalid PHINode of token type would be created.");
1361 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
1362 PN->addIncoming(Clone1, NewBB1);
1363 PN->addIncoming(Clone2, NewBB2);
1364 LPad->replaceAllUsesWith(PN);
1365 }
1366 LPad->eraseFromParent();
1367 } else {
1368 // There is no second clone. Just replace the landing pad with the first
1369 // clone.
1370 LPad->replaceAllUsesWith(Clone1);
1371 LPad->eraseFromParent();
1372 }
1373}
1374
1377 const char *Suffix1, const char *Suffix2,
1379 DomTreeUpdater *DTU, LoopInfo *LI,
1380 MemorySSAUpdater *MSSAU,
1381 bool PreserveLCSSA) {
1382 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1383 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1384 PreserveLCSSA);
1385}
1386
1388 BasicBlock *Pred,
1389 DomTreeUpdater *DTU) {
1390 Instruction *UncondBranch = Pred->getTerminator();
1391 // Clone the return and add it to the end of the predecessor.
1392 Instruction *NewRet = RI->clone();
1393 NewRet->insertInto(Pred, Pred->end());
1394
1395 // If the return instruction returns a value, and if the value was a
1396 // PHI node in "BB", propagate the right value into the return.
1397 for (Use &Op : NewRet->operands()) {
1398 Value *V = Op;
1399 Instruction *NewBC = nullptr;
1400 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1401 // Return value might be bitcasted. Clone and insert it before the
1402 // return instruction.
1403 V = BCI->getOperand(0);
1404 NewBC = BCI->clone();
1405 NewBC->insertInto(Pred, NewRet->getIterator());
1406 Op = NewBC;
1407 }
1408
1409 Instruction *NewEV = nullptr;
1410 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
1411 V = EVI->getOperand(0);
1412 NewEV = EVI->clone();
1413 if (NewBC) {
1414 NewBC->setOperand(0, NewEV);
1415 NewEV->insertInto(Pred, NewBC->getIterator());
1416 } else {
1417 NewEV->insertInto(Pred, NewRet->getIterator());
1418 Op = NewEV;
1419 }
1420 }
1421
1422 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1423 if (PN->getParent() == BB) {
1424 if (NewEV) {
1425 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1426 } else if (NewBC)
1427 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1428 else
1429 Op = PN->getIncomingValueForBlock(Pred);
1430 }
1431 }
1432 }
1433
1434 // Update any PHI nodes in the returning block to realize that we no
1435 // longer branch to them.
1436 BB->removePredecessor(Pred);
1437 UncondBranch->eraseFromParent();
1438
1439 if (DTU)
1440 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1441
1442 return cast<ReturnInst>(NewRet);
1443}
1444
1446 BasicBlock::iterator SplitBefore,
1447 bool Unreachable,
1448 MDNode *BranchWeights,
1449 DomTreeUpdater *DTU, LoopInfo *LI,
1450 BasicBlock *ThenBlock) {
1452 Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1453 /* UnreachableThen */ Unreachable,
1454 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1455 return ThenBlock->getTerminator();
1456}
1457
1459 BasicBlock::iterator SplitBefore,
1460 bool Unreachable,
1461 MDNode *BranchWeights,
1462 DomTreeUpdater *DTU, LoopInfo *LI,
1463 BasicBlock *ElseBlock) {
1465 Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1466 /* UnreachableThen */ false,
1467 /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1468 return ElseBlock->getTerminator();
1469}
1470
1472 Instruction **ThenTerm,
1473 Instruction **ElseTerm,
1474 MDNode *BranchWeights,
1475 DomTreeUpdater *DTU, LoopInfo *LI) {
1476 BasicBlock *ThenBlock = nullptr;
1477 BasicBlock *ElseBlock = nullptr;
1479 Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1480 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1481
1482 *ThenTerm = ThenBlock->getTerminator();
1483 *ElseTerm = ElseBlock->getTerminator();
1484}
1485
1487 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1488 BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1489 MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1490 assert((ThenBlock || ElseBlock) &&
1491 "At least one branch block must be created");
1492 assert((!UnreachableThen || !UnreachableElse) &&
1493 "Split block tail must be reachable");
1494
1496 SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1497 BasicBlock *Head = SplitBefore->getParent();
1498 if (DTU) {
1499 UniqueOrigSuccessors.insert_range(successors(Head));
1500 Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1501 }
1502
1503 LLVMContext &C = Head->getContext();
1504 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1505 BasicBlock *TrueBlock = Tail;
1506 BasicBlock *FalseBlock = Tail;
1507 bool ThenToTailEdge = false;
1508 bool ElseToTailEdge = false;
1509
1510 // Encapsulate the logic around creation/insertion/etc of a new block.
1511 auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1512 bool &ToTailEdge) {
1513 if (PBB == nullptr)
1514 return; // Do not create/insert a block.
1515
1516 if (*PBB)
1517 BB = *PBB; // Caller supplied block, use it.
1518 else {
1519 // Create a new block.
1520 BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1521 if (Unreachable)
1522 (void)new UnreachableInst(C, BB);
1523 else {
1524 (void)BranchInst::Create(Tail, BB);
1525 ToTailEdge = true;
1526 }
1527 BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1528 // Pass the new block back to the caller.
1529 *PBB = BB;
1530 }
1531 };
1532
1533 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1534 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1535
1536 Instruction *HeadOldTerm = Head->getTerminator();
1537 BranchInst *HeadNewTerm =
1538 BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
1539 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1540 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1541
1542 if (DTU) {
1543 Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1544 Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1545 if (ThenToTailEdge)
1546 Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1547 if (ElseToTailEdge)
1548 Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1549 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1550 Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1551 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1552 Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1553 DTU->applyUpdates(Updates);
1554 }
1555
1556 if (LI) {
1557 if (Loop *L = LI->getLoopFor(Head); L) {
1558 if (ThenToTailEdge)
1559 L->addBasicBlockToLoop(TrueBlock, *LI);
1560 if (ElseToTailEdge)
1561 L->addBasicBlockToLoop(FalseBlock, *LI);
1562 L->addBasicBlockToLoop(Tail, *LI);
1563 }
1564 }
1565}
1566
1567std::pair<Instruction *, Value *>
1569 BasicBlock::iterator SplitBefore) {
1570 BasicBlock *LoopPred = SplitBefore->getParent();
1571 BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1572 BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1573
1574 auto *Ty = End->getType();
1575 auto &DL = SplitBefore->getDataLayout();
1576 const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1577
1578 IRBuilder<> Builder(LoopBody->getTerminator());
1579 auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1580 auto *IVNext =
1581 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1582 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1583 auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1584 IV->getName() + ".check");
1585 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1586 LoopBody->getTerminator()->eraseFromParent();
1587
1588 // Populate the IV PHI.
1589 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1590 IV->addIncoming(IVNext, LoopBody);
1591
1592 return std::make_pair(&*LoopBody->getFirstNonPHIIt(), IV);
1593}
1594
1596 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
1597 std::function<void(IRBuilderBase &, Value *)> Func) {
1598
1599 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1600
1601 if (EC.isScalable()) {
1602 Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1603
1604 auto [BodyIP, Index] =
1605 SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1606
1607 IRB.SetInsertPoint(BodyIP);
1608 Func(IRB, Index);
1609 return;
1610 }
1611
1612 unsigned Num = EC.getFixedValue();
1613 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1614 IRB.SetInsertPoint(InsertBefore);
1615 Func(IRB, ConstantInt::get(IndexTy, Idx));
1616 }
1617}
1618
1620 Value *EVL, BasicBlock::iterator InsertBefore,
1621 std::function<void(IRBuilderBase &, Value *)> Func) {
1622
1623 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1624 Type *Ty = EVL->getType();
1625
1626 if (!isa<ConstantInt>(EVL)) {
1627 auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1628 IRB.SetInsertPoint(BodyIP);
1629 Func(IRB, Index);
1630 return;
1631 }
1632
1633 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1634 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1635 IRB.SetInsertPoint(InsertBefore);
1636 Func(IRB, ConstantInt::get(Ty, Idx));
1637 }
1638}
1639
1641 BasicBlock *&IfFalse) {
1642 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1643 BasicBlock *Pred1 = nullptr;
1644 BasicBlock *Pred2 = nullptr;
1645
1646 if (SomePHI) {
1647 if (SomePHI->getNumIncomingValues() != 2)
1648 return nullptr;
1649 Pred1 = SomePHI->getIncomingBlock(0);
1650 Pred2 = SomePHI->getIncomingBlock(1);
1651 } else {
1652 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1653 if (PI == PE) // No predecessor
1654 return nullptr;
1655 Pred1 = *PI++;
1656 if (PI == PE) // Only one predecessor
1657 return nullptr;
1658 Pred2 = *PI++;
1659 if (PI != PE) // More than two predecessors
1660 return nullptr;
1661 }
1662
1663 // We can only handle branches. Other control flow will be lowered to
1664 // branches if possible anyway.
1665 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
1666 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
1667 if (!Pred1Br || !Pred2Br)
1668 return nullptr;
1669
1670 // Eliminate code duplication by ensuring that Pred1Br is conditional if
1671 // either are.
1672 if (Pred2Br->isConditional()) {
1673 // If both branches are conditional, we don't have an "if statement". In
1674 // reality, we could transform this case, but since the condition will be
1675 // required anyway, we stand no chance of eliminating it, so the xform is
1676 // probably not profitable.
1677 if (Pred1Br->isConditional())
1678 return nullptr;
1679
1680 std::swap(Pred1, Pred2);
1681 std::swap(Pred1Br, Pred2Br);
1682 }
1683
1684 if (Pred1Br->isConditional()) {
1685 // The only thing we have to watch out for here is to make sure that Pred2
1686 // doesn't have incoming edges from other blocks. If it does, the condition
1687 // doesn't dominate BB.
1688 if (!Pred2->getSinglePredecessor())
1689 return nullptr;
1690
1691 // If we found a conditional branch predecessor, make sure that it branches
1692 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
1693 if (Pred1Br->getSuccessor(0) == BB &&
1694 Pred1Br->getSuccessor(1) == Pred2) {
1695 IfTrue = Pred1;
1696 IfFalse = Pred2;
1697 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1698 Pred1Br->getSuccessor(1) == BB) {
1699 IfTrue = Pred2;
1700 IfFalse = Pred1;
1701 } else {
1702 // We know that one arm of the conditional goes to BB, so the other must
1703 // go somewhere unrelated, and this must not be an "if statement".
1704 return nullptr;
1705 }
1706
1707 return Pred1Br;
1708 }
1709
1710 // Ok, if we got here, both predecessors end with an unconditional branch to
1711 // BB. Don't panic! If both blocks only have a single (identical)
1712 // predecessor, and THAT is a conditional branch, then we're all ok!
1713 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1714 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1715 return nullptr;
1716
1717 // Otherwise, if this is a conditional branch, then we can use it!
1718 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
1719 if (!BI) return nullptr;
1720
1721 assert(BI->isConditional() && "Two successors but not conditional?");
1722 if (BI->getSuccessor(0) == Pred1) {
1723 IfTrue = Pred1;
1724 IfFalse = Pred2;
1725 } else {
1726 IfTrue = Pred2;
1727 IfFalse = Pred1;
1728 }
1729 return BI;
1730}
1731
1733 Value *NewCond = PBI->getCondition();
1734 // If this is a "cmp" instruction, only used for branching (and nowhere
1735 // else), then we can simply invert the predicate.
1736 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1737 CmpInst *CI = cast<CmpInst>(NewCond);
1739 } else
1740 NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
1741
1742 PBI->setCondition(NewCond);
1743 PBI->swapSuccessors();
1744}
1745
1747 for (auto &BB : F) {
1748 auto *Term = BB.getTerminator();
1749 if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
1750 isa<BranchInst>(Term)))
1751 return false;
1752 }
1753 return true;
1754}
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 BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName, bool Before)
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, BranchInst *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB)
Remove redundant undef dbg.assign intrinsic from an entry block using a forward scan.
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 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"))
BlockVerifier::State From
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
bool End
Definition: ELF_riscv.cpp:480
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:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
static const uint32_t IV[8]
Definition: blake3_impl.h:83
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:142
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator end()
Definition: BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:459
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:528
LLVM_ABI const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:665
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...
Definition: BasicBlock.cpp:393
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:690
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:337
const Instruction & front() const
Definition: BasicBlock.h:482
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.
Definition: BasicBlock.cpp:549
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,...
Definition: BasicBlock.cpp:354
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:555
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:475
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:437
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:287
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:445
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:467
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:131
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:661
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:233
LLVM_ABI bool canSplitPredecessors() const
Definition: BasicBlock.cpp:523
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition: BasicBlock.h:662
const Instruction & back() const
Definition: BasicBlock.h:484
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:494
This class represents a no-op cast from one type to another.
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Value * getCondition() 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:666
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition: InstrTypes.h:770
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:791
DWARF expression.
This class represents an Operation in the 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:245
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
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:165
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:334
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...
Definition: GlobalValue.h:663
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:114
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2494
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1805
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2329
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1197
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1403
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.
Definition: IRBuilder.cpp:123
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
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.
Definition: Instruction.h:879
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.
Definition: Instruction.h:428
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.
Definition: Metadata.cpp:1718
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.
Definition: Instruction.h:510
bool isSpecialTerminator() const
Definition: Instruction.h:323
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.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:40
Metadata node.
Definition: Metadata.h:1077
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 applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
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.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1905
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.
Definition: Constants.cpp:1885
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:283
size_type size() const
Definition: SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:380
bool erase(PtrType Ptr)
Remove pointer from the set.
Definition: SmallPtrSet.h:418
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:470
void insert_range(Range &&R)
Definition: SmallPtrSet.h:490
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
iterator begin() const
Definition: SmallPtrSet.h:494
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:476
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void reserve(size_type N)
Definition: SmallVector.h:664
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
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
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:234
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:292
void setOperand(unsigned i, Value *Val)
Definition: User.h:237
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:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
bool use_empty() const
Definition: Value.h:346
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:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:169
self_iterator getIterator()
Definition: ilist_node.h:134
#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.
Definition: DebugInfo.cpp:1887
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:256
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 BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
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:80
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.
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.
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:663
auto pred_size(const MachineBasicBlock *BB)
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,...
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:1751
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.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
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...
Definition: SmallVector.h:1300
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_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.
Definition: DebugInfo.cpp:2259
DWARFExpression::Operation Op
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.
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:96
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.
auto pred_begin(const MachineBasicBlock *BB)
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition: iterator.h:363
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1916
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:641
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:858
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()