LLVM 22.0.0git
LowerConstantIntrinsics.cpp
Go to the documentation of this file.
1//===- LowerConstantIntrinsics.cpp - Lower constant intrinsic calls -------===//
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 pass lowers all remaining 'objectsize' 'is.constant' intrinsic calls
10// and provides constant propagation and basic CFG cleanup on the result.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
30#include "llvm/Pass.h"
31#include "llvm/Support/Debug.h"
34#include <optional>
35
36using namespace llvm;
37using namespace llvm::PatternMatch;
38
39#define DEBUG_TYPE "lower-is-constant-intrinsic"
40
41STATISTIC(IsConstantIntrinsicsHandled,
42 "Number of 'is.constant' intrinsic calls handled");
43STATISTIC(ObjectSizeIntrinsicsHandled,
44 "Number of 'objectsize' intrinsic calls handled");
45
47 if (auto *C = dyn_cast<Constant>(II->getOperand(0)))
48 if (C->isManifestConstant())
49 return ConstantInt::getTrue(II->getType());
50 return ConstantInt::getFalse(II->getType());
51}
52
54 Value *NewValue,
55 DomTreeUpdater *DTU) {
56 bool HasDeadBlocks = false;
57 SmallSetVector<Instruction *, 8> UnsimplifiedUsers;
58 replaceAndRecursivelySimplify(II, NewValue, nullptr, nullptr, nullptr,
59 &UnsimplifiedUsers);
60 // UnsimplifiedUsers can contain PHI nodes that may be removed when
61 // replacing the branch instructions, so use a value handle worklist
62 // to handle those possibly removed instructions.
63 SmallVector<WeakVH, 8> Worklist(UnsimplifiedUsers.begin(),
64 UnsimplifiedUsers.end());
65
66 for (auto &VH : Worklist) {
68 if (!BI)
69 continue;
70 if (BI->isUnconditional())
71 continue;
72
74 if (match(BI->getOperand(0), m_Zero())) {
75 Target = BI->getSuccessor(1);
76 Other = BI->getSuccessor(0);
77 } else if (match(BI->getOperand(0), m_One())) {
78 Target = BI->getSuccessor(0);
79 Other = BI->getSuccessor(1);
80 } else {
81 Target = nullptr;
82 Other = nullptr;
83 }
84 if (Target && Target != Other) {
85 BasicBlock *Source = BI->getParent();
86 Other->removePredecessor(Source);
87
88 Instruction *NewBI = BranchInst::Create(Target, Source);
89 NewBI->setDebugLoc(BI->getDebugLoc());
90 BI->eraseFromParent();
91
92 if (DTU)
93 DTU->applyUpdates({{DominatorTree::Delete, Source, Other}});
94 if (pred_empty(Other))
95 HasDeadBlocks = true;
96 }
97 }
98 return HasDeadBlocks;
99}
100
102 DominatorTree *DT) {
103 std::optional<DomTreeUpdater> DTU;
104 if (DT)
105 DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
106
107 bool HasDeadBlocks = false;
108 const auto &DL = F.getDataLayout();
110
112 for (BasicBlock *BB : RPOT) {
113 for (Instruction &I: *BB) {
115 if (!II)
116 continue;
117 switch (II->getIntrinsicID()) {
118 default:
119 break;
120 case Intrinsic::is_constant:
121 case Intrinsic::objectsize:
122 Worklist.push_back(WeakTrackingVH(&I));
123 break;
124 }
125 }
126 }
127 for (WeakTrackingVH &VH: Worklist) {
128 // Items on the worklist can be mutated by earlier recursive replaces.
129 // This can remove the intrinsic as dead (VH == null), but also replace
130 // the intrinsic in place.
131 if (!VH)
132 continue;
134 if (!II)
135 continue;
136 Value *NewValue;
137 switch (II->getIntrinsicID()) {
138 default:
139 continue;
140 case Intrinsic::is_constant:
141 NewValue = lowerIsConstantIntrinsic(II);
142 LLVM_DEBUG(dbgs() << "Folding " << *II << " to " << *NewValue << "\n");
143 IsConstantIntrinsicsHandled++;
144 break;
145 case Intrinsic::objectsize:
146 NewValue = lowerObjectSizeCall(II, DL, &TLI, true);
147 LLVM_DEBUG(dbgs() << "Folding " << *II << " to " << *NewValue << "\n");
148 ObjectSizeIntrinsicsHandled++;
149 break;
150 }
152 II, NewValue, DTU ? &*DTU : nullptr);
153 }
154 if (HasDeadBlocks)
155 removeUnreachableBlocks(F, DTU ? &*DTU : nullptr);
156 return !Worklist.empty();
157}
158
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This is the interface for a simple mod/ref and alias analysis over globals.
static bool replaceConditionalBranchesOnConstant(Instruction *II, Value *NewValue, DomTreeUpdater *DTU)
static Value * lowerIsConstantIntrinsic(IntrinsicInst *II)
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
uint64_t IntrinsicInst * II
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:167
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
iterator end()
Get an iterator to the end of the SetVector.
Definition SetVector.h:119
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:109
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:356
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Target - Wrapper for Target specific information.
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Value handle that is nullable, but tries to track the Value.
const ParentTy * getParent() const
Definition ilist_node.h:34
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
bool lowerConstantIntrinsics(Function &F, const TargetLibraryInfo &TLI, DominatorTree *DT)
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:759
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
@ Other
Any other memory.
Definition ModRef.h:68
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:119
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2883
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Run the pass over the function.