Movatterモバイル変換


[0]ホーム

URL:


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

Generated on Thu Jul 17 2025 17:29:23 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp