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