LLVM 24.0.0git
Legality.cpp
Go to the documentation of this file.
1//===- Legality.cpp -------------------------------------------------------===//
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
14#include "llvm/Support/Debug.h"
17
18namespace llvm::sandboxir {
19
20#ifndef NDEBUG
21void ShuffleMask::dump() const {
22 print(dbgs());
23 dbgs() << "\n";
24}
25
27 print(dbgs());
28 dbgs() << "\n";
29}
30#endif // NDEBUG
31
32std::optional<ResultReason>
33LegalityAnalysis::notVectorizableBasedOnOpcodesAndTypes(BndlRef<Value *> Bndl) {
34 auto *I0 = cast<Instruction>(Bndl[0]);
35 auto Opcode = I0->getOpcode();
36 // If they have different opcodes, then we cannot form a vector (for now).
37 if (any_of(drop_begin(Bndl), [Opcode](Value *V) {
38 return cast<Instruction>(V)->getOpcode() != Opcode;
39 }))
41
42 // If not the same scalar type, Pack. This will accept scalars and vectors as
43 // long as the element type is the same.
45 if (any_of(drop_begin(Bndl), [ElmTy0](Value *V) {
47 }))
49
50 // TODO: Allow vectorization of instrs with different flags as long as we
51 // change them to the least common one.
52 // For now pack if differnt FastMathFlags.
53 if (isa<FPMathOperator>(I0)) {
54 FastMathFlags FMF0 = cast<Instruction>(Bndl[0])->getFastMathFlags();
55 if (any_of(drop_begin(Bndl), [FMF0](auto *V) {
56 return cast<Instruction>(V)->getFastMathFlags() != FMF0;
57 }))
59 }
60
61 // TODO: Allow vectorization by using common flags.
62 // For now Pack if they don't have the same wrap flags.
63 bool CanHaveWrapFlags =
65 if (CanHaveWrapFlags) {
66 bool NUW0 = I0->hasNoUnsignedWrap();
67 bool NSW0 = I0->hasNoSignedWrap();
68 if (any_of(drop_begin(Bndl), [NUW0, NSW0](auto *V) {
69 return cast<Instruction>(V)->hasNoUnsignedWrap() != NUW0 ||
70 cast<Instruction>(V)->hasNoSignedWrap() != NSW0;
71 })) {
73 }
74 }
75
76 // Now we need to do further checks for specific opcodes.
77 switch (Opcode) {
78 case Instruction::Opcode::ZExt:
79 case Instruction::Opcode::SExt:
80 case Instruction::Opcode::FPToUI:
81 case Instruction::Opcode::FPToSI:
82 case Instruction::Opcode::FPExt:
83 case Instruction::Opcode::PtrToAddr:
84 case Instruction::Opcode::PtrToInt:
85 case Instruction::Opcode::IntToPtr:
86 case Instruction::Opcode::SIToFP:
87 case Instruction::Opcode::UIToFP:
88 case Instruction::Opcode::Trunc:
89 case Instruction::Opcode::FPTrunc:
90 case Instruction::Opcode::BitCast: {
91 // We have already checked that they are of the same opcode.
92 assert(all_of(Bndl,
93 [Opcode](Value *V) {
94 return cast<Instruction>(V)->getOpcode() == Opcode;
95 }) &&
96 "Different opcodes, should have early returned!");
97 // But for these opcodes we should also check the operand type.
98 Type *FromTy0 = Utils::getExpectedType(I0->getOperand(0));
99 if (any_of(drop_begin(Bndl), [FromTy0](Value *V) {
101 FromTy0;
102 }))
104 return std::nullopt;
105 }
106 case Instruction::Opcode::FCmp:
107 case Instruction::Opcode::ICmp: {
108 // We need the same predicate and the same operand type.
109 auto Pred0 = cast<CmpInst>(I0)->getPredicate();
110 Type *Ty0 = cast<CmpInst>(I0)->getOperand(0)->getType();
111 bool Same = all_of(Bndl, [Pred0, Ty0](Value *V) {
112 auto *CmpI = cast<CmpInst>(V);
113 return CmpI->getPredicate() == Pred0 &&
114 CmpI->getOperand(0)->getType() == Ty0;
115 });
116 if (Same)
117 return std::nullopt;
119 }
120 case Instruction::Opcode::Select: {
121 auto *Sel0 = cast<SelectInst>(Bndl[0]);
122 auto *Cond0 = Sel0->getCondition();
124 // TODO: For now we don't vectorize if the lanes in the condition don't
125 // match those of the select instruction.
127 return std::nullopt;
128 }
129 case Instruction::Opcode::FNeg:
130 case Instruction::Opcode::Add:
131 case Instruction::Opcode::FAdd:
132 case Instruction::Opcode::Sub:
133 case Instruction::Opcode::FSub:
134 case Instruction::Opcode::Mul:
135 case Instruction::Opcode::FMul:
136 case Instruction::Opcode::FRem:
137 case Instruction::Opcode::UDiv:
138 case Instruction::Opcode::SDiv:
139 case Instruction::Opcode::FDiv:
140 case Instruction::Opcode::URem:
141 case Instruction::Opcode::SRem:
142 case Instruction::Opcode::Shl:
143 case Instruction::Opcode::LShr:
144 case Instruction::Opcode::AShr:
145 case Instruction::Opcode::And:
146 case Instruction::Opcode::Or:
147 case Instruction::Opcode::Xor:
148 return std::nullopt;
149 case Instruction::Opcode::Load:
150 if (VecUtils::areConsecutive<LoadInst>(Bndl, SE, DL))
151 return std::nullopt;
153 case Instruction::Opcode::Store:
154 if (VecUtils::areConsecutive<StoreInst>(Bndl, SE, DL))
155 return std::nullopt;
157 case Instruction::Opcode::PHI:
159 case Instruction::Opcode::Opaque:
161 case Instruction::Opcode::UncondBr:
162 case Instruction::Opcode::CondBr:
163 case Instruction::Opcode::Ret:
164 case Instruction::Opcode::AddrSpaceCast:
165 case Instruction::Opcode::InsertElement:
166 case Instruction::Opcode::InsertValue:
167 case Instruction::Opcode::ExtractElement:
168 case Instruction::Opcode::ExtractValue:
169 case Instruction::Opcode::ShuffleVector:
170 case Instruction::Opcode::Call:
171 case Instruction::Opcode::GetElementPtr:
172 case Instruction::Opcode::Switch:
173 case Instruction::Opcode::Pack:
175 case Instruction::Opcode::VAArg:
176 case Instruction::Opcode::Freeze:
177 case Instruction::Opcode::Fence:
178 case Instruction::Opcode::Invoke:
179 case Instruction::Opcode::CallBr:
180 case Instruction::Opcode::LandingPad:
181 case Instruction::Opcode::CatchPad:
182 case Instruction::Opcode::CleanupPad:
183 case Instruction::Opcode::CatchRet:
184 case Instruction::Opcode::CleanupRet:
185 case Instruction::Opcode::Resume:
186 case Instruction::Opcode::CatchSwitch:
187 case Instruction::Opcode::AtomicRMW:
188 case Instruction::Opcode::AtomicCmpXchg:
189 case Instruction::Opcode::Alloca:
190 case Instruction::Opcode::Unreachable:
192 }
193
194 return std::nullopt;
195}
196
198LegalityAnalysis::getHowToCollectValues(BndlRef<Value *> Bndl) const {
200 Vec.reserve(Bndl.size());
201 for (auto [Elm, V] : enumerate(Bndl)) {
202 if (auto *VecOp = IMaps.getVectorForOrig(V)) {
203 // If there is a vector containing `V`, then get the lane it came from.
204 std::optional<int> ExtractIdxOpt = IMaps.getOrigLane(VecOp, V);
205 // This could be a vector, like <2 x float> in which case the mask needs
206 // to enumerate all lanes.
207 for (unsigned Ln = 0, Lanes = VecUtils::getNumLanes(V); Ln != Lanes; ++Ln)
208 Vec.emplace_back(VecOp, ExtractIdxOpt ? *ExtractIdxOpt + Ln : -1);
209 } else {
210 Vec.emplace_back(V);
211 }
212 }
213 return CollectDescr(std::move(Vec));
214}
215
217 bool SkipScheduling) {
218 // If Bndl contains values other than instructions, we need to Pack.
219 if (any_of(Bndl, [](auto *V) { return !isa<Instruction>(V); }))
221 // Pack if not in the same BB.
224 // Pack if instructions repeat, i.e., require some sort of broadcast.
227
228 auto CollectDescrs = getHowToCollectValues(Bndl);
229 if (CollectDescrs.hasVectorInputs()) {
230 if (auto ValueShuffleOpt = CollectDescrs.getSingleInput()) {
231 auto [Vec, Mask] = *ValueShuffleOpt;
232 if (Mask.isIdentity())
235 }
237 std::move(CollectDescrs));
238 }
239
240 if (auto ReasonOpt = notVectorizableBasedOnOpcodesAndTypes(Bndl))
241 return createLegalityResult<Pack>(*ReasonOpt);
242
243 if (!SkipScheduling) {
244 // TODO: Try to remove the IBndl vector.
246 IBndl.reserve(Bndl.size());
247 for (auto *V : Bndl)
249 if (!Sched.trySchedule(IBndl))
251 }
252
254}
255
257 Sched.clear();
258 IMaps.clear();
259}
260} // namespace llvm::sandboxir
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
size_t size() const
Get the array size.
Definition ArrayRef.h:141
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
An ArrayRef of Values or Instructions that we can print/dump for debugging.
Definition VecUtils.h:459
Describes how to collect the values needed by each lane.
Definition Legality.h:252
LLVM_ABI const LegalityResult & canVectorize(BndlRef< Value * > Bndl, bool SkipScheduling=false)
Checks if it's legal to vectorize the instructions in Bndl.
Definition Legality.cpp:216
static bool areUnique(BndlRef< ValueT * > Values)
Definition Legality.h:358
static bool differentBlock(BndlRef< ValueT * > Instrs)
Definition Legality.h:350
ResultT & createLegalityResult(ArgsT &&...Args)
A LegalityResult factory.
Definition Legality.h:342
The legality outcome is represented by a class rather than an enum class because in some cases the le...
Definition Legality.h:158
LLVM_DUMP_METHOD void dump() const
Definition Legality.cpp:26
virtual void print(raw_ostream &OS) const
Definition Legality.h:173
void print(raw_ostream &OS) const
Definition Legality.h:73
LLVM_DUMP_METHOD void dump() const
Definition Legality.cpp:21
static Type * getExpectedType(const Value *V)
\Returns the expected type of Value V.
Definition Utils.h:32
A SandboxIR Value has users. This is the base class.
Definition Value.h:72
static unsigned getNumLanes(Type *Ty)
\Returns the number of vector lanes of Ty or 1 if not a vector.
Definition VecUtils.h:91
static bool areConsecutive(LoadOrStoreT *I1, LoadOrStoreT *I2, ScalarEvolution &SE, const DataLayout &DL)
\Returns true if I1 and I2 are load/stores accessing consecutive memory addresses.
Definition VecUtils.h:58
static Type * getElementType(Type *Ty)
Returns Ty if scalar or its element type if vector.
Definition VecUtils.h:51
static BundleTy getOperand(BndlRef< Value * > Bndl, unsigned OpIdx)
Definition BundleVec.cpp:44
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559