File: | llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp |
Warning: | line 743, column 17 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===// | ||||||||||||||
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 performs various transformations related to eliminating memcpy | ||||||||||||||
10 | // calls, or transforming sets of stores into memset's. | ||||||||||||||
11 | // | ||||||||||||||
12 | //===----------------------------------------------------------------------===// | ||||||||||||||
13 | |||||||||||||||
14 | #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" | ||||||||||||||
15 | #include "llvm/ADT/DenseSet.h" | ||||||||||||||
16 | #include "llvm/ADT/None.h" | ||||||||||||||
17 | #include "llvm/ADT/STLExtras.h" | ||||||||||||||
18 | #include "llvm/ADT/SmallVector.h" | ||||||||||||||
19 | #include "llvm/ADT/Statistic.h" | ||||||||||||||
20 | #include "llvm/ADT/iterator_range.h" | ||||||||||||||
21 | #include "llvm/Analysis/AliasAnalysis.h" | ||||||||||||||
22 | #include "llvm/Analysis/AssumptionCache.h" | ||||||||||||||
23 | #include "llvm/Analysis/GlobalsModRef.h" | ||||||||||||||
24 | #include "llvm/Analysis/Loads.h" | ||||||||||||||
25 | #include "llvm/Analysis/MemoryDependenceAnalysis.h" | ||||||||||||||
26 | #include "llvm/Analysis/MemoryLocation.h" | ||||||||||||||
27 | #include "llvm/Analysis/MemorySSA.h" | ||||||||||||||
28 | #include "llvm/Analysis/MemorySSAUpdater.h" | ||||||||||||||
29 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||||||||||||
30 | #include "llvm/Analysis/ValueTracking.h" | ||||||||||||||
31 | #include "llvm/IR/Argument.h" | ||||||||||||||
32 | #include "llvm/IR/BasicBlock.h" | ||||||||||||||
33 | #include "llvm/IR/Constants.h" | ||||||||||||||
34 | #include "llvm/IR/DataLayout.h" | ||||||||||||||
35 | #include "llvm/IR/DerivedTypes.h" | ||||||||||||||
36 | #include "llvm/IR/Dominators.h" | ||||||||||||||
37 | #include "llvm/IR/Function.h" | ||||||||||||||
38 | #include "llvm/IR/GetElementPtrTypeIterator.h" | ||||||||||||||
39 | #include "llvm/IR/GlobalVariable.h" | ||||||||||||||
40 | #include "llvm/IR/IRBuilder.h" | ||||||||||||||
41 | #include "llvm/IR/InstrTypes.h" | ||||||||||||||
42 | #include "llvm/IR/Instruction.h" | ||||||||||||||
43 | #include "llvm/IR/Instructions.h" | ||||||||||||||
44 | #include "llvm/IR/IntrinsicInst.h" | ||||||||||||||
45 | #include "llvm/IR/Intrinsics.h" | ||||||||||||||
46 | #include "llvm/IR/LLVMContext.h" | ||||||||||||||
47 | #include "llvm/IR/Module.h" | ||||||||||||||
48 | #include "llvm/IR/Operator.h" | ||||||||||||||
49 | #include "llvm/IR/PassManager.h" | ||||||||||||||
50 | #include "llvm/IR/Type.h" | ||||||||||||||
51 | #include "llvm/IR/User.h" | ||||||||||||||
52 | #include "llvm/IR/Value.h" | ||||||||||||||
53 | #include "llvm/InitializePasses.h" | ||||||||||||||
54 | #include "llvm/Pass.h" | ||||||||||||||
55 | #include "llvm/Support/Casting.h" | ||||||||||||||
56 | #include "llvm/Support/Debug.h" | ||||||||||||||
57 | #include "llvm/Support/MathExtras.h" | ||||||||||||||
58 | #include "llvm/Support/raw_ostream.h" | ||||||||||||||
59 | #include "llvm/Transforms/Scalar.h" | ||||||||||||||
60 | #include "llvm/Transforms/Utils/Local.h" | ||||||||||||||
61 | #include <algorithm> | ||||||||||||||
62 | #include <cassert> | ||||||||||||||
63 | #include <cstdint> | ||||||||||||||
64 | #include <utility> | ||||||||||||||
65 | |||||||||||||||
66 | using namespace llvm; | ||||||||||||||
67 | |||||||||||||||
68 | #define DEBUG_TYPE"memcpyopt" "memcpyopt" | ||||||||||||||
69 | |||||||||||||||
70 | static cl::opt<bool> | ||||||||||||||
71 | EnableMemorySSA("enable-memcpyopt-memoryssa", cl::init(false), cl::Hidden, | ||||||||||||||
72 | cl::desc("Use MemorySSA-backed MemCpyOpt.")); | ||||||||||||||
73 | |||||||||||||||
74 | STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted")static llvm::Statistic NumMemCpyInstr = {"memcpyopt", "NumMemCpyInstr" , "Number of memcpy instructions deleted"}; | ||||||||||||||
75 | STATISTIC(NumMemSetInfer, "Number of memsets inferred")static llvm::Statistic NumMemSetInfer = {"memcpyopt", "NumMemSetInfer" , "Number of memsets inferred"}; | ||||||||||||||
76 | STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy")static llvm::Statistic NumMoveToCpy = {"memcpyopt", "NumMoveToCpy" , "Number of memmoves converted to memcpy"}; | ||||||||||||||
77 | STATISTIC(NumCpyToSet, "Number of memcpys converted to memset")static llvm::Statistic NumCpyToSet = {"memcpyopt", "NumCpyToSet" , "Number of memcpys converted to memset"}; | ||||||||||||||
78 | STATISTIC(NumCallSlot, "Number of call slot optimizations performed")static llvm::Statistic NumCallSlot = {"memcpyopt", "NumCallSlot" , "Number of call slot optimizations performed"}; | ||||||||||||||
79 | |||||||||||||||
80 | namespace { | ||||||||||||||
81 | |||||||||||||||
82 | /// Represents a range of memset'd bytes with the ByteVal value. | ||||||||||||||
83 | /// This allows us to analyze stores like: | ||||||||||||||
84 | /// store 0 -> P+1 | ||||||||||||||
85 | /// store 0 -> P+0 | ||||||||||||||
86 | /// store 0 -> P+3 | ||||||||||||||
87 | /// store 0 -> P+2 | ||||||||||||||
88 | /// which sometimes happens with stores to arrays of structs etc. When we see | ||||||||||||||
89 | /// the first store, we make a range [1, 2). The second store extends the range | ||||||||||||||
90 | /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the | ||||||||||||||
91 | /// two ranges into [0, 3) which is memset'able. | ||||||||||||||
92 | struct MemsetRange { | ||||||||||||||
93 | // Start/End - A semi range that describes the span that this range covers. | ||||||||||||||
94 | // The range is closed at the start and open at the end: [Start, End). | ||||||||||||||
95 | int64_t Start, End; | ||||||||||||||
96 | |||||||||||||||
97 | /// StartPtr - The getelementptr instruction that points to the start of the | ||||||||||||||
98 | /// range. | ||||||||||||||
99 | Value *StartPtr; | ||||||||||||||
100 | |||||||||||||||
101 | /// Alignment - The known alignment of the first store. | ||||||||||||||
102 | unsigned Alignment; | ||||||||||||||
103 | |||||||||||||||
104 | /// TheStores - The actual stores that make up this range. | ||||||||||||||
105 | SmallVector<Instruction*, 16> TheStores; | ||||||||||||||
106 | |||||||||||||||
107 | bool isProfitableToUseMemset(const DataLayout &DL) const; | ||||||||||||||
108 | }; | ||||||||||||||
109 | |||||||||||||||
110 | } // end anonymous namespace | ||||||||||||||
111 | |||||||||||||||
112 | bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const { | ||||||||||||||
113 | // If we found more than 4 stores to merge or 16 bytes, use memset. | ||||||||||||||
114 | if (TheStores.size() >= 4 || End-Start >= 16) return true; | ||||||||||||||
115 | |||||||||||||||
116 | // If there is nothing to merge, don't do anything. | ||||||||||||||
117 | if (TheStores.size() < 2) return false; | ||||||||||||||
118 | |||||||||||||||
119 | // If any of the stores are a memset, then it is always good to extend the | ||||||||||||||
120 | // memset. | ||||||||||||||
121 | for (Instruction *SI : TheStores) | ||||||||||||||
122 | if (!isa<StoreInst>(SI)) | ||||||||||||||
123 | return true; | ||||||||||||||
124 | |||||||||||||||
125 | // Assume that the code generator is capable of merging pairs of stores | ||||||||||||||
126 | // together if it wants to. | ||||||||||||||
127 | if (TheStores.size() == 2) return false; | ||||||||||||||
128 | |||||||||||||||
129 | // If we have fewer than 8 stores, it can still be worthwhile to do this. | ||||||||||||||
130 | // For example, merging 4 i8 stores into an i32 store is useful almost always. | ||||||||||||||
131 | // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the | ||||||||||||||
132 | // memset will be split into 2 32-bit stores anyway) and doing so can | ||||||||||||||
133 | // pessimize the llvm optimizer. | ||||||||||||||
134 | // | ||||||||||||||
135 | // Since we don't have perfect knowledge here, make some assumptions: assume | ||||||||||||||
136 | // the maximum GPR width is the same size as the largest legal integer | ||||||||||||||
137 | // size. If so, check to see whether we will end up actually reducing the | ||||||||||||||
138 | // number of stores used. | ||||||||||||||
139 | unsigned Bytes = unsigned(End-Start); | ||||||||||||||
140 | unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8; | ||||||||||||||
141 | if (MaxIntSize == 0) | ||||||||||||||
142 | MaxIntSize = 1; | ||||||||||||||
143 | unsigned NumPointerStores = Bytes / MaxIntSize; | ||||||||||||||
144 | |||||||||||||||
145 | // Assume the remaining bytes if any are done a byte at a time. | ||||||||||||||
146 | unsigned NumByteStores = Bytes % MaxIntSize; | ||||||||||||||
147 | |||||||||||||||
148 | // If we will reduce the # stores (according to this heuristic), do the | ||||||||||||||
149 | // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32 | ||||||||||||||
150 | // etc. | ||||||||||||||
151 | return TheStores.size() > NumPointerStores+NumByteStores; | ||||||||||||||
152 | } | ||||||||||||||
153 | |||||||||||||||
154 | namespace { | ||||||||||||||
155 | |||||||||||||||
156 | class MemsetRanges { | ||||||||||||||
157 | using range_iterator = SmallVectorImpl<MemsetRange>::iterator; | ||||||||||||||
158 | |||||||||||||||
159 | /// A sorted list of the memset ranges. | ||||||||||||||
160 | SmallVector<MemsetRange, 8> Ranges; | ||||||||||||||
161 | |||||||||||||||
162 | const DataLayout &DL; | ||||||||||||||
163 | |||||||||||||||
164 | public: | ||||||||||||||
165 | MemsetRanges(const DataLayout &DL) : DL(DL) {} | ||||||||||||||
166 | |||||||||||||||
167 | using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator; | ||||||||||||||
168 | |||||||||||||||
169 | const_iterator begin() const { return Ranges.begin(); } | ||||||||||||||
170 | const_iterator end() const { return Ranges.end(); } | ||||||||||||||
171 | bool empty() const { return Ranges.empty(); } | ||||||||||||||
172 | |||||||||||||||
173 | void addInst(int64_t OffsetFromFirst, Instruction *Inst) { | ||||||||||||||
174 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) | ||||||||||||||
175 | addStore(OffsetFromFirst, SI); | ||||||||||||||
176 | else | ||||||||||||||
177 | addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst)); | ||||||||||||||
178 | } | ||||||||||||||
179 | |||||||||||||||
180 | void addStore(int64_t OffsetFromFirst, StoreInst *SI) { | ||||||||||||||
181 | int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType()); | ||||||||||||||
182 | |||||||||||||||
183 | addRange(OffsetFromFirst, StoreSize, SI->getPointerOperand(), | ||||||||||||||
184 | SI->getAlign().value(), SI); | ||||||||||||||
185 | } | ||||||||||||||
186 | |||||||||||||||
187 | void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) { | ||||||||||||||
188 | int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue(); | ||||||||||||||
189 | addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI); | ||||||||||||||
190 | } | ||||||||||||||
191 | |||||||||||||||
192 | void addRange(int64_t Start, int64_t Size, Value *Ptr, | ||||||||||||||
193 | unsigned Alignment, Instruction *Inst); | ||||||||||||||
194 | }; | ||||||||||||||
195 | |||||||||||||||
196 | } // end anonymous namespace | ||||||||||||||
197 | |||||||||||||||
198 | /// Add a new store to the MemsetRanges data structure. This adds a | ||||||||||||||
199 | /// new range for the specified store at the specified offset, merging into | ||||||||||||||
200 | /// existing ranges as appropriate. | ||||||||||||||
201 | void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr, | ||||||||||||||
202 | unsigned Alignment, Instruction *Inst) { | ||||||||||||||
203 | int64_t End = Start+Size; | ||||||||||||||
204 | |||||||||||||||
205 | range_iterator I = partition_point( | ||||||||||||||
206 | Ranges, [=](const MemsetRange &O) { return O.End < Start; }); | ||||||||||||||
207 | |||||||||||||||
208 | // We now know that I == E, in which case we didn't find anything to merge | ||||||||||||||
209 | // with, or that Start <= I->End. If End < I->Start or I == E, then we need | ||||||||||||||
210 | // to insert a new range. Handle this now. | ||||||||||||||
211 | if (I == Ranges.end() || End < I->Start) { | ||||||||||||||
212 | MemsetRange &R = *Ranges.insert(I, MemsetRange()); | ||||||||||||||
213 | R.Start = Start; | ||||||||||||||
214 | R.End = End; | ||||||||||||||
215 | R.StartPtr = Ptr; | ||||||||||||||
216 | R.Alignment = Alignment; | ||||||||||||||
217 | R.TheStores.push_back(Inst); | ||||||||||||||
218 | return; | ||||||||||||||
219 | } | ||||||||||||||
220 | |||||||||||||||
221 | // This store overlaps with I, add it. | ||||||||||||||
222 | I->TheStores.push_back(Inst); | ||||||||||||||
223 | |||||||||||||||
224 | // At this point, we may have an interval that completely contains our store. | ||||||||||||||
225 | // If so, just add it to the interval and return. | ||||||||||||||
226 | if (I->Start <= Start && I->End >= End) | ||||||||||||||
227 | return; | ||||||||||||||
228 | |||||||||||||||
229 | // Now we know that Start <= I->End and End >= I->Start so the range overlaps | ||||||||||||||
230 | // but is not entirely contained within the range. | ||||||||||||||
231 | |||||||||||||||
232 | // See if the range extends the start of the range. In this case, it couldn't | ||||||||||||||
233 | // possibly cause it to join the prior range, because otherwise we would have | ||||||||||||||
234 | // stopped on *it*. | ||||||||||||||
235 | if (Start < I->Start) { | ||||||||||||||
236 | I->Start = Start; | ||||||||||||||
237 | I->StartPtr = Ptr; | ||||||||||||||
238 | I->Alignment = Alignment; | ||||||||||||||
239 | } | ||||||||||||||
240 | |||||||||||||||
241 | // Now we know that Start <= I->End and Start >= I->Start (so the startpoint | ||||||||||||||
242 | // is in or right at the end of I), and that End >= I->Start. Extend I out to | ||||||||||||||
243 | // End. | ||||||||||||||
244 | if (End > I->End) { | ||||||||||||||
245 | I->End = End; | ||||||||||||||
246 | range_iterator NextI = I; | ||||||||||||||
247 | while (++NextI != Ranges.end() && End >= NextI->Start) { | ||||||||||||||
248 | // Merge the range in. | ||||||||||||||
249 | I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end()); | ||||||||||||||
250 | if (NextI->End > I->End) | ||||||||||||||
251 | I->End = NextI->End; | ||||||||||||||
252 | Ranges.erase(NextI); | ||||||||||||||
253 | NextI = I; | ||||||||||||||
254 | } | ||||||||||||||
255 | } | ||||||||||||||
256 | } | ||||||||||||||
257 | |||||||||||||||
258 | //===----------------------------------------------------------------------===// | ||||||||||||||
259 | // MemCpyOptLegacyPass Pass | ||||||||||||||
260 | //===----------------------------------------------------------------------===// | ||||||||||||||
261 | |||||||||||||||
262 | namespace { | ||||||||||||||
263 | |||||||||||||||
264 | class MemCpyOptLegacyPass : public FunctionPass { | ||||||||||||||
265 | MemCpyOptPass Impl; | ||||||||||||||
266 | |||||||||||||||
267 | public: | ||||||||||||||
268 | static char ID; // Pass identification, replacement for typeid | ||||||||||||||
269 | |||||||||||||||
270 | MemCpyOptLegacyPass() : FunctionPass(ID) { | ||||||||||||||
271 | initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry()); | ||||||||||||||
272 | } | ||||||||||||||
273 | |||||||||||||||
274 | bool runOnFunction(Function &F) override; | ||||||||||||||
275 | |||||||||||||||
276 | private: | ||||||||||||||
277 | // This transformation requires dominator postdominator info | ||||||||||||||
278 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||||||||||||
279 | AU.setPreservesCFG(); | ||||||||||||||
280 | AU.addRequired<AssumptionCacheTracker>(); | ||||||||||||||
281 | AU.addRequired<DominatorTreeWrapperPass>(); | ||||||||||||||
282 | AU.addPreserved<DominatorTreeWrapperPass>(); | ||||||||||||||
283 | AU.addPreserved<GlobalsAAWrapperPass>(); | ||||||||||||||
284 | AU.addRequired<TargetLibraryInfoWrapperPass>(); | ||||||||||||||
285 | if (!EnableMemorySSA) | ||||||||||||||
286 | AU.addRequired<MemoryDependenceWrapperPass>(); | ||||||||||||||
287 | AU.addPreserved<MemoryDependenceWrapperPass>(); | ||||||||||||||
288 | AU.addRequired<AAResultsWrapperPass>(); | ||||||||||||||
289 | AU.addPreserved<AAResultsWrapperPass>(); | ||||||||||||||
290 | if (EnableMemorySSA) | ||||||||||||||
291 | AU.addRequired<MemorySSAWrapperPass>(); | ||||||||||||||
292 | AU.addPreserved<MemorySSAWrapperPass>(); | ||||||||||||||
293 | } | ||||||||||||||
294 | }; | ||||||||||||||
295 | |||||||||||||||
296 | } // end anonymous namespace | ||||||||||||||
297 | |||||||||||||||
298 | char MemCpyOptLegacyPass::ID = 0; | ||||||||||||||
299 | |||||||||||||||
300 | /// The public interface to this file... | ||||||||||||||
301 | FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); } | ||||||||||||||
302 | |||||||||||||||
303 | INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry &Registry) { | ||||||||||||||
304 | false, false)static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry &Registry) { | ||||||||||||||
305 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | ||||||||||||||
306 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry); | ||||||||||||||
307 | INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)initializeMemoryDependenceWrapperPassPass(Registry); | ||||||||||||||
308 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||||||||||||
309 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | ||||||||||||||
310 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry); | ||||||||||||||
311 | INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt" , &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <MemCpyOptLegacyPass>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag ; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag , initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry)); } | ||||||||||||||
312 | false, false)PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt" , &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <MemCpyOptLegacyPass>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag ; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag , initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry)); } | ||||||||||||||
313 | |||||||||||||||
314 | // Check that V is either not accessible by the caller, or unwinding cannot | ||||||||||||||
315 | // occur between Start and End. | ||||||||||||||
316 | static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start, | ||||||||||||||
317 | Instruction *End) { | ||||||||||||||
318 | assert(Start->getParent() == End->getParent() && "Must be in same block")((Start->getParent() == End->getParent() && "Must be in same block" ) ? static_cast<void> (0) : __assert_fail ("Start->getParent() == End->getParent() && \"Must be in same block\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 318, __PRETTY_FUNCTION__)); | ||||||||||||||
319 | if (!Start->getFunction()->doesNotThrow() && | ||||||||||||||
320 | !isa<AllocaInst>(getUnderlyingObject(V))) { | ||||||||||||||
321 | for (const Instruction &I : | ||||||||||||||
322 | make_range(Start->getIterator(), End->getIterator())) { | ||||||||||||||
323 | if (I.mayThrow()) | ||||||||||||||
324 | return true; | ||||||||||||||
325 | } | ||||||||||||||
326 | } | ||||||||||||||
327 | return false; | ||||||||||||||
328 | } | ||||||||||||||
329 | |||||||||||||||
330 | void MemCpyOptPass::eraseInstruction(Instruction *I) { | ||||||||||||||
331 | if (MSSAU) | ||||||||||||||
332 | MSSAU->removeMemoryAccess(I); | ||||||||||||||
333 | if (MD) | ||||||||||||||
334 | MD->removeInstruction(I); | ||||||||||||||
335 | I->eraseFromParent(); | ||||||||||||||
336 | } | ||||||||||||||
337 | |||||||||||||||
338 | // Check for mod or ref of Loc between Start and End, excluding both boundaries. | ||||||||||||||
339 | // Start and End must be in the same block | ||||||||||||||
340 | static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc, | ||||||||||||||
341 | const MemoryUseOrDef *Start, | ||||||||||||||
342 | const MemoryUseOrDef *End) { | ||||||||||||||
343 | assert(Start->getBlock() == End->getBlock() && "Only local supported")((Start->getBlock() == End->getBlock() && "Only local supported" ) ? static_cast<void> (0) : __assert_fail ("Start->getBlock() == End->getBlock() && \"Only local supported\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 343, __PRETTY_FUNCTION__)); | ||||||||||||||
344 | for (const MemoryAccess &MA : | ||||||||||||||
345 | make_range(++Start->getIterator(), End->getIterator())) { | ||||||||||||||
346 | if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(), | ||||||||||||||
347 | Loc))) | ||||||||||||||
348 | return true; | ||||||||||||||
349 | } | ||||||||||||||
350 | return false; | ||||||||||||||
351 | } | ||||||||||||||
352 | |||||||||||||||
353 | // Check for mod of Loc between Start and End, excluding both boundaries. | ||||||||||||||
354 | // Start and End can be in different blocks. | ||||||||||||||
355 | static bool writtenBetween(MemorySSA *MSSA, MemoryLocation Loc, | ||||||||||||||
356 | const MemoryUseOrDef *Start, | ||||||||||||||
357 | const MemoryUseOrDef *End) { | ||||||||||||||
358 | // TODO: Only walk until we hit Start. | ||||||||||||||
359 | MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess( | ||||||||||||||
360 | End->getDefiningAccess(), Loc); | ||||||||||||||
361 | return !MSSA->dominates(Clobber, Start); | ||||||||||||||
362 | } | ||||||||||||||
363 | |||||||||||||||
364 | /// When scanning forward over instructions, we look for some other patterns to | ||||||||||||||
365 | /// fold away. In particular, this looks for stores to neighboring locations of | ||||||||||||||
366 | /// memory. If it sees enough consecutive ones, it attempts to merge them | ||||||||||||||
367 | /// together into a memcpy/memset. | ||||||||||||||
368 | Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst, | ||||||||||||||
369 | Value *StartPtr, | ||||||||||||||
370 | Value *ByteVal) { | ||||||||||||||
371 | const DataLayout &DL = StartInst->getModule()->getDataLayout(); | ||||||||||||||
372 | |||||||||||||||
373 | // Okay, so we now have a single store that can be splatable. Scan to find | ||||||||||||||
374 | // all subsequent stores of the same value to offset from the same pointer. | ||||||||||||||
375 | // Join these together into ranges, so we can decide whether contiguous blocks | ||||||||||||||
376 | // are stored. | ||||||||||||||
377 | MemsetRanges Ranges(DL); | ||||||||||||||
378 | |||||||||||||||
379 | BasicBlock::iterator BI(StartInst); | ||||||||||||||
380 | |||||||||||||||
381 | // Keeps track of the last memory use or def before the insertion point for | ||||||||||||||
382 | // the new memset. The new MemoryDef for the inserted memsets will be inserted | ||||||||||||||
383 | // after MemInsertPoint. It points to either LastMemDef or to the last user | ||||||||||||||
384 | // before the insertion point of the memset, if there are any such users. | ||||||||||||||
385 | MemoryUseOrDef *MemInsertPoint = nullptr; | ||||||||||||||
386 | // Keeps track of the last MemoryDef between StartInst and the insertion point | ||||||||||||||
387 | // for the new memset. This will become the defining access of the inserted | ||||||||||||||
388 | // memsets. | ||||||||||||||
389 | MemoryDef *LastMemDef = nullptr; | ||||||||||||||
390 | for (++BI; !BI->isTerminator(); ++BI) { | ||||||||||||||
391 | if (MSSAU) { | ||||||||||||||
392 | auto *CurrentAcc = cast_or_null<MemoryUseOrDef>( | ||||||||||||||
393 | MSSAU->getMemorySSA()->getMemoryAccess(&*BI)); | ||||||||||||||
394 | if (CurrentAcc) { | ||||||||||||||
395 | MemInsertPoint = CurrentAcc; | ||||||||||||||
396 | if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc)) | ||||||||||||||
397 | LastMemDef = CurrentDef; | ||||||||||||||
398 | } | ||||||||||||||
399 | } | ||||||||||||||
400 | |||||||||||||||
401 | if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) { | ||||||||||||||
402 | // If the instruction is readnone, ignore it, otherwise bail out. We | ||||||||||||||
403 | // don't even allow readonly here because we don't want something like: | ||||||||||||||
404 | // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). | ||||||||||||||
405 | if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) | ||||||||||||||
406 | break; | ||||||||||||||
407 | continue; | ||||||||||||||
408 | } | ||||||||||||||
409 | |||||||||||||||
410 | if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) { | ||||||||||||||
411 | // If this is a store, see if we can merge it in. | ||||||||||||||
412 | if (!NextStore->isSimple()) break; | ||||||||||||||
413 | |||||||||||||||
414 | Value *StoredVal = NextStore->getValueOperand(); | ||||||||||||||
415 | |||||||||||||||
416 | // Don't convert stores of non-integral pointer types to memsets (which | ||||||||||||||
417 | // stores integers). | ||||||||||||||
418 | if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType())) | ||||||||||||||
419 | break; | ||||||||||||||
420 | |||||||||||||||
421 | // Check to see if this stored value is of the same byte-splattable value. | ||||||||||||||
422 | Value *StoredByte = isBytewiseValue(StoredVal, DL); | ||||||||||||||
423 | if (isa<UndefValue>(ByteVal) && StoredByte) | ||||||||||||||
424 | ByteVal = StoredByte; | ||||||||||||||
425 | if (ByteVal != StoredByte) | ||||||||||||||
426 | break; | ||||||||||||||
427 | |||||||||||||||
428 | // Check to see if this store is to a constant offset from the start ptr. | ||||||||||||||
429 | Optional<int64_t> Offset = | ||||||||||||||
430 | isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL); | ||||||||||||||
431 | if (!Offset) | ||||||||||||||
432 | break; | ||||||||||||||
433 | |||||||||||||||
434 | Ranges.addStore(*Offset, NextStore); | ||||||||||||||
435 | } else { | ||||||||||||||
436 | MemSetInst *MSI = cast<MemSetInst>(BI); | ||||||||||||||
437 | |||||||||||||||
438 | if (MSI->isVolatile() || ByteVal != MSI->getValue() || | ||||||||||||||
439 | !isa<ConstantInt>(MSI->getLength())) | ||||||||||||||
440 | break; | ||||||||||||||
441 | |||||||||||||||
442 | // Check to see if this store is to a constant offset from the start ptr. | ||||||||||||||
443 | Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL); | ||||||||||||||
444 | if (!Offset) | ||||||||||||||
445 | break; | ||||||||||||||
446 | |||||||||||||||
447 | Ranges.addMemSet(*Offset, MSI); | ||||||||||||||
448 | } | ||||||||||||||
449 | } | ||||||||||||||
450 | |||||||||||||||
451 | // If we have no ranges, then we just had a single store with nothing that | ||||||||||||||
452 | // could be merged in. This is a very common case of course. | ||||||||||||||
453 | if (Ranges.empty()) | ||||||||||||||
454 | return nullptr; | ||||||||||||||
455 | |||||||||||||||
456 | // If we had at least one store that could be merged in, add the starting | ||||||||||||||
457 | // store as well. We try to avoid this unless there is at least something | ||||||||||||||
458 | // interesting as a small compile-time optimization. | ||||||||||||||
459 | Ranges.addInst(0, StartInst); | ||||||||||||||
460 | |||||||||||||||
461 | // If we create any memsets, we put it right before the first instruction that | ||||||||||||||
462 | // isn't part of the memset block. This ensure that the memset is dominated | ||||||||||||||
463 | // by any addressing instruction needed by the start of the block. | ||||||||||||||
464 | IRBuilder<> Builder(&*BI); | ||||||||||||||
465 | |||||||||||||||
466 | // Now that we have full information about ranges, loop over the ranges and | ||||||||||||||
467 | // emit memset's for anything big enough to be worthwhile. | ||||||||||||||
468 | Instruction *AMemSet = nullptr; | ||||||||||||||
469 | for (const MemsetRange &Range : Ranges) { | ||||||||||||||
470 | if (Range.TheStores.size() == 1) continue; | ||||||||||||||
471 | |||||||||||||||
472 | // If it is profitable to lower this range to memset, do so now. | ||||||||||||||
473 | if (!Range.isProfitableToUseMemset(DL)) | ||||||||||||||
474 | continue; | ||||||||||||||
475 | |||||||||||||||
476 | // Otherwise, we do want to transform this! Create a new memset. | ||||||||||||||
477 | // Get the starting pointer of the block. | ||||||||||||||
478 | StartPtr = Range.StartPtr; | ||||||||||||||
479 | |||||||||||||||
480 | AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start, | ||||||||||||||
481 | MaybeAlign(Range.Alignment)); | ||||||||||||||
482 | LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction *SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs () << "With: " << *AMemSet << '\n'; } } while (false) | ||||||||||||||
483 | : Range.TheStores) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction *SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs () << "With: " << *AMemSet << '\n'; } } while (false) | ||||||||||||||
484 | << *SI << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction *SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs () << "With: " << *AMemSet << '\n'; } } while (false) | ||||||||||||||
485 | dbgs() << "With: " << *AMemSet << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction *SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs () << "With: " << *AMemSet << '\n'; } } while (false); | ||||||||||||||
486 | if (!Range.TheStores.empty()) | ||||||||||||||
487 | AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc()); | ||||||||||||||
488 | |||||||||||||||
489 | if (MSSAU) { | ||||||||||||||
490 | assert(LastMemDef && MemInsertPoint &&((LastMemDef && MemInsertPoint && "Both LastMemDef and MemInsertPoint need to be set" ) ? static_cast<void> (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 491, __PRETTY_FUNCTION__)) | ||||||||||||||
491 | "Both LastMemDef and MemInsertPoint need to be set")((LastMemDef && MemInsertPoint && "Both LastMemDef and MemInsertPoint need to be set" ) ? static_cast<void> (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 491, __PRETTY_FUNCTION__)); | ||||||||||||||
492 | auto *NewDef = | ||||||||||||||
493 | cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI | ||||||||||||||
494 | ? MSSAU->createMemoryAccessBefore( | ||||||||||||||
495 | AMemSet, LastMemDef, MemInsertPoint) | ||||||||||||||
496 | : MSSAU->createMemoryAccessAfter( | ||||||||||||||
497 | AMemSet, LastMemDef, MemInsertPoint)); | ||||||||||||||
498 | MSSAU->insertDef(NewDef, /*RenameUses=*/true); | ||||||||||||||
499 | LastMemDef = NewDef; | ||||||||||||||
500 | MemInsertPoint = NewDef; | ||||||||||||||
501 | } | ||||||||||||||
502 | |||||||||||||||
503 | // Zap all the stores. | ||||||||||||||
504 | for (Instruction *SI : Range.TheStores) | ||||||||||||||
505 | eraseInstruction(SI); | ||||||||||||||
506 | |||||||||||||||
507 | ++NumMemSetInfer; | ||||||||||||||
508 | } | ||||||||||||||
509 | |||||||||||||||
510 | return AMemSet; | ||||||||||||||
511 | } | ||||||||||||||
512 | |||||||||||||||
513 | // This method try to lift a store instruction before position P. | ||||||||||||||
514 | // It will lift the store and its argument + that anything that | ||||||||||||||
515 | // may alias with these. | ||||||||||||||
516 | // The method returns true if it was successful. | ||||||||||||||
517 | bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) { | ||||||||||||||
518 | // If the store alias this position, early bail out. | ||||||||||||||
519 | MemoryLocation StoreLoc = MemoryLocation::get(SI); | ||||||||||||||
520 | if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc))) | ||||||||||||||
521 | return false; | ||||||||||||||
522 | |||||||||||||||
523 | // Keep track of the arguments of all instruction we plan to lift | ||||||||||||||
524 | // so we can make sure to lift them as well if appropriate. | ||||||||||||||
525 | DenseSet<Instruction*> Args; | ||||||||||||||
526 | if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) | ||||||||||||||
527 | if (Ptr->getParent() == SI->getParent()) | ||||||||||||||
528 | Args.insert(Ptr); | ||||||||||||||
529 | |||||||||||||||
530 | // Instruction to lift before P. | ||||||||||||||
531 | SmallVector<Instruction *, 8> ToLift{SI}; | ||||||||||||||
532 | |||||||||||||||
533 | // Memory locations of lifted instructions. | ||||||||||||||
534 | SmallVector<MemoryLocation, 8> MemLocs{StoreLoc}; | ||||||||||||||
535 | |||||||||||||||
536 | // Lifted calls. | ||||||||||||||
537 | SmallVector<const CallBase *, 8> Calls; | ||||||||||||||
538 | |||||||||||||||
539 | const MemoryLocation LoadLoc = MemoryLocation::get(LI); | ||||||||||||||
540 | |||||||||||||||
541 | for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) { | ||||||||||||||
542 | auto *C = &*I; | ||||||||||||||
543 | |||||||||||||||
544 | // Make sure hoisting does not perform a store that was not guaranteed to | ||||||||||||||
545 | // happen. | ||||||||||||||
546 | if (!isGuaranteedToTransferExecutionToSuccessor(C)) | ||||||||||||||
547 | return false; | ||||||||||||||
548 | |||||||||||||||
549 | bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None)); | ||||||||||||||
550 | |||||||||||||||
551 | bool NeedLift = false; | ||||||||||||||
552 | if (Args.erase(C)) | ||||||||||||||
553 | NeedLift = true; | ||||||||||||||
554 | else if (MayAlias) { | ||||||||||||||
555 | NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) { | ||||||||||||||
556 | return isModOrRefSet(AA->getModRefInfo(C, ML)); | ||||||||||||||
557 | }); | ||||||||||||||
558 | |||||||||||||||
559 | if (!NeedLift) | ||||||||||||||
560 | NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) { | ||||||||||||||
561 | return isModOrRefSet(AA->getModRefInfo(C, Call)); | ||||||||||||||
562 | }); | ||||||||||||||
563 | } | ||||||||||||||
564 | |||||||||||||||
565 | if (!NeedLift) | ||||||||||||||
566 | continue; | ||||||||||||||
567 | |||||||||||||||
568 | if (MayAlias) { | ||||||||||||||
569 | // Since LI is implicitly moved downwards past the lifted instructions, | ||||||||||||||
570 | // none of them may modify its source. | ||||||||||||||
571 | if (isModSet(AA->getModRefInfo(C, LoadLoc))) | ||||||||||||||
572 | return false; | ||||||||||||||
573 | else if (const auto *Call = dyn_cast<CallBase>(C)) { | ||||||||||||||
574 | // If we can't lift this before P, it's game over. | ||||||||||||||
575 | if (isModOrRefSet(AA->getModRefInfo(P, Call))) | ||||||||||||||
576 | return false; | ||||||||||||||
577 | |||||||||||||||
578 | Calls.push_back(Call); | ||||||||||||||
579 | } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) { | ||||||||||||||
580 | // If we can't lift this before P, it's game over. | ||||||||||||||
581 | auto ML = MemoryLocation::get(C); | ||||||||||||||
582 | if (isModOrRefSet(AA->getModRefInfo(P, ML))) | ||||||||||||||
583 | return false; | ||||||||||||||
584 | |||||||||||||||
585 | MemLocs.push_back(ML); | ||||||||||||||
586 | } else | ||||||||||||||
587 | // We don't know how to lift this instruction. | ||||||||||||||
588 | return false; | ||||||||||||||
589 | } | ||||||||||||||
590 | |||||||||||||||
591 | ToLift.push_back(C); | ||||||||||||||
592 | for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k) | ||||||||||||||
593 | if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) { | ||||||||||||||
594 | if (A->getParent() == SI->getParent()) { | ||||||||||||||
595 | // Cannot hoist user of P above P | ||||||||||||||
596 | if(A == P) return false; | ||||||||||||||
597 | Args.insert(A); | ||||||||||||||
598 | } | ||||||||||||||
599 | } | ||||||||||||||
600 | } | ||||||||||||||
601 | |||||||||||||||
602 | // Find MSSA insertion point. Normally P will always have a corresponding | ||||||||||||||
603 | // memory access before which we can insert. However, with non-standard AA | ||||||||||||||
604 | // pipelines, there may be a mismatch between AA and MSSA, in which case we | ||||||||||||||
605 | // will scan for a memory access before P. In either case, we know for sure | ||||||||||||||
606 | // that at least the load will have a memory access. | ||||||||||||||
607 | // TODO: Simplify this once P will be determined by MSSA, in which case the | ||||||||||||||
608 | // discrepancy can no longer occur. | ||||||||||||||
609 | MemoryUseOrDef *MemInsertPoint = nullptr; | ||||||||||||||
610 | if (MSSAU) { | ||||||||||||||
611 | if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) { | ||||||||||||||
612 | MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator()); | ||||||||||||||
613 | } else { | ||||||||||||||
614 | const Instruction *ConstP = P; | ||||||||||||||
615 | for (const Instruction &I : make_range(++ConstP->getReverseIterator(), | ||||||||||||||
616 | ++LI->getReverseIterator())) { | ||||||||||||||
617 | if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) { | ||||||||||||||
618 | MemInsertPoint = MA; | ||||||||||||||
619 | break; | ||||||||||||||
620 | } | ||||||||||||||
621 | } | ||||||||||||||
622 | } | ||||||||||||||
623 | } | ||||||||||||||
624 | |||||||||||||||
625 | // We made it, we need to lift. | ||||||||||||||
626 | for (auto *I : llvm::reverse(ToLift)) { | ||||||||||||||
627 | LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Lifting " << *I << " before " << *P << "\n"; } } while (false); | ||||||||||||||
628 | I->moveBefore(P); | ||||||||||||||
629 | if (MSSAU) { | ||||||||||||||
630 | assert(MemInsertPoint && "Must have found insert point")((MemInsertPoint && "Must have found insert point") ? static_cast<void> (0) : __assert_fail ("MemInsertPoint && \"Must have found insert point\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 630, __PRETTY_FUNCTION__)); | ||||||||||||||
631 | if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) { | ||||||||||||||
632 | MSSAU->moveAfter(MA, MemInsertPoint); | ||||||||||||||
633 | MemInsertPoint = MA; | ||||||||||||||
634 | } | ||||||||||||||
635 | } | ||||||||||||||
636 | } | ||||||||||||||
637 | |||||||||||||||
638 | return true; | ||||||||||||||
639 | } | ||||||||||||||
640 | |||||||||||||||
641 | bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { | ||||||||||||||
642 | if (!SI->isSimple()) return false; | ||||||||||||||
643 | |||||||||||||||
644 | // Avoid merging nontemporal stores since the resulting | ||||||||||||||
645 | // memcpy/memset would not be able to preserve the nontemporal hint. | ||||||||||||||
646 | // In theory we could teach how to propagate the !nontemporal metadata to | ||||||||||||||
647 | // memset calls. However, that change would force the backend to | ||||||||||||||
648 | // conservatively expand !nontemporal memset calls back to sequences of | ||||||||||||||
649 | // store instructions (effectively undoing the merging). | ||||||||||||||
650 | if (SI->getMetadata(LLVMContext::MD_nontemporal)) | ||||||||||||||
651 | return false; | ||||||||||||||
652 | |||||||||||||||
653 | const DataLayout &DL = SI->getModule()->getDataLayout(); | ||||||||||||||
654 | |||||||||||||||
655 | Value *StoredVal = SI->getValueOperand(); | ||||||||||||||
656 | |||||||||||||||
657 | // Not all the transforms below are correct for non-integral pointers, bail | ||||||||||||||
658 | // until we've audited the individual pieces. | ||||||||||||||
659 | if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType())) | ||||||||||||||
660 | return false; | ||||||||||||||
661 | |||||||||||||||
662 | // Load to store forwarding can be interpreted as memcpy. | ||||||||||||||
663 | if (LoadInst *LI
| ||||||||||||||
664 | if (LI->isSimple() && LI->hasOneUse() && | ||||||||||||||
665 | LI->getParent() == SI->getParent()) { | ||||||||||||||
666 | |||||||||||||||
667 | auto *T = LI->getType(); | ||||||||||||||
668 | if (T->isAggregateType()) { | ||||||||||||||
669 | MemoryLocation LoadLoc = MemoryLocation::get(LI); | ||||||||||||||
670 | |||||||||||||||
671 | // We use alias analysis to check if an instruction may store to | ||||||||||||||
672 | // the memory we load from in between the load and the store. If | ||||||||||||||
673 | // such an instruction is found, we try to promote there instead | ||||||||||||||
674 | // of at the store position. | ||||||||||||||
675 | // TODO: Can use MSSA for this. | ||||||||||||||
676 | Instruction *P = SI; | ||||||||||||||
677 | for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) { | ||||||||||||||
678 | if (isModSet(AA->getModRefInfo(&I, LoadLoc))) { | ||||||||||||||
679 | P = &I; | ||||||||||||||
680 | break; | ||||||||||||||
681 | } | ||||||||||||||
682 | } | ||||||||||||||
683 | |||||||||||||||
684 | // We found an instruction that may write to the loaded memory. | ||||||||||||||
685 | // We can try to promote at this position instead of the store | ||||||||||||||
686 | // position if nothing alias the store memory after this and the store | ||||||||||||||
687 | // destination is not in the range. | ||||||||||||||
688 | if (P && P != SI) { | ||||||||||||||
689 | if (!moveUp(SI, P, LI)) | ||||||||||||||
690 | P = nullptr; | ||||||||||||||
691 | } | ||||||||||||||
692 | |||||||||||||||
693 | // If a valid insertion position is found, then we can promote | ||||||||||||||
694 | // the load/store pair to a memcpy. | ||||||||||||||
695 | if (P) { | ||||||||||||||
696 | // If we load from memory that may alias the memory we store to, | ||||||||||||||
697 | // memmove must be used to preserve semantic. If not, memcpy can | ||||||||||||||
698 | // be used. | ||||||||||||||
699 | bool UseMemMove = false; | ||||||||||||||
700 | if (!AA->isNoAlias(MemoryLocation::get(SI), LoadLoc)) | ||||||||||||||
701 | UseMemMove = true; | ||||||||||||||
702 | |||||||||||||||
703 | uint64_t Size = DL.getTypeStoreSize(T); | ||||||||||||||
704 | |||||||||||||||
705 | IRBuilder<> Builder(P); | ||||||||||||||
706 | Instruction *M; | ||||||||||||||
707 | if (UseMemMove) | ||||||||||||||
708 | M = Builder.CreateMemMove( | ||||||||||||||
709 | SI->getPointerOperand(), SI->getAlign(), | ||||||||||||||
710 | LI->getPointerOperand(), LI->getAlign(), Size); | ||||||||||||||
711 | else | ||||||||||||||
712 | M = Builder.CreateMemCpy( | ||||||||||||||
713 | SI->getPointerOperand(), SI->getAlign(), | ||||||||||||||
714 | LI->getPointerOperand(), LI->getAlign(), Size); | ||||||||||||||
715 | |||||||||||||||
716 | LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Promoting " << *LI << " to " << *SI << " => " << *M << "\n" ; } } while (false) | ||||||||||||||
717 | << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Promoting " << *LI << " to " << *SI << " => " << *M << "\n" ; } } while (false); | ||||||||||||||
718 | |||||||||||||||
719 | if (MSSAU) { | ||||||||||||||
720 | auto *LastDef = | ||||||||||||||
721 | cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)); | ||||||||||||||
722 | auto *NewAccess = | ||||||||||||||
723 | MSSAU->createMemoryAccessAfter(M, LastDef, LastDef); | ||||||||||||||
724 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
725 | } | ||||||||||||||
726 | |||||||||||||||
727 | eraseInstruction(SI); | ||||||||||||||
728 | eraseInstruction(LI); | ||||||||||||||
729 | ++NumMemCpyInstr; | ||||||||||||||
730 | |||||||||||||||
731 | // Make sure we do not invalidate the iterator. | ||||||||||||||
732 | BBI = M->getIterator(); | ||||||||||||||
733 | return true; | ||||||||||||||
734 | } | ||||||||||||||
735 | } | ||||||||||||||
736 | |||||||||||||||
737 | // Detect cases where we're performing call slot forwarding, but | ||||||||||||||
738 | // happen to be using a load-store pair to implement it, rather than | ||||||||||||||
739 | // a memcpy. | ||||||||||||||
740 | CallInst *C = nullptr; | ||||||||||||||
741 | if (EnableMemorySSA) { | ||||||||||||||
742 | if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>( | ||||||||||||||
743 | MSSA->getWalker()->getClobberingMemoryAccess(LI))) { | ||||||||||||||
| |||||||||||||||
744 | // The load most post-dom the call. Limit to the same block for now. | ||||||||||||||
745 | // TODO: Support non-local call-slot optimization? | ||||||||||||||
746 | if (LoadClobber->getBlock() == SI->getParent()) | ||||||||||||||
747 | C = dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst()); | ||||||||||||||
748 | } | ||||||||||||||
749 | } else { | ||||||||||||||
750 | MemDepResult ldep = MD->getDependency(LI); | ||||||||||||||
751 | if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst())) | ||||||||||||||
752 | C = dyn_cast<CallInst>(ldep.getInst()); | ||||||||||||||
753 | } | ||||||||||||||
754 | |||||||||||||||
755 | if (C) { | ||||||||||||||
756 | // Check that nothing touches the dest of the "copy" between | ||||||||||||||
757 | // the call and the store. | ||||||||||||||
758 | MemoryLocation StoreLoc = MemoryLocation::get(SI); | ||||||||||||||
759 | if (EnableMemorySSA) { | ||||||||||||||
760 | if (accessedBetween(*AA, StoreLoc, MSSA->getMemoryAccess(C), | ||||||||||||||
761 | MSSA->getMemoryAccess(SI))) | ||||||||||||||
762 | C = nullptr; | ||||||||||||||
763 | } else { | ||||||||||||||
764 | for (BasicBlock::iterator I = --SI->getIterator(), | ||||||||||||||
765 | E = C->getIterator(); | ||||||||||||||
766 | I != E; --I) { | ||||||||||||||
767 | if (isModOrRefSet(AA->getModRefInfo(&*I, StoreLoc))) { | ||||||||||||||
768 | C = nullptr; | ||||||||||||||
769 | break; | ||||||||||||||
770 | } | ||||||||||||||
771 | } | ||||||||||||||
772 | } | ||||||||||||||
773 | } | ||||||||||||||
774 | |||||||||||||||
775 | if (C) { | ||||||||||||||
776 | bool changed = performCallSlotOptzn( | ||||||||||||||
777 | LI, SI, SI->getPointerOperand()->stripPointerCasts(), | ||||||||||||||
778 | LI->getPointerOperand()->stripPointerCasts(), | ||||||||||||||
779 | DL.getTypeStoreSize(SI->getOperand(0)->getType()), | ||||||||||||||
780 | commonAlignment(SI->getAlign(), LI->getAlign()), C); | ||||||||||||||
781 | if (changed) { | ||||||||||||||
782 | eraseInstruction(SI); | ||||||||||||||
783 | eraseInstruction(LI); | ||||||||||||||
784 | ++NumMemCpyInstr; | ||||||||||||||
785 | return true; | ||||||||||||||
786 | } | ||||||||||||||
787 | } | ||||||||||||||
788 | } | ||||||||||||||
789 | } | ||||||||||||||
790 | |||||||||||||||
791 | // There are two cases that are interesting for this code to handle: memcpy | ||||||||||||||
792 | // and memset. Right now we only handle memset. | ||||||||||||||
793 | |||||||||||||||
794 | // Ensure that the value being stored is something that can be memset'able a | ||||||||||||||
795 | // byte at a time like "0" or "-1" or any width, as well as things like | ||||||||||||||
796 | // 0xA0A0A0A0 and 0.0. | ||||||||||||||
797 | auto *V = SI->getOperand(0); | ||||||||||||||
798 | if (Value *ByteVal = isBytewiseValue(V, DL)) { | ||||||||||||||
799 | if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(), | ||||||||||||||
800 | ByteVal)) { | ||||||||||||||
801 | BBI = I->getIterator(); // Don't invalidate iterator. | ||||||||||||||
802 | return true; | ||||||||||||||
803 | } | ||||||||||||||
804 | |||||||||||||||
805 | // If we have an aggregate, we try to promote it to memset regardless | ||||||||||||||
806 | // of opportunity for merging as it can expose optimization opportunities | ||||||||||||||
807 | // in subsequent passes. | ||||||||||||||
808 | auto *T = V->getType(); | ||||||||||||||
809 | if (T->isAggregateType()) { | ||||||||||||||
810 | uint64_t Size = DL.getTypeStoreSize(T); | ||||||||||||||
811 | IRBuilder<> Builder(SI); | ||||||||||||||
812 | auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size, | ||||||||||||||
813 | SI->getAlign()); | ||||||||||||||
814 | |||||||||||||||
815 | LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Promoting " << *SI << " to " << *M << "\n"; } } while (false); | ||||||||||||||
816 | |||||||||||||||
817 | if (MSSAU) { | ||||||||||||||
818 | assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)))((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess (SI))) ? static_cast<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI))" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 818, __PRETTY_FUNCTION__)); | ||||||||||||||
819 | auto *LastDef = | ||||||||||||||
820 | cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)); | ||||||||||||||
821 | auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef); | ||||||||||||||
822 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
823 | } | ||||||||||||||
824 | |||||||||||||||
825 | eraseInstruction(SI); | ||||||||||||||
826 | NumMemSetInfer++; | ||||||||||||||
827 | |||||||||||||||
828 | // Make sure we do not invalidate the iterator. | ||||||||||||||
829 | BBI = M->getIterator(); | ||||||||||||||
830 | return true; | ||||||||||||||
831 | } | ||||||||||||||
832 | } | ||||||||||||||
833 | |||||||||||||||
834 | return false; | ||||||||||||||
835 | } | ||||||||||||||
836 | |||||||||||||||
837 | bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) { | ||||||||||||||
838 | // See if there is another memset or store neighboring this memset which | ||||||||||||||
839 | // allows us to widen out the memset to do a single larger store. | ||||||||||||||
840 | if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile()) | ||||||||||||||
841 | if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(), | ||||||||||||||
842 | MSI->getValue())) { | ||||||||||||||
843 | BBI = I->getIterator(); // Don't invalidate iterator. | ||||||||||||||
844 | return true; | ||||||||||||||
845 | } | ||||||||||||||
846 | return false; | ||||||||||||||
847 | } | ||||||||||||||
848 | |||||||||||||||
849 | /// Takes a memcpy and a call that it depends on, | ||||||||||||||
850 | /// and checks for the possibility of a call slot optimization by having | ||||||||||||||
851 | /// the call write its result directly into the destination of the memcpy. | ||||||||||||||
852 | bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad, | ||||||||||||||
853 | Instruction *cpyStore, Value *cpyDest, | ||||||||||||||
854 | Value *cpySrc, uint64_t cpyLen, | ||||||||||||||
855 | Align cpyAlign, CallInst *C) { | ||||||||||||||
856 | // The general transformation to keep in mind is | ||||||||||||||
857 | // | ||||||||||||||
858 | // call @func(..., src, ...) | ||||||||||||||
859 | // memcpy(dest, src, ...) | ||||||||||||||
860 | // | ||||||||||||||
861 | // -> | ||||||||||||||
862 | // | ||||||||||||||
863 | // memcpy(dest, src, ...) | ||||||||||||||
864 | // call @func(..., dest, ...) | ||||||||||||||
865 | // | ||||||||||||||
866 | // Since moving the memcpy is technically awkward, we additionally check that | ||||||||||||||
867 | // src only holds uninitialized values at the moment of the call, meaning that | ||||||||||||||
868 | // the memcpy can be discarded rather than moved. | ||||||||||||||
869 | |||||||||||||||
870 | // Lifetime marks shouldn't be operated on. | ||||||||||||||
871 | if (Function *F = C->getCalledFunction()) | ||||||||||||||
872 | if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start) | ||||||||||||||
873 | return false; | ||||||||||||||
874 | |||||||||||||||
875 | // Require that src be an alloca. This simplifies the reasoning considerably. | ||||||||||||||
876 | AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc); | ||||||||||||||
877 | if (!srcAlloca) | ||||||||||||||
878 | return false; | ||||||||||||||
879 | |||||||||||||||
880 | ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize()); | ||||||||||||||
881 | if (!srcArraySize) | ||||||||||||||
882 | return false; | ||||||||||||||
883 | |||||||||||||||
884 | const DataLayout &DL = cpyLoad->getModule()->getDataLayout(); | ||||||||||||||
885 | uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) * | ||||||||||||||
886 | srcArraySize->getZExtValue(); | ||||||||||||||
887 | |||||||||||||||
888 | if (cpyLen < srcSize) | ||||||||||||||
889 | return false; | ||||||||||||||
890 | |||||||||||||||
891 | // Check that accessing the first srcSize bytes of dest will not cause a | ||||||||||||||
892 | // trap. Otherwise the transform is invalid since it might cause a trap | ||||||||||||||
893 | // to occur earlier than it otherwise would. | ||||||||||||||
894 | if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpyLen), | ||||||||||||||
895 | DL, C, DT)) | ||||||||||||||
896 | return false; | ||||||||||||||
897 | |||||||||||||||
898 | // Make sure that nothing can observe cpyDest being written early. There are | ||||||||||||||
899 | // a number of cases to consider: | ||||||||||||||
900 | // 1. cpyDest cannot be accessed between C and cpyStore as a precondition of | ||||||||||||||
901 | // the transform. | ||||||||||||||
902 | // 2. C itself may not access cpyDest (prior to the transform). This is | ||||||||||||||
903 | // checked further below. | ||||||||||||||
904 | // 3. If cpyDest is accessible to the caller of this function (potentially | ||||||||||||||
905 | // captured and not based on an alloca), we need to ensure that we cannot | ||||||||||||||
906 | // unwind between C and cpyStore. This is checked here. | ||||||||||||||
907 | // 4. If cpyDest is potentially captured, there may be accesses to it from | ||||||||||||||
908 | // another thread. In this case, we need to check that cpyStore is | ||||||||||||||
909 | // guaranteed to be executed if C is. As it is a non-atomic access, it | ||||||||||||||
910 | // renders accesses from other threads undefined. | ||||||||||||||
911 | // TODO: This is currently not checked. | ||||||||||||||
912 | if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore)) | ||||||||||||||
913 | return false; | ||||||||||||||
914 | |||||||||||||||
915 | // Check that dest points to memory that is at least as aligned as src. | ||||||||||||||
916 | Align srcAlign = srcAlloca->getAlign(); | ||||||||||||||
917 | bool isDestSufficientlyAligned = srcAlign <= cpyAlign; | ||||||||||||||
918 | // If dest is not aligned enough and we can't increase its alignment then | ||||||||||||||
919 | // bail out. | ||||||||||||||
920 | if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest)) | ||||||||||||||
921 | return false; | ||||||||||||||
922 | |||||||||||||||
923 | // Check that src is not accessed except via the call and the memcpy. This | ||||||||||||||
924 | // guarantees that it holds only undefined values when passed in (so the final | ||||||||||||||
925 | // memcpy can be dropped), that it is not read or written between the call and | ||||||||||||||
926 | // the memcpy, and that writing beyond the end of it is undefined. | ||||||||||||||
927 | SmallVector<User *, 8> srcUseList(srcAlloca->users()); | ||||||||||||||
928 | while (!srcUseList.empty()) { | ||||||||||||||
929 | User *U = srcUseList.pop_back_val(); | ||||||||||||||
930 | |||||||||||||||
931 | if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) { | ||||||||||||||
932 | append_range(srcUseList, U->users()); | ||||||||||||||
933 | continue; | ||||||||||||||
934 | } | ||||||||||||||
935 | if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) { | ||||||||||||||
936 | if (!G->hasAllZeroIndices()) | ||||||||||||||
937 | return false; | ||||||||||||||
938 | |||||||||||||||
939 | append_range(srcUseList, U->users()); | ||||||||||||||
940 | continue; | ||||||||||||||
941 | } | ||||||||||||||
942 | if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U)) | ||||||||||||||
943 | if (IT->isLifetimeStartOrEnd()) | ||||||||||||||
944 | continue; | ||||||||||||||
945 | |||||||||||||||
946 | if (U != C && U != cpyLoad) | ||||||||||||||
947 | return false; | ||||||||||||||
948 | } | ||||||||||||||
949 | |||||||||||||||
950 | // Check that src isn't captured by the called function since the | ||||||||||||||
951 | // transformation can cause aliasing issues in that case. | ||||||||||||||
952 | for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI) | ||||||||||||||
953 | if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI)) | ||||||||||||||
954 | return false; | ||||||||||||||
955 | |||||||||||||||
956 | // Since we're changing the parameter to the callsite, we need to make sure | ||||||||||||||
957 | // that what would be the new parameter dominates the callsite. | ||||||||||||||
958 | if (!DT->dominates(cpyDest, C)) { | ||||||||||||||
959 | // Support moving a constant index GEP before the call. | ||||||||||||||
960 | auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest); | ||||||||||||||
961 | if (GEP && GEP->hasAllConstantIndices() && | ||||||||||||||
962 | DT->dominates(GEP->getPointerOperand(), C)) | ||||||||||||||
963 | GEP->moveBefore(C); | ||||||||||||||
964 | else | ||||||||||||||
965 | return false; | ||||||||||||||
966 | } | ||||||||||||||
967 | |||||||||||||||
968 | // In addition to knowing that the call does not access src in some | ||||||||||||||
969 | // unexpected manner, for example via a global, which we deduce from | ||||||||||||||
970 | // the use analysis, we also need to know that it does not sneakily | ||||||||||||||
971 | // access dest. We rely on AA to figure this out for us. | ||||||||||||||
972 | ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize)); | ||||||||||||||
973 | // If necessary, perform additional analysis. | ||||||||||||||
974 | if (isModOrRefSet(MR)) | ||||||||||||||
975 | MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT); | ||||||||||||||
976 | if (isModOrRefSet(MR)) | ||||||||||||||
977 | return false; | ||||||||||||||
978 | |||||||||||||||
979 | // We can't create address space casts here because we don't know if they're | ||||||||||||||
980 | // safe for the target. | ||||||||||||||
981 | if (cpySrc->getType()->getPointerAddressSpace() != | ||||||||||||||
982 | cpyDest->getType()->getPointerAddressSpace()) | ||||||||||||||
983 | return false; | ||||||||||||||
984 | for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI) | ||||||||||||||
985 | if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc && | ||||||||||||||
986 | cpySrc->getType()->getPointerAddressSpace() != | ||||||||||||||
987 | C->getArgOperand(ArgI)->getType()->getPointerAddressSpace()) | ||||||||||||||
988 | return false; | ||||||||||||||
989 | |||||||||||||||
990 | // All the checks have passed, so do the transformation. | ||||||||||||||
991 | bool changedArgument = false; | ||||||||||||||
992 | for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI) | ||||||||||||||
993 | if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) { | ||||||||||||||
994 | Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest | ||||||||||||||
995 | : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), | ||||||||||||||
996 | cpyDest->getName(), C); | ||||||||||||||
997 | changedArgument = true; | ||||||||||||||
998 | if (C->getArgOperand(ArgI)->getType() == Dest->getType()) | ||||||||||||||
999 | C->setArgOperand(ArgI, Dest); | ||||||||||||||
1000 | else | ||||||||||||||
1001 | C->setArgOperand(ArgI, CastInst::CreatePointerCast( | ||||||||||||||
1002 | Dest, C->getArgOperand(ArgI)->getType(), | ||||||||||||||
1003 | Dest->getName(), C)); | ||||||||||||||
1004 | } | ||||||||||||||
1005 | |||||||||||||||
1006 | if (!changedArgument) | ||||||||||||||
1007 | return false; | ||||||||||||||
1008 | |||||||||||||||
1009 | // If the destination wasn't sufficiently aligned then increase its alignment. | ||||||||||||||
1010 | if (!isDestSufficientlyAligned) { | ||||||||||||||
1011 | assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!")((isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!" ) ? static_cast<void> (0) : __assert_fail ("isa<AllocaInst>(cpyDest) && \"Can only increase alloca alignment!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 1011, __PRETTY_FUNCTION__)); | ||||||||||||||
1012 | cast<AllocaInst>(cpyDest)->setAlignment(srcAlign); | ||||||||||||||
1013 | } | ||||||||||||||
1014 | |||||||||||||||
1015 | // Drop any cached information about the call, because we may have changed | ||||||||||||||
1016 | // its dependence information by changing its parameter. | ||||||||||||||
1017 | if (MD) | ||||||||||||||
1018 | MD->removeInstruction(C); | ||||||||||||||
1019 | |||||||||||||||
1020 | // Update AA metadata | ||||||||||||||
1021 | // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be | ||||||||||||||
1022 | // handled here, but combineMetadata doesn't support them yet | ||||||||||||||
1023 | unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, | ||||||||||||||
1024 | LLVMContext::MD_noalias, | ||||||||||||||
1025 | LLVMContext::MD_invariant_group, | ||||||||||||||
1026 | LLVMContext::MD_access_group}; | ||||||||||||||
1027 | combineMetadata(C, cpyLoad, KnownIDs, true); | ||||||||||||||
1028 | |||||||||||||||
1029 | ++NumCallSlot; | ||||||||||||||
1030 | return true; | ||||||||||||||
1031 | } | ||||||||||||||
1032 | |||||||||||||||
1033 | /// We've found that the (upward scanning) memory dependence of memcpy 'M' is | ||||||||||||||
1034 | /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can. | ||||||||||||||
1035 | bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M, | ||||||||||||||
1036 | MemCpyInst *MDep) { | ||||||||||||||
1037 | // We can only transforms memcpy's where the dest of one is the source of the | ||||||||||||||
1038 | // other. | ||||||||||||||
1039 | if (M->getSource() != MDep->getDest() || MDep->isVolatile()) | ||||||||||||||
1040 | return false; | ||||||||||||||
1041 | |||||||||||||||
1042 | // If dep instruction is reading from our current input, then it is a noop | ||||||||||||||
1043 | // transfer and substituting the input won't change this instruction. Just | ||||||||||||||
1044 | // ignore the input and let someone else zap MDep. This handles cases like: | ||||||||||||||
1045 | // memcpy(a <- a) | ||||||||||||||
1046 | // memcpy(b <- a) | ||||||||||||||
1047 | if (M->getSource() == MDep->getSource()) | ||||||||||||||
1048 | return false; | ||||||||||||||
1049 | |||||||||||||||
1050 | // Second, the length of the memcpy's must be the same, or the preceding one | ||||||||||||||
1051 | // must be larger than the following one. | ||||||||||||||
1052 | ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength()); | ||||||||||||||
1053 | ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength()); | ||||||||||||||
1054 | if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue()) | ||||||||||||||
1055 | return false; | ||||||||||||||
1056 | |||||||||||||||
1057 | // Verify that the copied-from memory doesn't change in between the two | ||||||||||||||
1058 | // transfers. For example, in: | ||||||||||||||
1059 | // memcpy(a <- b) | ||||||||||||||
1060 | // *b = 42; | ||||||||||||||
1061 | // memcpy(c <- a) | ||||||||||||||
1062 | // It would be invalid to transform the second memcpy into memcpy(c <- b). | ||||||||||||||
1063 | // | ||||||||||||||
1064 | // TODO: If the code between M and MDep is transparent to the destination "c", | ||||||||||||||
1065 | // then we could still perform the xform by moving M up to the first memcpy. | ||||||||||||||
1066 | if (EnableMemorySSA) { | ||||||||||||||
1067 | // TODO: It would be sufficient to check the MDep source up to the memcpy | ||||||||||||||
1068 | // size of M, rather than MDep. | ||||||||||||||
1069 | if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep), | ||||||||||||||
1070 | MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M))) | ||||||||||||||
1071 | return false; | ||||||||||||||
1072 | } else { | ||||||||||||||
1073 | // NOTE: This is conservative, it will stop on any read from the source loc, | ||||||||||||||
1074 | // not just the defining memcpy. | ||||||||||||||
1075 | MemDepResult SourceDep = | ||||||||||||||
1076 | MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false, | ||||||||||||||
1077 | M->getIterator(), M->getParent()); | ||||||||||||||
1078 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) | ||||||||||||||
1079 | return false; | ||||||||||||||
1080 | } | ||||||||||||||
1081 | |||||||||||||||
1082 | // If the dest of the second might alias the source of the first, then the | ||||||||||||||
1083 | // source and dest might overlap. We still want to eliminate the intermediate | ||||||||||||||
1084 | // value, but we have to generate a memmove instead of memcpy. | ||||||||||||||
1085 | bool UseMemMove = false; | ||||||||||||||
1086 | if (!AA->isNoAlias(MemoryLocation::getForDest(M), | ||||||||||||||
1087 | MemoryLocation::getForSource(MDep))) | ||||||||||||||
1088 | UseMemMove = true; | ||||||||||||||
1089 | |||||||||||||||
1090 | // If all checks passed, then we can transform M. | ||||||||||||||
1091 | LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n" << *MDep << '\n' << *M << '\n'; } } while (false) | ||||||||||||||
1092 | << *MDep << '\n' << *M << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n" << *MDep << '\n' << *M << '\n'; } } while (false); | ||||||||||||||
1093 | |||||||||||||||
1094 | // TODO: Is this worth it if we're creating a less aligned memcpy? For | ||||||||||||||
1095 | // example we could be moving from movaps -> movq on x86. | ||||||||||||||
1096 | IRBuilder<> Builder(M); | ||||||||||||||
1097 | Instruction *NewM; | ||||||||||||||
1098 | if (UseMemMove) | ||||||||||||||
1099 | NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(), | ||||||||||||||
1100 | MDep->getRawSource(), MDep->getSourceAlign(), | ||||||||||||||
1101 | M->getLength(), M->isVolatile()); | ||||||||||||||
1102 | else | ||||||||||||||
1103 | NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(), | ||||||||||||||
1104 | MDep->getRawSource(), MDep->getSourceAlign(), | ||||||||||||||
1105 | M->getLength(), M->isVolatile()); | ||||||||||||||
1106 | |||||||||||||||
1107 | if (MSSAU) { | ||||||||||||||
1108 | assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)))((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess (M))) ? static_cast<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M))" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 1108, __PRETTY_FUNCTION__)); | ||||||||||||||
1109 | auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)); | ||||||||||||||
1110 | auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); | ||||||||||||||
1111 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
1112 | } | ||||||||||||||
1113 | |||||||||||||||
1114 | // Remove the instruction we're replacing. | ||||||||||||||
1115 | eraseInstruction(M); | ||||||||||||||
1116 | ++NumMemCpyInstr; | ||||||||||||||
1117 | return true; | ||||||||||||||
1118 | } | ||||||||||||||
1119 | |||||||||||||||
1120 | /// We've found that the (upward scanning) memory dependence of \p MemCpy is | ||||||||||||||
1121 | /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that | ||||||||||||||
1122 | /// weren't copied over by \p MemCpy. | ||||||||||||||
1123 | /// | ||||||||||||||
1124 | /// In other words, transform: | ||||||||||||||
1125 | /// \code | ||||||||||||||
1126 | /// memset(dst, c, dst_size); | ||||||||||||||
1127 | /// memcpy(dst, src, src_size); | ||||||||||||||
1128 | /// \endcode | ||||||||||||||
1129 | /// into: | ||||||||||||||
1130 | /// \code | ||||||||||||||
1131 | /// memcpy(dst, src, src_size); | ||||||||||||||
1132 | /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size); | ||||||||||||||
1133 | /// \endcode | ||||||||||||||
1134 | bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy, | ||||||||||||||
1135 | MemSetInst *MemSet) { | ||||||||||||||
1136 | // We can only transform memset/memcpy with the same destination. | ||||||||||||||
1137 | if (MemSet->getDest() != MemCpy->getDest()) | ||||||||||||||
1138 | return false; | ||||||||||||||
1139 | |||||||||||||||
1140 | // Check that src and dst of the memcpy aren't the same. While memcpy | ||||||||||||||
1141 | // operands cannot partially overlap, exact equality is allowed. | ||||||||||||||
1142 | if (!AA->isNoAlias(MemoryLocation(MemCpy->getSource(), | ||||||||||||||
1143 | LocationSize::precise(1)), | ||||||||||||||
1144 | MemoryLocation(MemCpy->getDest(), | ||||||||||||||
1145 | LocationSize::precise(1)))) | ||||||||||||||
1146 | return false; | ||||||||||||||
1147 | |||||||||||||||
1148 | if (EnableMemorySSA) { | ||||||||||||||
1149 | // We know that dst up to src_size is not written. We now need to make sure | ||||||||||||||
1150 | // that dst up to dst_size is not accessed. (If we did not move the memset, | ||||||||||||||
1151 | // checking for reads would be sufficient.) | ||||||||||||||
1152 | if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet), | ||||||||||||||
1153 | MSSA->getMemoryAccess(MemSet), | ||||||||||||||
1154 | MSSA->getMemoryAccess(MemCpy))) { | ||||||||||||||
1155 | return false; | ||||||||||||||
1156 | } | ||||||||||||||
1157 | } else { | ||||||||||||||
1158 | // We have already checked that dst up to src_size is not accessed. We | ||||||||||||||
1159 | // need to make sure that there are no accesses up to dst_size either. | ||||||||||||||
1160 | MemDepResult DstDepInfo = MD->getPointerDependencyFrom( | ||||||||||||||
1161 | MemoryLocation::getForDest(MemSet), false, MemCpy->getIterator(), | ||||||||||||||
1162 | MemCpy->getParent()); | ||||||||||||||
1163 | if (DstDepInfo.getInst() != MemSet) | ||||||||||||||
1164 | return false; | ||||||||||||||
1165 | } | ||||||||||||||
1166 | |||||||||||||||
1167 | // Use the same i8* dest as the memcpy, killing the memset dest if different. | ||||||||||||||
1168 | Value *Dest = MemCpy->getRawDest(); | ||||||||||||||
1169 | Value *DestSize = MemSet->getLength(); | ||||||||||||||
1170 | Value *SrcSize = MemCpy->getLength(); | ||||||||||||||
1171 | |||||||||||||||
1172 | if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy)) | ||||||||||||||
1173 | return false; | ||||||||||||||
1174 | |||||||||||||||
1175 | // By default, create an unaligned memset. | ||||||||||||||
1176 | unsigned Align = 1; | ||||||||||||||
1177 | // If Dest is aligned, and SrcSize is constant, use the minimum alignment | ||||||||||||||
1178 | // of the sum. | ||||||||||||||
1179 | const unsigned DestAlign = | ||||||||||||||
1180 | std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment()); | ||||||||||||||
1181 | if (DestAlign > 1) | ||||||||||||||
1182 | if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize)) | ||||||||||||||
1183 | Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign); | ||||||||||||||
1184 | |||||||||||||||
1185 | IRBuilder<> Builder(MemCpy); | ||||||||||||||
1186 | |||||||||||||||
1187 | // If the sizes have different types, zext the smaller one. | ||||||||||||||
1188 | if (DestSize->getType() != SrcSize->getType()) { | ||||||||||||||
1189 | if (DestSize->getType()->getIntegerBitWidth() > | ||||||||||||||
1190 | SrcSize->getType()->getIntegerBitWidth()) | ||||||||||||||
1191 | SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType()); | ||||||||||||||
1192 | else | ||||||||||||||
1193 | DestSize = Builder.CreateZExt(DestSize, SrcSize->getType()); | ||||||||||||||
1194 | } | ||||||||||||||
1195 | |||||||||||||||
1196 | Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize); | ||||||||||||||
1197 | Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize); | ||||||||||||||
1198 | Value *MemsetLen = Builder.CreateSelect( | ||||||||||||||
1199 | Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff); | ||||||||||||||
1200 | Instruction *NewMemSet = Builder.CreateMemSet( | ||||||||||||||
1201 | Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest, | ||||||||||||||
1202 | SrcSize), | ||||||||||||||
1203 | MemSet->getOperand(1), MemsetLen, MaybeAlign(Align)); | ||||||||||||||
1204 | |||||||||||||||
1205 | if (MSSAU) { | ||||||||||||||
1206 | assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess (MemCpy)) && "MemCpy must be a MemoryDef") ? static_cast <void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 1207, __PRETTY_FUNCTION__)) | ||||||||||||||
1207 | "MemCpy must be a MemoryDef")((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess (MemCpy)) && "MemCpy must be a MemoryDef") ? static_cast <void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp" , 1207, __PRETTY_FUNCTION__)); | ||||||||||||||
1208 | // The new memset is inserted after the memcpy, but it is known that its | ||||||||||||||
1209 | // defining access is the memset about to be removed which immediately | ||||||||||||||
1210 | // precedes the memcpy. | ||||||||||||||
1211 | auto *LastDef = | ||||||||||||||
1212 | cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)); | ||||||||||||||
1213 | auto *NewAccess = MSSAU->createMemoryAccessBefore( | ||||||||||||||
1214 | NewMemSet, LastDef->getDefiningAccess(), LastDef); | ||||||||||||||
1215 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
1216 | } | ||||||||||||||
1217 | |||||||||||||||
1218 | eraseInstruction(MemSet); | ||||||||||||||
1219 | return true; | ||||||||||||||
1220 | } | ||||||||||||||
1221 | |||||||||||||||
1222 | /// Determine whether the instruction has undefined content for the given Size, | ||||||||||||||
1223 | /// either because it was freshly alloca'd or started its lifetime. | ||||||||||||||
1224 | static bool hasUndefContents(Instruction *I, ConstantInt *Size) { | ||||||||||||||
1225 | if (isa<AllocaInst>(I)) | ||||||||||||||
1226 | return true; | ||||||||||||||
1227 | |||||||||||||||
1228 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) | ||||||||||||||
1229 | if (II->getIntrinsicID() == Intrinsic::lifetime_start) | ||||||||||||||
1230 | if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0))) | ||||||||||||||
1231 | if (LTSize->getZExtValue() >= Size->getZExtValue()) | ||||||||||||||
1232 | return true; | ||||||||||||||
1233 | |||||||||||||||
1234 | return false; | ||||||||||||||
1235 | } | ||||||||||||||
1236 | |||||||||||||||
1237 | static bool hasUndefContentsMSSA(MemorySSA *MSSA, AliasAnalysis *AA, Value *V, | ||||||||||||||
1238 | MemoryDef *Def, ConstantInt *Size) { | ||||||||||||||
1239 | if (MSSA->isLiveOnEntryDef(Def)) | ||||||||||||||
1240 | return isa<AllocaInst>(getUnderlyingObject(V)); | ||||||||||||||
1241 | |||||||||||||||
1242 | if (IntrinsicInst *II = | ||||||||||||||
1243 | dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) { | ||||||||||||||
1244 | if (II->getIntrinsicID() == Intrinsic::lifetime_start) { | ||||||||||||||
1245 | ConstantInt *LTSize = cast<ConstantInt>(II->getArgOperand(0)); | ||||||||||||||
1246 | if (AA->isMustAlias(V, II->getArgOperand(1)) && | ||||||||||||||
1247 | LTSize->getZExtValue() >= Size->getZExtValue()) | ||||||||||||||
1248 | return true; | ||||||||||||||
1249 | } | ||||||||||||||
1250 | } | ||||||||||||||
1251 | |||||||||||||||
1252 | return false; | ||||||||||||||
1253 | } | ||||||||||||||
1254 | |||||||||||||||
1255 | /// Transform memcpy to memset when its source was just memset. | ||||||||||||||
1256 | /// In other words, turn: | ||||||||||||||
1257 | /// \code | ||||||||||||||
1258 | /// memset(dst1, c, dst1_size); | ||||||||||||||
1259 | /// memcpy(dst2, dst1, dst2_size); | ||||||||||||||
1260 | /// \endcode | ||||||||||||||
1261 | /// into: | ||||||||||||||
1262 | /// \code | ||||||||||||||
1263 | /// memset(dst1, c, dst1_size); | ||||||||||||||
1264 | /// memset(dst2, c, dst2_size); | ||||||||||||||
1265 | /// \endcode | ||||||||||||||
1266 | /// When dst2_size <= dst1_size. | ||||||||||||||
1267 | /// | ||||||||||||||
1268 | /// The \p MemCpy must have a Constant length. | ||||||||||||||
1269 | bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy, | ||||||||||||||
1270 | MemSetInst *MemSet) { | ||||||||||||||
1271 | // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and | ||||||||||||||
1272 | // memcpying from the same address. Otherwise it is hard to reason about. | ||||||||||||||
1273 | if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource())) | ||||||||||||||
1274 | return false; | ||||||||||||||
1275 | |||||||||||||||
1276 | // A known memset size is required. | ||||||||||||||
1277 | ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength()); | ||||||||||||||
1278 | if (!MemSetSize) | ||||||||||||||
1279 | return false; | ||||||||||||||
1280 | |||||||||||||||
1281 | // Make sure the memcpy doesn't read any more than what the memset wrote. | ||||||||||||||
1282 | // Don't worry about sizes larger than i64. | ||||||||||||||
1283 | ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength()); | ||||||||||||||
1284 | if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) { | ||||||||||||||
1285 | // If the memcpy is larger than the memset, but the memory was undef prior | ||||||||||||||
1286 | // to the memset, we can just ignore the tail. Technically we're only | ||||||||||||||
1287 | // interested in the bytes from MemSetSize..CopySize here, but as we can't | ||||||||||||||
1288 | // easily represent this location, we use the full 0..CopySize range. | ||||||||||||||
1289 | MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy); | ||||||||||||||
1290 | bool CanReduceSize = false; | ||||||||||||||
1291 | if (EnableMemorySSA) { | ||||||||||||||
1292 | MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet); | ||||||||||||||
1293 | MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess( | ||||||||||||||
1294 | MemSetAccess->getDefiningAccess(), MemCpyLoc); | ||||||||||||||
1295 | if (auto *MD = dyn_cast<MemoryDef>(Clobber)) | ||||||||||||||
1296 | if (hasUndefContentsMSSA(MSSA, AA, MemCpy->getSource(), MD, CopySize)) | ||||||||||||||
1297 | CanReduceSize = true; | ||||||||||||||
1298 | } else { | ||||||||||||||
1299 | MemDepResult DepInfo = MD->getPointerDependencyFrom( | ||||||||||||||
1300 | MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent()); | ||||||||||||||
1301 | if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize)) | ||||||||||||||
1302 | CanReduceSize = true; | ||||||||||||||
1303 | } | ||||||||||||||
1304 | |||||||||||||||
1305 | if (!CanReduceSize) | ||||||||||||||
1306 | return false; | ||||||||||||||
1307 | CopySize = MemSetSize; | ||||||||||||||
1308 | } | ||||||||||||||
1309 | |||||||||||||||
1310 | IRBuilder<> Builder(MemCpy); | ||||||||||||||
1311 | Instruction *NewM = | ||||||||||||||
1312 | Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), | ||||||||||||||
1313 | CopySize, MaybeAlign(MemCpy->getDestAlignment())); | ||||||||||||||
1314 | if (MSSAU) { | ||||||||||||||
1315 | auto *LastDef = | ||||||||||||||
1316 | cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)); | ||||||||||||||
1317 | auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); | ||||||||||||||
1318 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
1319 | } | ||||||||||||||
1320 | |||||||||||||||
1321 | return true; | ||||||||||||||
1322 | } | ||||||||||||||
1323 | |||||||||||||||
1324 | /// Perform simplification of memcpy's. If we have memcpy A | ||||||||||||||
1325 | /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite | ||||||||||||||
1326 | /// B to be a memcpy from X to Z (or potentially a memmove, depending on | ||||||||||||||
1327 | /// circumstances). This allows later passes to remove the first memcpy | ||||||||||||||
1328 | /// altogether. | ||||||||||||||
1329 | bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) { | ||||||||||||||
1330 | // We can only optimize non-volatile memcpy's. | ||||||||||||||
1331 | if (M->isVolatile()) return false; | ||||||||||||||
1332 | |||||||||||||||
1333 | // If the source and destination of the memcpy are the same, then zap it. | ||||||||||||||
1334 | if (M->getSource() == M->getDest()) { | ||||||||||||||
1335 | ++BBI; | ||||||||||||||
1336 | eraseInstruction(M); | ||||||||||||||
1337 | return true; | ||||||||||||||
1338 | } | ||||||||||||||
1339 | |||||||||||||||
1340 | // If copying from a constant, try to turn the memcpy into a memset. | ||||||||||||||
1341 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource())) | ||||||||||||||
1342 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) | ||||||||||||||
1343 | if (Value *ByteVal = isBytewiseValue(GV->getInitializer(), | ||||||||||||||
1344 | M->getModule()->getDataLayout())) { | ||||||||||||||
1345 | IRBuilder<> Builder(M); | ||||||||||||||
1346 | Instruction *NewM = | ||||||||||||||
1347 | Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), | ||||||||||||||
1348 | MaybeAlign(M->getDestAlignment()), false); | ||||||||||||||
1349 | if (MSSAU) { | ||||||||||||||
1350 | auto *LastDef = | ||||||||||||||
1351 | cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)); | ||||||||||||||
1352 | auto *NewAccess = | ||||||||||||||
1353 | MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); | ||||||||||||||
1354 | MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true); | ||||||||||||||
1355 | } | ||||||||||||||
1356 | |||||||||||||||
1357 | eraseInstruction(M); | ||||||||||||||
1358 | ++NumCpyToSet; | ||||||||||||||
1359 | return true; | ||||||||||||||
1360 | } | ||||||||||||||
1361 | |||||||||||||||
1362 | if (EnableMemorySSA) { | ||||||||||||||
1363 | MemoryUseOrDef *MA = MSSA->getMemoryAccess(M); | ||||||||||||||
1364 | MemoryAccess *AnyClobber = MSSA->getWalker()->getClobberingMemoryAccess(MA); | ||||||||||||||
1365 | MemoryLocation DestLoc = MemoryLocation::getForDest(M); | ||||||||||||||
1366 | const MemoryAccess *DestClobber = | ||||||||||||||
1367 | MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc); | ||||||||||||||
1368 | |||||||||||||||
1369 | // Try to turn a partially redundant memset + memcpy into | ||||||||||||||
1370 | // memcpy + smaller memset. We don't need the memcpy size for this. | ||||||||||||||
1371 | // The memcpy most post-dom the memset, so limit this to the same basic | ||||||||||||||
1372 | // block. A non-local generalization is likely not worthwhile. | ||||||||||||||
1373 | if (auto *MD = dyn_cast<MemoryDef>(DestClobber)) | ||||||||||||||
1374 | if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst())) | ||||||||||||||
1375 | if (DestClobber->getBlock() == M->getParent()) | ||||||||||||||
1376 | if (processMemSetMemCpyDependence(M, MDep)) | ||||||||||||||
1377 | return true; | ||||||||||||||
1378 | |||||||||||||||
1379 | // The optimizations after this point require the memcpy size. | ||||||||||||||
1380 | ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); | ||||||||||||||
1381 | if (!CopySize) return false; | ||||||||||||||
1382 | |||||||||||||||
1383 | MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess( | ||||||||||||||
1384 | AnyClobber, MemoryLocation::getForSource(M)); | ||||||||||||||
1385 | |||||||||||||||
1386 | // There are four possible optimizations we can do for memcpy: | ||||||||||||||
1387 | // a) memcpy-memcpy xform which exposes redundance for DSE. | ||||||||||||||
1388 | // b) call-memcpy xform for return slot optimization. | ||||||||||||||
1389 | // c) memcpy from freshly alloca'd space or space that has just started | ||||||||||||||
1390 | // its lifetime copies undefined data, and we can therefore eliminate | ||||||||||||||
1391 | // the memcpy in favor of the data that was already at the destination. | ||||||||||||||
1392 | // d) memcpy from a just-memset'd source can be turned into memset. | ||||||||||||||
1393 | if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) { | ||||||||||||||
1394 | if (Instruction *MI = MD->getMemoryInst()) { | ||||||||||||||
1395 | if (auto *C = dyn_cast<CallInst>(MI)) { | ||||||||||||||
1396 | // The memcpy must post-dom the call. Limit to the same block for now. | ||||||||||||||
1397 | // Additionally, we need to ensure that there are no accesses to dest | ||||||||||||||
1398 | // between the call and the memcpy. Accesses to src will be checked | ||||||||||||||
1399 | // by performCallSlotOptzn(). | ||||||||||||||
1400 | // TODO: Support non-local call-slot optimization? | ||||||||||||||
1401 | if (C->getParent() == M->getParent() && | ||||||||||||||
1402 | !accessedBetween(*AA, DestLoc, MD, MA)) { | ||||||||||||||
1403 | // FIXME: Can we pass in either of dest/src alignment here instead | ||||||||||||||
1404 | // of conservatively taking the minimum? | ||||||||||||||
1405 | Align Alignment = std::min(M->getDestAlign().valueOrOne(), | ||||||||||||||
1406 | M->getSourceAlign().valueOrOne()); | ||||||||||||||
1407 | if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(), | ||||||||||||||
1408 | CopySize->getZExtValue(), Alignment, C)) { | ||||||||||||||
1409 | LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Performed call slot optimization:\n" << " call: " << *C << "\n" << " memcpy: " << *M << "\n"; } } while (false) | ||||||||||||||
1410 | << " call: " << *C << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Performed call slot optimization:\n" << " call: " << *C << "\n" << " memcpy: " << *M << "\n"; } } while (false) | ||||||||||||||
1411 | << " memcpy: " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Performed call slot optimization:\n" << " call: " << *C << "\n" << " memcpy: " << *M << "\n"; } } while (false); | ||||||||||||||
1412 | eraseInstruction(M); | ||||||||||||||
1413 | ++NumMemCpyInstr; | ||||||||||||||
1414 | return true; | ||||||||||||||
1415 | } | ||||||||||||||
1416 | } | ||||||||||||||
1417 | } | ||||||||||||||
1418 | if (auto *MDep = dyn_cast<MemCpyInst>(MI)) | ||||||||||||||
1419 | return processMemCpyMemCpyDependence(M, MDep); | ||||||||||||||
1420 | if (auto *MDep = dyn_cast<MemSetInst>(MI)) { | ||||||||||||||
1421 | if (performMemCpyToMemSetOptzn(M, MDep)) { | ||||||||||||||
1422 | LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Converted memcpy to memset\n" ; } } while (false); | ||||||||||||||
1423 | eraseInstruction(M); | ||||||||||||||
1424 | ++NumCpyToSet; | ||||||||||||||
1425 | return true; | ||||||||||||||
1426 | } | ||||||||||||||
1427 | } | ||||||||||||||
1428 | } | ||||||||||||||
1429 | |||||||||||||||
1430 | if (hasUndefContentsMSSA(MSSA, AA, M->getSource(), MD, CopySize)) { | ||||||||||||||
1431 | LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "Removed memcpy from undef\n" ; } } while (false); | ||||||||||||||
1432 | eraseInstruction(M); | ||||||||||||||
1433 | ++NumMemCpyInstr; | ||||||||||||||
1434 | return true; | ||||||||||||||
1435 | } | ||||||||||||||
1436 | } | ||||||||||||||
1437 | } else { | ||||||||||||||
1438 | MemDepResult DepInfo = MD->getDependency(M); | ||||||||||||||
1439 | |||||||||||||||
1440 | // Try to turn a partially redundant memset + memcpy into | ||||||||||||||
1441 | // memcpy + smaller memset. We don't need the memcpy size for this. | ||||||||||||||
1442 | if (DepInfo.isClobber()) | ||||||||||||||
1443 | if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst())) | ||||||||||||||
1444 | if (processMemSetMemCpyDependence(M, MDep)) | ||||||||||||||
1445 | return true; | ||||||||||||||
1446 | |||||||||||||||
1447 | // The optimizations after this point require the memcpy size. | ||||||||||||||
1448 | ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); | ||||||||||||||
1449 | if (!CopySize) return false; | ||||||||||||||
1450 | |||||||||||||||
1451 | // There are four possible optimizations we can do for memcpy: | ||||||||||||||
1452 | // a) memcpy-memcpy xform which exposes redundance for DSE. | ||||||||||||||
1453 | // b) call-memcpy xform for return slot optimization. | ||||||||||||||
1454 | // c) memcpy from freshly alloca'd space or space that has just started | ||||||||||||||
1455 | // its lifetime copies undefined data, and we can therefore eliminate | ||||||||||||||
1456 | // the memcpy in favor of the data that was already at the destination. | ||||||||||||||
1457 | // d) memcpy from a just-memset'd source can be turned into memset. | ||||||||||||||
1458 | if (DepInfo.isClobber()) { | ||||||||||||||
1459 | if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { | ||||||||||||||
1460 | // FIXME: Can we pass in either of dest/src alignment here instead | ||||||||||||||
1461 | // of conservatively taking the minimum? | ||||||||||||||
1462 | Align Alignment = std::min(M->getDestAlign().valueOrOne(), | ||||||||||||||
1463 | M->getSourceAlign().valueOrOne()); | ||||||||||||||
1464 | if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(), | ||||||||||||||
1465 | CopySize->getZExtValue(), Alignment, C)) { | ||||||||||||||
1466 | eraseInstruction(M); | ||||||||||||||
1467 | ++NumMemCpyInstr; | ||||||||||||||
1468 | return true; | ||||||||||||||
1469 | } | ||||||||||||||
1470 | } | ||||||||||||||
1471 | } | ||||||||||||||
1472 | |||||||||||||||
1473 | MemoryLocation SrcLoc = MemoryLocation::getForSource(M); | ||||||||||||||
1474 | MemDepResult SrcDepInfo = MD->getPointerDependencyFrom( | ||||||||||||||
1475 | SrcLoc, true, M->getIterator(), M->getParent()); | ||||||||||||||
1476 | |||||||||||||||
1477 | if (SrcDepInfo.isClobber()) { | ||||||||||||||
1478 | if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst())) | ||||||||||||||
1479 | return processMemCpyMemCpyDependence(M, MDep); | ||||||||||||||
1480 | } else if (SrcDepInfo.isDef()) { | ||||||||||||||
1481 | if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) { | ||||||||||||||
1482 | eraseInstruction(M); | ||||||||||||||
1483 | ++NumMemCpyInstr; | ||||||||||||||
1484 | return true; | ||||||||||||||
1485 | } | ||||||||||||||
1486 | } | ||||||||||||||
1487 | |||||||||||||||
1488 | if (SrcDepInfo.isClobber()) | ||||||||||||||
1489 | if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst())) | ||||||||||||||
1490 | if (performMemCpyToMemSetOptzn(M, MDep)) { | ||||||||||||||
1491 | eraseInstruction(M); | ||||||||||||||
1492 | ++NumCpyToSet; | ||||||||||||||
1493 | return true; | ||||||||||||||
1494 | } | ||||||||||||||
1495 | } | ||||||||||||||
1496 | |||||||||||||||
1497 | return false; | ||||||||||||||
1498 | } | ||||||||||||||
1499 | |||||||||||||||
1500 | /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed | ||||||||||||||
1501 | /// not to alias. | ||||||||||||||
1502 | bool MemCpyOptPass::processMemMove(MemMoveInst *M) { | ||||||||||||||
1503 | if (!TLI->has(LibFunc_memmove)) | ||||||||||||||
1504 | return false; | ||||||||||||||
1505 | |||||||||||||||
1506 | // See if the pointers alias. | ||||||||||||||
1507 | if (!AA->isNoAlias(MemoryLocation::getForDest(M), | ||||||||||||||
1508 | MemoryLocation::getForSource(M))) | ||||||||||||||
1509 | return false; | ||||||||||||||
1510 | |||||||||||||||
1511 | LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *Mdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M << "\n"; } } while (false) | ||||||||||||||
1512 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M << "\n"; } } while (false); | ||||||||||||||
1513 | |||||||||||||||
1514 | // If not, then we know we can transform this. | ||||||||||||||
1515 | Type *ArgTys[3] = { M->getRawDest()->getType(), | ||||||||||||||
1516 | M->getRawSource()->getType(), | ||||||||||||||
1517 | M->getLength()->getType() }; | ||||||||||||||
1518 | M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(), | ||||||||||||||
1519 | Intrinsic::memcpy, ArgTys)); | ||||||||||||||
1520 | |||||||||||||||
1521 | // For MemorySSA nothing really changes (except that memcpy may imply stricter | ||||||||||||||
1522 | // aliasing guarantees). | ||||||||||||||
1523 | |||||||||||||||
1524 | // MemDep may have over conservative information about this instruction, just | ||||||||||||||
1525 | // conservatively flush it from the cache. | ||||||||||||||
1526 | if (MD) | ||||||||||||||
1527 | MD->removeInstruction(M); | ||||||||||||||
1528 | |||||||||||||||
1529 | ++NumMoveToCpy; | ||||||||||||||
1530 | return true; | ||||||||||||||
1531 | } | ||||||||||||||
1532 | |||||||||||||||
1533 | /// This is called on every byval argument in call sites. | ||||||||||||||
1534 | bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) { | ||||||||||||||
1535 | const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout(); | ||||||||||||||
1536 | // Find out what feeds this byval argument. | ||||||||||||||
1537 | Value *ByValArg = CB.getArgOperand(ArgNo); | ||||||||||||||
1538 | Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType(); | ||||||||||||||
1539 | uint64_t ByValSize = DL.getTypeAllocSize(ByValTy); | ||||||||||||||
1540 | MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize)); | ||||||||||||||
1541 | MemCpyInst *MDep = nullptr; | ||||||||||||||
1542 | if (EnableMemorySSA) { | ||||||||||||||
1543 | MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB); | ||||||||||||||
1544 | MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess( | ||||||||||||||
1545 | CallAccess->getDefiningAccess(), Loc); | ||||||||||||||
1546 | if (auto *MD = dyn_cast<MemoryDef>(Clobber)) | ||||||||||||||
1547 | MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst()); | ||||||||||||||
1548 | } else { | ||||||||||||||
1549 | MemDepResult DepInfo = MD->getPointerDependencyFrom( | ||||||||||||||
1550 | Loc, true, CB.getIterator(), CB.getParent()); | ||||||||||||||
1551 | if (!DepInfo.isClobber()) | ||||||||||||||
1552 | return false; | ||||||||||||||
1553 | MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); | ||||||||||||||
1554 | } | ||||||||||||||
1555 | |||||||||||||||
1556 | // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by | ||||||||||||||
1557 | // a memcpy, see if we can byval from the source of the memcpy instead of the | ||||||||||||||
1558 | // result. | ||||||||||||||
1559 | if (!MDep || MDep->isVolatile() || | ||||||||||||||
1560 | ByValArg->stripPointerCasts() != MDep->getDest()) | ||||||||||||||
1561 | return false; | ||||||||||||||
1562 | |||||||||||||||
1563 | // The length of the memcpy must be larger or equal to the size of the byval. | ||||||||||||||
1564 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); | ||||||||||||||
1565 | if (!C1 || C1->getValue().getZExtValue() < ByValSize) | ||||||||||||||
1566 | return false; | ||||||||||||||
1567 | |||||||||||||||
1568 | // Get the alignment of the byval. If the call doesn't specify the alignment, | ||||||||||||||
1569 | // then it is some target specific value that we can't know. | ||||||||||||||
1570 | MaybeAlign ByValAlign = CB.getParamAlign(ArgNo); | ||||||||||||||
1571 | if (!ByValAlign) return false; | ||||||||||||||
1572 | |||||||||||||||
1573 | // If it is greater than the memcpy, then we check to see if we can force the | ||||||||||||||
1574 | // source of the memcpy to the alignment we need. If we fail, we bail out. | ||||||||||||||
1575 | MaybeAlign MemDepAlign = MDep->getSourceAlign(); | ||||||||||||||
1576 | if ((!MemDepAlign || *MemDepAlign < *ByValAlign) && | ||||||||||||||
1577 | getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC, | ||||||||||||||
1578 | DT) < *ByValAlign) | ||||||||||||||
1579 | return false; | ||||||||||||||
1580 | |||||||||||||||
1581 | // The address space of the memcpy source must match the byval argument | ||||||||||||||
1582 | if (MDep->getSource()->getType()->getPointerAddressSpace() != | ||||||||||||||
1583 | ByValArg->getType()->getPointerAddressSpace()) | ||||||||||||||
1584 | return false; | ||||||||||||||
1585 | |||||||||||||||
1586 | // Verify that the copied-from memory doesn't change in between the memcpy and | ||||||||||||||
1587 | // the byval call. | ||||||||||||||
1588 | // memcpy(a <- b) | ||||||||||||||
1589 | // *b = 42; | ||||||||||||||
1590 | // foo(*a) | ||||||||||||||
1591 | // It would be invalid to transform the second memcpy into foo(*b). | ||||||||||||||
1592 | if (EnableMemorySSA) { | ||||||||||||||
1593 | if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep), | ||||||||||||||
1594 | MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB))) | ||||||||||||||
1595 | return false; | ||||||||||||||
1596 | } else { | ||||||||||||||
1597 | // NOTE: This is conservative, it will stop on any read from the source loc, | ||||||||||||||
1598 | // not just the defining memcpy. | ||||||||||||||
1599 | MemDepResult SourceDep = MD->getPointerDependencyFrom( | ||||||||||||||
1600 | MemoryLocation::getForSource(MDep), false, | ||||||||||||||
1601 | CB.getIterator(), MDep->getParent()); | ||||||||||||||
1602 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) | ||||||||||||||
1603 | return false; | ||||||||||||||
1604 | } | ||||||||||||||
1605 | |||||||||||||||
1606 | Value *TmpCast = MDep->getSource(); | ||||||||||||||
1607 | if (MDep->getSource()->getType() != ByValArg->getType()) { | ||||||||||||||
1608 | BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), | ||||||||||||||
1609 | "tmpcast", &CB); | ||||||||||||||
1610 | // Set the tmpcast's DebugLoc to MDep's | ||||||||||||||
1611 | TmpBitCast->setDebugLoc(MDep->getDebugLoc()); | ||||||||||||||
1612 | TmpCast = TmpBitCast; | ||||||||||||||
1613 | } | ||||||||||||||
1614 | |||||||||||||||
1615 | LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" << " " << *MDep << "\n" << " " << CB << "\n"; } } while (false) | ||||||||||||||
1616 | << " " << *MDep << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" << " " << *MDep << "\n" << " " << CB << "\n"; } } while (false) | ||||||||||||||
1617 | << " " << CB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" << " " << *MDep << "\n" << " " << CB << "\n"; } } while (false); | ||||||||||||||
1618 | |||||||||||||||
1619 | // Otherwise we're good! Update the byval argument. | ||||||||||||||
1620 | CB.setArgOperand(ArgNo, TmpCast); | ||||||||||||||
1621 | ++NumMemCpyInstr; | ||||||||||||||
1622 | return true; | ||||||||||||||
1623 | } | ||||||||||||||
1624 | |||||||||||||||
1625 | /// Executes one iteration of MemCpyOptPass. | ||||||||||||||
1626 | bool MemCpyOptPass::iterateOnFunction(Function &F) { | ||||||||||||||
1627 | bool MadeChange = false; | ||||||||||||||
1628 | |||||||||||||||
1629 | // Walk all instruction in the function. | ||||||||||||||
1630 | for (BasicBlock &BB : F) { | ||||||||||||||
1631 | // Skip unreachable blocks. For example processStore assumes that an | ||||||||||||||
1632 | // instruction in a BB can't be dominated by a later instruction in the | ||||||||||||||
1633 | // same BB (which is a scenario that can happen for an unreachable BB that | ||||||||||||||
1634 | // has itself as a predecessor). | ||||||||||||||
1635 | if (!DT->isReachableFromEntry(&BB)) | ||||||||||||||
1636 | continue; | ||||||||||||||
1637 | |||||||||||||||
1638 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { | ||||||||||||||
1639 | // Avoid invalidating the iterator. | ||||||||||||||
1640 | Instruction *I = &*BI++; | ||||||||||||||
1641 | |||||||||||||||
1642 | bool RepeatInstruction = false; | ||||||||||||||
1643 | |||||||||||||||
1644 | if (StoreInst *SI
| ||||||||||||||
1645 | MadeChange |= processStore(SI, BI); | ||||||||||||||
1646 | else if (MemSetInst *M = dyn_cast<MemSetInst>(I)) | ||||||||||||||
1647 | RepeatInstruction = processMemSet(M, BI); | ||||||||||||||
1648 | else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) | ||||||||||||||
1649 | RepeatInstruction = processMemCpy(M, BI); | ||||||||||||||
1650 | else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) | ||||||||||||||
1651 | RepeatInstruction = processMemMove(M); | ||||||||||||||
1652 | else if (auto *CB = dyn_cast<CallBase>(I)) { | ||||||||||||||
1653 | for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) | ||||||||||||||
1654 | if (CB->isByValArgument(i)) | ||||||||||||||
1655 | MadeChange |= processByValArgument(*CB, i); | ||||||||||||||
1656 | } | ||||||||||||||
1657 | |||||||||||||||
1658 | // Reprocess the instruction if desired. | ||||||||||||||
1659 | if (RepeatInstruction) { | ||||||||||||||
1660 | if (BI != BB.begin()) | ||||||||||||||
1661 | --BI; | ||||||||||||||
1662 | MadeChange = true; | ||||||||||||||
1663 | } | ||||||||||||||
1664 | } | ||||||||||||||
1665 | } | ||||||||||||||
1666 | |||||||||||||||
1667 | return MadeChange; | ||||||||||||||
1668 | } | ||||||||||||||
1669 | |||||||||||||||
1670 | PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) { | ||||||||||||||
1671 | auto *MD = !EnableMemorySSA ? &AM.getResult<MemoryDependenceAnalysis>(F) | ||||||||||||||
1672 | : AM.getCachedResult<MemoryDependenceAnalysis>(F); | ||||||||||||||
1673 | auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); | ||||||||||||||
1674 | auto *AA = &AM.getResult<AAManager>(F); | ||||||||||||||
1675 | auto *AC = &AM.getResult<AssumptionAnalysis>(F); | ||||||||||||||
1676 | auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); | ||||||||||||||
1677 | auto *MSSA = EnableMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F) | ||||||||||||||
1678 | : AM.getCachedResult<MemorySSAAnalysis>(F); | ||||||||||||||
1679 | |||||||||||||||
1680 | bool MadeChange = | ||||||||||||||
1681 | runImpl(F, MD, &TLI, AA, AC, DT, MSSA ? &MSSA->getMSSA() : nullptr); | ||||||||||||||
1682 | if (!MadeChange) | ||||||||||||||
1683 | return PreservedAnalyses::all(); | ||||||||||||||
1684 | |||||||||||||||
1685 | PreservedAnalyses PA; | ||||||||||||||
1686 | PA.preserveSet<CFGAnalyses>(); | ||||||||||||||
1687 | PA.preserve<GlobalsAA>(); | ||||||||||||||
1688 | if (MD) | ||||||||||||||
1689 | PA.preserve<MemoryDependenceAnalysis>(); | ||||||||||||||
1690 | if (MSSA) | ||||||||||||||
1691 | PA.preserve<MemorySSAAnalysis>(); | ||||||||||||||
1692 | return PA; | ||||||||||||||
1693 | } | ||||||||||||||
1694 | |||||||||||||||
1695 | bool MemCpyOptPass::runImpl(Function &F, MemoryDependenceResults *MD_, | ||||||||||||||
1696 | TargetLibraryInfo *TLI_, AliasAnalysis *AA_, | ||||||||||||||
1697 | AssumptionCache *AC_, DominatorTree *DT_, | ||||||||||||||
1698 | MemorySSA *MSSA_) { | ||||||||||||||
1699 | bool MadeChange = false; | ||||||||||||||
1700 | MD = MD_; | ||||||||||||||
1701 | TLI = TLI_; | ||||||||||||||
1702 | AA = AA_; | ||||||||||||||
1703 | AC = AC_; | ||||||||||||||
1704 | DT = DT_; | ||||||||||||||
1705 | MSSA = MSSA_; | ||||||||||||||
1706 | MemorySSAUpdater MSSAU_(MSSA_); | ||||||||||||||
1707 | MSSAU = MSSA_
| ||||||||||||||
1708 | // If we don't have at least memset and memcpy, there is little point of doing | ||||||||||||||
1709 | // anything here. These are required by a freestanding implementation, so if | ||||||||||||||
1710 | // even they are disabled, there is no point in trying hard. | ||||||||||||||
1711 | if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy)) | ||||||||||||||
1712 | return false; | ||||||||||||||
1713 | |||||||||||||||
1714 | while (true) { | ||||||||||||||
1715 | if (!iterateOnFunction(F)) | ||||||||||||||
1716 | break; | ||||||||||||||
1717 | MadeChange = true; | ||||||||||||||
1718 | } | ||||||||||||||
1719 | |||||||||||||||
1720 | if (MSSA_ && VerifyMemorySSA) | ||||||||||||||
1721 | MSSA_->verifyMemorySSA(); | ||||||||||||||
1722 | |||||||||||||||
1723 | MD = nullptr; | ||||||||||||||
1724 | return MadeChange; | ||||||||||||||
1725 | } | ||||||||||||||
1726 | |||||||||||||||
1727 | /// This is the main transformation entry point for a function. | ||||||||||||||
1728 | bool MemCpyOptLegacyPass::runOnFunction(Function &F) { | ||||||||||||||
1729 | if (skipFunction(F)) | ||||||||||||||
| |||||||||||||||
1730 | return false; | ||||||||||||||
1731 | |||||||||||||||
1732 | auto *MDWP = !EnableMemorySSA | ||||||||||||||
1733 | ? &getAnalysis<MemoryDependenceWrapperPass>() | ||||||||||||||
1734 | : getAnalysisIfAvailable<MemoryDependenceWrapperPass>(); | ||||||||||||||
1735 | auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); | ||||||||||||||
1736 | auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); | ||||||||||||||
1737 | auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); | ||||||||||||||
1738 | auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); | ||||||||||||||
1739 | auto *MSSAWP = EnableMemorySSA | ||||||||||||||
1740 | ? &getAnalysis<MemorySSAWrapperPass>() | ||||||||||||||
1741 | : getAnalysisIfAvailable<MemorySSAWrapperPass>(); | ||||||||||||||
1742 | |||||||||||||||
1743 | return Impl.runImpl(F, MDWP ? & MDWP->getMemDep() : nullptr, TLI, AA, AC, DT, | ||||||||||||||
1744 | MSSAWP
| ||||||||||||||
1745 | } |
1 | //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===// |
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 file exposes the class definitions of all of the subclasses of the |
10 | // Instruction class. This is meant to be an easy way to get access to all |
11 | // instruction subclasses. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_IR_INSTRUCTIONS_H |
16 | #define LLVM_IR_INSTRUCTIONS_H |
17 | |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/Bitfields.h" |
20 | #include "llvm/ADT/None.h" |
21 | #include "llvm/ADT/STLExtras.h" |
22 | #include "llvm/ADT/SmallVector.h" |
23 | #include "llvm/ADT/StringRef.h" |
24 | #include "llvm/ADT/Twine.h" |
25 | #include "llvm/ADT/iterator.h" |
26 | #include "llvm/ADT/iterator_range.h" |
27 | #include "llvm/IR/Attributes.h" |
28 | #include "llvm/IR/BasicBlock.h" |
29 | #include "llvm/IR/CallingConv.h" |
30 | #include "llvm/IR/CFG.h" |
31 | #include "llvm/IR/Constant.h" |
32 | #include "llvm/IR/DerivedTypes.h" |
33 | #include "llvm/IR/Function.h" |
34 | #include "llvm/IR/InstrTypes.h" |
35 | #include "llvm/IR/Instruction.h" |
36 | #include "llvm/IR/OperandTraits.h" |
37 | #include "llvm/IR/Type.h" |
38 | #include "llvm/IR/Use.h" |
39 | #include "llvm/IR/User.h" |
40 | #include "llvm/IR/Value.h" |
41 | #include "llvm/Support/AtomicOrdering.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/ErrorHandling.h" |
44 | #include <cassert> |
45 | #include <cstddef> |
46 | #include <cstdint> |
47 | #include <iterator> |
48 | |
49 | namespace llvm { |
50 | |
51 | class APInt; |
52 | class ConstantInt; |
53 | class DataLayout; |
54 | class LLVMContext; |
55 | |
56 | //===----------------------------------------------------------------------===// |
57 | // AllocaInst Class |
58 | //===----------------------------------------------------------------------===// |
59 | |
60 | /// an instruction to allocate memory on the stack |
61 | class AllocaInst : public UnaryInstruction { |
62 | Type *AllocatedType; |
63 | |
64 | using AlignmentField = AlignmentBitfieldElementT<0>; |
65 | using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>; |
66 | using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>; |
67 | static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField, |
68 | SwiftErrorField>(), |
69 | "Bitfields must be contiguous"); |
70 | |
71 | protected: |
72 | // Note: Instruction needs to be a friend here to call cloneImpl. |
73 | friend class Instruction; |
74 | |
75 | AllocaInst *cloneImpl() const; |
76 | |
77 | public: |
78 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
79 | const Twine &Name, Instruction *InsertBefore); |
80 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
81 | const Twine &Name, BasicBlock *InsertAtEnd); |
82 | |
83 | AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
84 | Instruction *InsertBefore); |
85 | AllocaInst(Type *Ty, unsigned AddrSpace, |
86 | const Twine &Name, BasicBlock *InsertAtEnd); |
87 | |
88 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
89 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
90 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
91 | const Twine &Name, BasicBlock *InsertAtEnd); |
92 | |
93 | /// Return true if there is an allocation size parameter to the allocation |
94 | /// instruction that is not 1. |
95 | bool isArrayAllocation() const; |
96 | |
97 | /// Get the number of elements allocated. For a simple allocation of a single |
98 | /// element, this will return a constant 1 value. |
99 | const Value *getArraySize() const { return getOperand(0); } |
100 | Value *getArraySize() { return getOperand(0); } |
101 | |
102 | /// Overload to return most specific pointer type. |
103 | PointerType *getType() const { |
104 | return cast<PointerType>(Instruction::getType()); |
105 | } |
106 | |
107 | /// Get allocation size in bits. Returns None if size can't be determined, |
108 | /// e.g. in case of a VLA. |
109 | Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const; |
110 | |
111 | /// Return the type that is being allocated by the instruction. |
112 | Type *getAllocatedType() const { return AllocatedType; } |
113 | /// for use only in special circumstances that need to generically |
114 | /// transform a whole instruction (eg: IR linking and vectorization). |
115 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
116 | |
117 | /// Return the alignment of the memory that is being allocated by the |
118 | /// instruction. |
119 | Align getAlign() const { |
120 | return Align(1ULL << getSubclassData<AlignmentField>()); |
121 | } |
122 | |
123 | void setAlignment(Align Align) { |
124 | setSubclassData<AlignmentField>(Log2(Align)); |
125 | } |
126 | |
127 | // FIXME: Remove this one transition to Align is over. |
128 | unsigned getAlignment() const { return getAlign().value(); } |
129 | |
130 | /// Return true if this alloca is in the entry block of the function and is a |
131 | /// constant size. If so, the code generator will fold it into the |
132 | /// prolog/epilog code, so it is basically free. |
133 | bool isStaticAlloca() const; |
134 | |
135 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
136 | /// allocas are never considered static even if they are in the entry block. |
137 | bool isUsedWithInAlloca() const { |
138 | return getSubclassData<UsedWithInAllocaField>(); |
139 | } |
140 | |
141 | /// Specify whether this alloca is used to represent the arguments to a call. |
142 | void setUsedWithInAlloca(bool V) { |
143 | setSubclassData<UsedWithInAllocaField>(V); |
144 | } |
145 | |
146 | /// Return true if this alloca is used as a swifterror argument to a call. |
147 | bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); } |
148 | /// Specify whether this alloca is used to represent a swifterror. |
149 | void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); } |
150 | |
151 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
152 | static bool classof(const Instruction *I) { |
153 | return (I->getOpcode() == Instruction::Alloca); |
154 | } |
155 | static bool classof(const Value *V) { |
156 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
157 | } |
158 | |
159 | private: |
160 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
161 | // method so that subclasses cannot accidentally use it. |
162 | template <typename Bitfield> |
163 | void setSubclassData(typename Bitfield::Type Value) { |
164 | Instruction::setSubclassData<Bitfield>(Value); |
165 | } |
166 | }; |
167 | |
168 | //===----------------------------------------------------------------------===// |
169 | // LoadInst Class |
170 | //===----------------------------------------------------------------------===// |
171 | |
172 | /// An instruction for reading from memory. This uses the SubclassData field in |
173 | /// Value to store whether or not the load is volatile. |
174 | class LoadInst : public UnaryInstruction { |
175 | using VolatileField = BoolBitfieldElementT<0>; |
176 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
177 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
178 | static_assert( |
179 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
180 | "Bitfields must be contiguous"); |
181 | |
182 | void AssertOK(); |
183 | |
184 | protected: |
185 | // Note: Instruction needs to be a friend here to call cloneImpl. |
186 | friend class Instruction; |
187 | |
188 | LoadInst *cloneImpl() const; |
189 | |
190 | public: |
191 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, |
192 | Instruction *InsertBefore); |
193 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
194 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
195 | Instruction *InsertBefore); |
196 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
197 | BasicBlock *InsertAtEnd); |
198 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
199 | Align Align, Instruction *InsertBefore = nullptr); |
200 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
201 | Align Align, BasicBlock *InsertAtEnd); |
202 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
203 | Align Align, AtomicOrdering Order, |
204 | SyncScope::ID SSID = SyncScope::System, |
205 | Instruction *InsertBefore = nullptr); |
206 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
207 | Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
208 | BasicBlock *InsertAtEnd); |
209 | |
210 | /// Return true if this is a load from a volatile memory location. |
211 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
212 | |
213 | /// Specify whether this is a volatile load or not. |
214 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
215 | |
216 | /// Return the alignment of the access that is being performed. |
217 | /// FIXME: Remove this function once transition to Align is over. |
218 | /// Use getAlign() instead. |
219 | unsigned getAlignment() const { return getAlign().value(); } |
220 | |
221 | /// Return the alignment of the access that is being performed. |
222 | Align getAlign() const { |
223 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
224 | } |
225 | |
226 | void setAlignment(Align Align) { |
227 | setSubclassData<AlignmentField>(Log2(Align)); |
228 | } |
229 | |
230 | /// Returns the ordering constraint of this load instruction. |
231 | AtomicOrdering getOrdering() const { |
232 | return getSubclassData<OrderingField>(); |
233 | } |
234 | /// Sets the ordering constraint of this load instruction. May not be Release |
235 | /// or AcquireRelease. |
236 | void setOrdering(AtomicOrdering Ordering) { |
237 | setSubclassData<OrderingField>(Ordering); |
238 | } |
239 | |
240 | /// Returns the synchronization scope ID of this load instruction. |
241 | SyncScope::ID getSyncScopeID() const { |
242 | return SSID; |
243 | } |
244 | |
245 | /// Sets the synchronization scope ID of this load instruction. |
246 | void setSyncScopeID(SyncScope::ID SSID) { |
247 | this->SSID = SSID; |
248 | } |
249 | |
250 | /// Sets the ordering constraint and the synchronization scope ID of this load |
251 | /// instruction. |
252 | void setAtomic(AtomicOrdering Ordering, |
253 | SyncScope::ID SSID = SyncScope::System) { |
254 | setOrdering(Ordering); |
255 | setSyncScopeID(SSID); |
256 | } |
257 | |
258 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
259 | |
260 | bool isUnordered() const { |
261 | return (getOrdering() == AtomicOrdering::NotAtomic || |
262 | getOrdering() == AtomicOrdering::Unordered) && |
263 | !isVolatile(); |
264 | } |
265 | |
266 | Value *getPointerOperand() { return getOperand(0); } |
267 | const Value *getPointerOperand() const { return getOperand(0); } |
268 | static unsigned getPointerOperandIndex() { return 0U; } |
269 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
270 | |
271 | /// Returns the address space of the pointer operand. |
272 | unsigned getPointerAddressSpace() const { |
273 | return getPointerOperandType()->getPointerAddressSpace(); |
274 | } |
275 | |
276 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
277 | static bool classof(const Instruction *I) { |
278 | return I->getOpcode() == Instruction::Load; |
279 | } |
280 | static bool classof(const Value *V) { |
281 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
282 | } |
283 | |
284 | private: |
285 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
286 | // method so that subclasses cannot accidentally use it. |
287 | template <typename Bitfield> |
288 | void setSubclassData(typename Bitfield::Type Value) { |
289 | Instruction::setSubclassData<Bitfield>(Value); |
290 | } |
291 | |
292 | /// The synchronization scope ID of this load instruction. Not quite enough |
293 | /// room in SubClassData for everything, so synchronization scope ID gets its |
294 | /// own field. |
295 | SyncScope::ID SSID; |
296 | }; |
297 | |
298 | //===----------------------------------------------------------------------===// |
299 | // StoreInst Class |
300 | //===----------------------------------------------------------------------===// |
301 | |
302 | /// An instruction for storing to memory. |
303 | class StoreInst : public Instruction { |
304 | using VolatileField = BoolBitfieldElementT<0>; |
305 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
306 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
307 | static_assert( |
308 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
309 | "Bitfields must be contiguous"); |
310 | |
311 | void AssertOK(); |
312 | |
313 | protected: |
314 | // Note: Instruction needs to be a friend here to call cloneImpl. |
315 | friend class Instruction; |
316 | |
317 | StoreInst *cloneImpl() const; |
318 | |
319 | public: |
320 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
321 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
322 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore); |
323 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
324 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
325 | Instruction *InsertBefore = nullptr); |
326 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
327 | BasicBlock *InsertAtEnd); |
328 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
329 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
330 | Instruction *InsertBefore = nullptr); |
331 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
332 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
333 | |
334 | // allocate space for exactly two operands |
335 | void *operator new(size_t s) { |
336 | return User::operator new(s, 2); |
337 | } |
338 | |
339 | /// Return true if this is a store to a volatile memory location. |
340 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
341 | |
342 | /// Specify whether this is a volatile store or not. |
343 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
344 | |
345 | /// Transparently provide more efficient getOperand methods. |
346 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
347 | |
348 | /// Return the alignment of the access that is being performed |
349 | /// FIXME: Remove this function once transition to Align is over. |
350 | /// Use getAlign() instead. |
351 | unsigned getAlignment() const { return getAlign().value(); } |
352 | |
353 | Align getAlign() const { |
354 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
355 | } |
356 | |
357 | void setAlignment(Align Align) { |
358 | setSubclassData<AlignmentField>(Log2(Align)); |
359 | } |
360 | |
361 | /// Returns the ordering constraint of this store instruction. |
362 | AtomicOrdering getOrdering() const { |
363 | return getSubclassData<OrderingField>(); |
364 | } |
365 | |
366 | /// Sets the ordering constraint of this store instruction. May not be |
367 | /// Acquire or AcquireRelease. |
368 | void setOrdering(AtomicOrdering Ordering) { |
369 | setSubclassData<OrderingField>(Ordering); |
370 | } |
371 | |
372 | /// Returns the synchronization scope ID of this store instruction. |
373 | SyncScope::ID getSyncScopeID() const { |
374 | return SSID; |
375 | } |
376 | |
377 | /// Sets the synchronization scope ID of this store instruction. |
378 | void setSyncScopeID(SyncScope::ID SSID) { |
379 | this->SSID = SSID; |
380 | } |
381 | |
382 | /// Sets the ordering constraint and the synchronization scope ID of this |
383 | /// store instruction. |
384 | void setAtomic(AtomicOrdering Ordering, |
385 | SyncScope::ID SSID = SyncScope::System) { |
386 | setOrdering(Ordering); |
387 | setSyncScopeID(SSID); |
388 | } |
389 | |
390 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
391 | |
392 | bool isUnordered() const { |
393 | return (getOrdering() == AtomicOrdering::NotAtomic || |
394 | getOrdering() == AtomicOrdering::Unordered) && |
395 | !isVolatile(); |
396 | } |
397 | |
398 | Value *getValueOperand() { return getOperand(0); } |
399 | const Value *getValueOperand() const { return getOperand(0); } |
400 | |
401 | Value *getPointerOperand() { return getOperand(1); } |
402 | const Value *getPointerOperand() const { return getOperand(1); } |
403 | static unsigned getPointerOperandIndex() { return 1U; } |
404 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
405 | |
406 | /// Returns the address space of the pointer operand. |
407 | unsigned getPointerAddressSpace() const { |
408 | return getPointerOperandType()->getPointerAddressSpace(); |
409 | } |
410 | |
411 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
412 | static bool classof(const Instruction *I) { |
413 | return I->getOpcode() == Instruction::Store; |
414 | } |
415 | static bool classof(const Value *V) { |
416 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
417 | } |
418 | |
419 | private: |
420 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
421 | // method so that subclasses cannot accidentally use it. |
422 | template <typename Bitfield> |
423 | void setSubclassData(typename Bitfield::Type Value) { |
424 | Instruction::setSubclassData<Bitfield>(Value); |
425 | } |
426 | |
427 | /// The synchronization scope ID of this store instruction. Not quite enough |
428 | /// room in SubClassData for everything, so synchronization scope ID gets its |
429 | /// own field. |
430 | SyncScope::ID SSID; |
431 | }; |
432 | |
433 | template <> |
434 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
435 | }; |
436 | |
437 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits <StoreInst>::op_begin(this); } StoreInst::const_op_iterator StoreInst::op_begin() const { return OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this)); } StoreInst ::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst >::op_end(this); } StoreInst::const_op_iterator StoreInst:: op_end() const { return OperandTraits<StoreInst>::op_end (const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <StoreInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst *>(this))[i_nocapture].get()); } void StoreInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst ::getNumOperands() const { return OperandTraits<StoreInst> ::operands(this); } template <int Idx_nocapture> Use & StoreInst::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &StoreInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
438 | |
439 | //===----------------------------------------------------------------------===// |
440 | // FenceInst Class |
441 | //===----------------------------------------------------------------------===// |
442 | |
443 | /// An instruction for ordering other memory operations. |
444 | class FenceInst : public Instruction { |
445 | using OrderingField = AtomicOrderingBitfieldElementT<0>; |
446 | |
447 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
448 | |
449 | protected: |
450 | // Note: Instruction needs to be a friend here to call cloneImpl. |
451 | friend class Instruction; |
452 | |
453 | FenceInst *cloneImpl() const; |
454 | |
455 | public: |
456 | // Ordering may only be Acquire, Release, AcquireRelease, or |
457 | // SequentiallyConsistent. |
458 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
459 | SyncScope::ID SSID = SyncScope::System, |
460 | Instruction *InsertBefore = nullptr); |
461 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
462 | BasicBlock *InsertAtEnd); |
463 | |
464 | // allocate space for exactly zero operands |
465 | void *operator new(size_t s) { |
466 | return User::operator new(s, 0); |
467 | } |
468 | |
469 | /// Returns the ordering constraint of this fence instruction. |
470 | AtomicOrdering getOrdering() const { |
471 | return getSubclassData<OrderingField>(); |
472 | } |
473 | |
474 | /// Sets the ordering constraint of this fence instruction. May only be |
475 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
476 | void setOrdering(AtomicOrdering Ordering) { |
477 | setSubclassData<OrderingField>(Ordering); |
478 | } |
479 | |
480 | /// Returns the synchronization scope ID of this fence instruction. |
481 | SyncScope::ID getSyncScopeID() const { |
482 | return SSID; |
483 | } |
484 | |
485 | /// Sets the synchronization scope ID of this fence instruction. |
486 | void setSyncScopeID(SyncScope::ID SSID) { |
487 | this->SSID = SSID; |
488 | } |
489 | |
490 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
491 | static bool classof(const Instruction *I) { |
492 | return I->getOpcode() == Instruction::Fence; |
493 | } |
494 | static bool classof(const Value *V) { |
495 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
496 | } |
497 | |
498 | private: |
499 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
500 | // method so that subclasses cannot accidentally use it. |
501 | template <typename Bitfield> |
502 | void setSubclassData(typename Bitfield::Type Value) { |
503 | Instruction::setSubclassData<Bitfield>(Value); |
504 | } |
505 | |
506 | /// The synchronization scope ID of this fence instruction. Not quite enough |
507 | /// room in SubClassData for everything, so synchronization scope ID gets its |
508 | /// own field. |
509 | SyncScope::ID SSID; |
510 | }; |
511 | |
512 | //===----------------------------------------------------------------------===// |
513 | // AtomicCmpXchgInst Class |
514 | //===----------------------------------------------------------------------===// |
515 | |
516 | /// An instruction that atomically checks whether a |
517 | /// specified value is in a memory location, and, if it is, stores a new value |
518 | /// there. The value returned by this instruction is a pair containing the |
519 | /// original value as first element, and an i1 indicating success (true) or |
520 | /// failure (false) as second element. |
521 | /// |
522 | class AtomicCmpXchgInst : public Instruction { |
523 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align, |
524 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
525 | SyncScope::ID SSID); |
526 | |
527 | template <unsigned Offset> |
528 | using AtomicOrderingBitfieldElement = |
529 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
530 | AtomicOrdering::LAST>; |
531 | |
532 | protected: |
533 | // Note: Instruction needs to be a friend here to call cloneImpl. |
534 | friend class Instruction; |
535 | |
536 | AtomicCmpXchgInst *cloneImpl() const; |
537 | |
538 | public: |
539 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
540 | AtomicOrdering SuccessOrdering, |
541 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
542 | Instruction *InsertBefore = nullptr); |
543 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
544 | AtomicOrdering SuccessOrdering, |
545 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
546 | BasicBlock *InsertAtEnd); |
547 | |
548 | // allocate space for exactly three operands |
549 | void *operator new(size_t s) { |
550 | return User::operator new(s, 3); |
551 | } |
552 | |
553 | using VolatileField = BoolBitfieldElementT<0>; |
554 | using WeakField = BoolBitfieldElementT<VolatileField::NextBit>; |
555 | using SuccessOrderingField = |
556 | AtomicOrderingBitfieldElementT<WeakField::NextBit>; |
557 | using FailureOrderingField = |
558 | AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>; |
559 | using AlignmentField = |
560 | AlignmentBitfieldElementT<FailureOrderingField::NextBit>; |
561 | static_assert( |
562 | Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField, |
563 | FailureOrderingField, AlignmentField>(), |
564 | "Bitfields must be contiguous"); |
565 | |
566 | /// Return the alignment of the memory that is being allocated by the |
567 | /// instruction. |
568 | Align getAlign() const { |
569 | return Align(1ULL << getSubclassData<AlignmentField>()); |
570 | } |
571 | |
572 | void setAlignment(Align Align) { |
573 | setSubclassData<AlignmentField>(Log2(Align)); |
574 | } |
575 | |
576 | /// Return true if this is a cmpxchg from a volatile memory |
577 | /// location. |
578 | /// |
579 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
580 | |
581 | /// Specify whether this is a volatile cmpxchg. |
582 | /// |
583 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
584 | |
585 | /// Return true if this cmpxchg may spuriously fail. |
586 | bool isWeak() const { return getSubclassData<WeakField>(); } |
587 | |
588 | void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); } |
589 | |
590 | /// Transparently provide more efficient getOperand methods. |
591 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
592 | |
593 | /// Returns the success ordering constraint of this cmpxchg instruction. |
594 | AtomicOrdering getSuccessOrdering() const { |
595 | return getSubclassData<SuccessOrderingField>(); |
596 | } |
597 | |
598 | /// Sets the success ordering constraint of this cmpxchg instruction. |
599 | void setSuccessOrdering(AtomicOrdering Ordering) { |
600 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)) |
601 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)); |
602 | setSubclassData<SuccessOrderingField>(Ordering); |
603 | } |
604 | |
605 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
606 | AtomicOrdering getFailureOrdering() const { |
607 | return getSubclassData<FailureOrderingField>(); |
608 | } |
609 | |
610 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
611 | void setFailureOrdering(AtomicOrdering Ordering) { |
612 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)) |
613 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)); |
614 | setSubclassData<FailureOrderingField>(Ordering); |
615 | } |
616 | |
617 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
618 | SyncScope::ID getSyncScopeID() const { |
619 | return SSID; |
620 | } |
621 | |
622 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
623 | void setSyncScopeID(SyncScope::ID SSID) { |
624 | this->SSID = SSID; |
625 | } |
626 | |
627 | Value *getPointerOperand() { return getOperand(0); } |
628 | const Value *getPointerOperand() const { return getOperand(0); } |
629 | static unsigned getPointerOperandIndex() { return 0U; } |
630 | |
631 | Value *getCompareOperand() { return getOperand(1); } |
632 | const Value *getCompareOperand() const { return getOperand(1); } |
633 | |
634 | Value *getNewValOperand() { return getOperand(2); } |
635 | const Value *getNewValOperand() const { return getOperand(2); } |
636 | |
637 | /// Returns the address space of the pointer operand. |
638 | unsigned getPointerAddressSpace() const { |
639 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
640 | } |
641 | |
642 | /// Returns the strongest permitted ordering on failure, given the |
643 | /// desired ordering on success. |
644 | /// |
645 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
646 | /// so release semantics cannot be provided. So this function drops explicit |
647 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
648 | /// operation would remain SequentiallyConsistent. |
649 | static AtomicOrdering |
650 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
651 | switch (SuccessOrdering) { |
652 | default: |
653 | llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 653); |
654 | case AtomicOrdering::Release: |
655 | case AtomicOrdering::Monotonic: |
656 | return AtomicOrdering::Monotonic; |
657 | case AtomicOrdering::AcquireRelease: |
658 | case AtomicOrdering::Acquire: |
659 | return AtomicOrdering::Acquire; |
660 | case AtomicOrdering::SequentiallyConsistent: |
661 | return AtomicOrdering::SequentiallyConsistent; |
662 | } |
663 | } |
664 | |
665 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
666 | static bool classof(const Instruction *I) { |
667 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
668 | } |
669 | static bool classof(const Value *V) { |
670 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
671 | } |
672 | |
673 | private: |
674 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
675 | // method so that subclasses cannot accidentally use it. |
676 | template <typename Bitfield> |
677 | void setSubclassData(typename Bitfield::Type Value) { |
678 | Instruction::setSubclassData<Bitfield>(Value); |
679 | } |
680 | |
681 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
682 | /// enough room in SubClassData for everything, so synchronization scope ID |
683 | /// gets its own field. |
684 | SyncScope::ID SSID; |
685 | }; |
686 | |
687 | template <> |
688 | struct OperandTraits<AtomicCmpXchgInst> : |
689 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
690 | }; |
691 | |
692 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() { return OperandTraits<AtomicCmpXchgInst>::op_begin(this ); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst:: op_begin() const { return OperandTraits<AtomicCmpXchgInst> ::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst ::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits <AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst:: const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits <AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst *>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast <AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicCmpXchgInst::getNumOperands() const { return OperandTraits <AtomicCmpXchgInst>::operands(this); } template <int Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &AtomicCmpXchgInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
693 | |
694 | //===----------------------------------------------------------------------===// |
695 | // AtomicRMWInst Class |
696 | //===----------------------------------------------------------------------===// |
697 | |
698 | /// an instruction that atomically reads a memory location, |
699 | /// combines it with another value, and then stores the result back. Returns |
700 | /// the old value. |
701 | /// |
702 | class AtomicRMWInst : public Instruction { |
703 | protected: |
704 | // Note: Instruction needs to be a friend here to call cloneImpl. |
705 | friend class Instruction; |
706 | |
707 | AtomicRMWInst *cloneImpl() const; |
708 | |
709 | public: |
710 | /// This enumeration lists the possible modifications atomicrmw can make. In |
711 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
712 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
713 | /// instruction. These instructions always return 'old'. |
714 | enum BinOp : unsigned { |
715 | /// *p = v |
716 | Xchg, |
717 | /// *p = old + v |
718 | Add, |
719 | /// *p = old - v |
720 | Sub, |
721 | /// *p = old & v |
722 | And, |
723 | /// *p = ~(old & v) |
724 | Nand, |
725 | /// *p = old | v |
726 | Or, |
727 | /// *p = old ^ v |
728 | Xor, |
729 | /// *p = old >signed v ? old : v |
730 | Max, |
731 | /// *p = old <signed v ? old : v |
732 | Min, |
733 | /// *p = old >unsigned v ? old : v |
734 | UMax, |
735 | /// *p = old <unsigned v ? old : v |
736 | UMin, |
737 | |
738 | /// *p = old + v |
739 | FAdd, |
740 | |
741 | /// *p = old - v |
742 | FSub, |
743 | |
744 | FIRST_BINOP = Xchg, |
745 | LAST_BINOP = FSub, |
746 | BAD_BINOP |
747 | }; |
748 | |
749 | private: |
750 | template <unsigned Offset> |
751 | using AtomicOrderingBitfieldElement = |
752 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
753 | AtomicOrdering::LAST>; |
754 | |
755 | template <unsigned Offset> |
756 | using BinOpBitfieldElement = |
757 | typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>; |
758 | |
759 | public: |
760 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
761 | AtomicOrdering Ordering, SyncScope::ID SSID, |
762 | Instruction *InsertBefore = nullptr); |
763 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
764 | AtomicOrdering Ordering, SyncScope::ID SSID, |
765 | BasicBlock *InsertAtEnd); |
766 | |
767 | // allocate space for exactly two operands |
768 | void *operator new(size_t s) { |
769 | return User::operator new(s, 2); |
770 | } |
771 | |
772 | using VolatileField = BoolBitfieldElementT<0>; |
773 | using AtomicOrderingField = |
774 | AtomicOrderingBitfieldElementT<VolatileField::NextBit>; |
775 | using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>; |
776 | using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>; |
777 | static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField, |
778 | OperationField, AlignmentField>(), |
779 | "Bitfields must be contiguous"); |
780 | |
781 | BinOp getOperation() const { return getSubclassData<OperationField>(); } |
782 | |
783 | static StringRef getOperationName(BinOp Op); |
784 | |
785 | static bool isFPOperation(BinOp Op) { |
786 | switch (Op) { |
787 | case AtomicRMWInst::FAdd: |
788 | case AtomicRMWInst::FSub: |
789 | return true; |
790 | default: |
791 | return false; |
792 | } |
793 | } |
794 | |
795 | void setOperation(BinOp Operation) { |
796 | setSubclassData<OperationField>(Operation); |
797 | } |
798 | |
799 | /// Return the alignment of the memory that is being allocated by the |
800 | /// instruction. |
801 | Align getAlign() const { |
802 | return Align(1ULL << getSubclassData<AlignmentField>()); |
803 | } |
804 | |
805 | void setAlignment(Align Align) { |
806 | setSubclassData<AlignmentField>(Log2(Align)); |
807 | } |
808 | |
809 | /// Return true if this is a RMW on a volatile memory location. |
810 | /// |
811 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
812 | |
813 | /// Specify whether this is a volatile RMW or not. |
814 | /// |
815 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
816 | |
817 | /// Transparently provide more efficient getOperand methods. |
818 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
819 | |
820 | /// Returns the ordering constraint of this rmw instruction. |
821 | AtomicOrdering getOrdering() const { |
822 | return getSubclassData<AtomicOrderingField>(); |
823 | } |
824 | |
825 | /// Sets the ordering constraint of this rmw instruction. |
826 | void setOrdering(AtomicOrdering Ordering) { |
827 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)) |
828 | "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)); |
829 | setSubclassData<AtomicOrderingField>(Ordering); |
830 | } |
831 | |
832 | /// Returns the synchronization scope ID of this rmw instruction. |
833 | SyncScope::ID getSyncScopeID() const { |
834 | return SSID; |
835 | } |
836 | |
837 | /// Sets the synchronization scope ID of this rmw instruction. |
838 | void setSyncScopeID(SyncScope::ID SSID) { |
839 | this->SSID = SSID; |
840 | } |
841 | |
842 | Value *getPointerOperand() { return getOperand(0); } |
843 | const Value *getPointerOperand() const { return getOperand(0); } |
844 | static unsigned getPointerOperandIndex() { return 0U; } |
845 | |
846 | Value *getValOperand() { return getOperand(1); } |
847 | const Value *getValOperand() const { return getOperand(1); } |
848 | |
849 | /// Returns the address space of the pointer operand. |
850 | unsigned getPointerAddressSpace() const { |
851 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
852 | } |
853 | |
854 | bool isFloatingPointOperation() const { |
855 | return isFPOperation(getOperation()); |
856 | } |
857 | |
858 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
859 | static bool classof(const Instruction *I) { |
860 | return I->getOpcode() == Instruction::AtomicRMW; |
861 | } |
862 | static bool classof(const Value *V) { |
863 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
864 | } |
865 | |
866 | private: |
867 | void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align, |
868 | AtomicOrdering Ordering, SyncScope::ID SSID); |
869 | |
870 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
871 | // method so that subclasses cannot accidentally use it. |
872 | template <typename Bitfield> |
873 | void setSubclassData(typename Bitfield::Type Value) { |
874 | Instruction::setSubclassData<Bitfield>(Value); |
875 | } |
876 | |
877 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
878 | /// room in SubClassData for everything, so synchronization scope ID gets its |
879 | /// own field. |
880 | SyncScope::ID SSID; |
881 | }; |
882 | |
883 | template <> |
884 | struct OperandTraits<AtomicRMWInst> |
885 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
886 | }; |
887 | |
888 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst ::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits <AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*> (this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end() { return OperandTraits<AtomicRMWInst>::op_end(this); } AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const { return OperandTraits<AtomicRMWInst>::op_end(const_cast <AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <AtomicRMWInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicRMWInst>::op_begin(const_cast< AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<AtomicRMWInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst ::getNumOperands() const { return OperandTraits<AtomicRMWInst >::operands(this); } template <int Idx_nocapture> Use &AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
889 | |
890 | //===----------------------------------------------------------------------===// |
891 | // GetElementPtrInst Class |
892 | //===----------------------------------------------------------------------===// |
893 | |
894 | // checkGEPType - Simple wrapper function to give a better assertion failure |
895 | // message on bad indexes for a gep instruction. |
896 | // |
897 | inline Type *checkGEPType(Type *Ty) { |
898 | assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!" ) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 898, __PRETTY_FUNCTION__)); |
899 | return Ty; |
900 | } |
901 | |
902 | /// an instruction for type-safe pointer arithmetic to |
903 | /// access elements of arrays and structs |
904 | /// |
905 | class GetElementPtrInst : public Instruction { |
906 | Type *SourceElementType; |
907 | Type *ResultElementType; |
908 | |
909 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
910 | |
911 | /// Constructors - Create a getelementptr instruction with a base pointer an |
912 | /// list of indices. The first ctor can optionally insert before an existing |
913 | /// instruction, the second appends the new instruction to the specified |
914 | /// BasicBlock. |
915 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
916 | ArrayRef<Value *> IdxList, unsigned Values, |
917 | const Twine &NameStr, Instruction *InsertBefore); |
918 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
919 | ArrayRef<Value *> IdxList, unsigned Values, |
920 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
921 | |
922 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
923 | |
924 | protected: |
925 | // Note: Instruction needs to be a friend here to call cloneImpl. |
926 | friend class Instruction; |
927 | |
928 | GetElementPtrInst *cloneImpl() const; |
929 | |
930 | public: |
931 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
932 | ArrayRef<Value *> IdxList, |
933 | const Twine &NameStr = "", |
934 | Instruction *InsertBefore = nullptr) { |
935 | unsigned Values = 1 + unsigned(IdxList.size()); |
936 | if (!PointeeType) |
937 | PointeeType = |
938 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
939 | else |
940 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
941 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
942 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)); |
943 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
944 | NameStr, InsertBefore); |
945 | } |
946 | |
947 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
948 | ArrayRef<Value *> IdxList, |
949 | const Twine &NameStr, |
950 | BasicBlock *InsertAtEnd) { |
951 | unsigned Values = 1 + unsigned(IdxList.size()); |
952 | if (!PointeeType) |
953 | PointeeType = |
954 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
955 | else |
956 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
957 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
958 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)); |
959 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
960 | NameStr, InsertAtEnd); |
961 | } |
962 | |
963 | /// Create an "inbounds" getelementptr. See the documentation for the |
964 | /// "inbounds" flag in LangRef.html for details. |
965 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
966 | ArrayRef<Value *> IdxList, |
967 | const Twine &NameStr = "", |
968 | Instruction *InsertBefore = nullptr){ |
969 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore); |
970 | } |
971 | |
972 | static GetElementPtrInst * |
973 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
974 | const Twine &NameStr = "", |
975 | Instruction *InsertBefore = nullptr) { |
976 | GetElementPtrInst *GEP = |
977 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
978 | GEP->setIsInBounds(true); |
979 | return GEP; |
980 | } |
981 | |
982 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
983 | ArrayRef<Value *> IdxList, |
984 | const Twine &NameStr, |
985 | BasicBlock *InsertAtEnd) { |
986 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd); |
987 | } |
988 | |
989 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
990 | ArrayRef<Value *> IdxList, |
991 | const Twine &NameStr, |
992 | BasicBlock *InsertAtEnd) { |
993 | GetElementPtrInst *GEP = |
994 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
995 | GEP->setIsInBounds(true); |
996 | return GEP; |
997 | } |
998 | |
999 | /// Transparently provide more efficient getOperand methods. |
1000 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1001 | |
1002 | Type *getSourceElementType() const { return SourceElementType; } |
1003 | |
1004 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
1005 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
1006 | |
1007 | Type *getResultElementType() const { |
1008 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)) |
1009 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)); |
1010 | return ResultElementType; |
1011 | } |
1012 | |
1013 | /// Returns the address space of this instruction's pointer type. |
1014 | unsigned getAddressSpace() const { |
1015 | // Note that this is always the same as the pointer operand's address space |
1016 | // and that is cheaper to compute, so cheat here. |
1017 | return getPointerAddressSpace(); |
1018 | } |
1019 | |
1020 | /// Returns the result type of a getelementptr with the given source |
1021 | /// element type and indexes. |
1022 | /// |
1023 | /// Null is returned if the indices are invalid for the specified |
1024 | /// source element type. |
1025 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
1026 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
1027 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
1028 | |
1029 | /// Return the type of the element at the given index of an indexable |
1030 | /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})". |
1031 | /// |
1032 | /// Returns null if the type can't be indexed, or the given index is not |
1033 | /// legal for the given type. |
1034 | static Type *getTypeAtIndex(Type *Ty, Value *Idx); |
1035 | static Type *getTypeAtIndex(Type *Ty, uint64_t Idx); |
1036 | |
1037 | inline op_iterator idx_begin() { return op_begin()+1; } |
1038 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
1039 | inline op_iterator idx_end() { return op_end(); } |
1040 | inline const_op_iterator idx_end() const { return op_end(); } |
1041 | |
1042 | inline iterator_range<op_iterator> indices() { |
1043 | return make_range(idx_begin(), idx_end()); |
1044 | } |
1045 | |
1046 | inline iterator_range<const_op_iterator> indices() const { |
1047 | return make_range(idx_begin(), idx_end()); |
1048 | } |
1049 | |
1050 | Value *getPointerOperand() { |
1051 | return getOperand(0); |
1052 | } |
1053 | const Value *getPointerOperand() const { |
1054 | return getOperand(0); |
1055 | } |
1056 | static unsigned getPointerOperandIndex() { |
1057 | return 0U; // get index for modifying correct operand. |
1058 | } |
1059 | |
1060 | /// Method to return the pointer operand as a |
1061 | /// PointerType. |
1062 | Type *getPointerOperandType() const { |
1063 | return getPointerOperand()->getType(); |
1064 | } |
1065 | |
1066 | /// Returns the address space of the pointer operand. |
1067 | unsigned getPointerAddressSpace() const { |
1068 | return getPointerOperandType()->getPointerAddressSpace(); |
1069 | } |
1070 | |
1071 | /// Returns the pointer type returned by the GEP |
1072 | /// instruction, which may be a vector of pointers. |
1073 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
1074 | ArrayRef<Value *> IdxList) { |
1075 | Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)), |
1076 | Ptr->getType()->getPointerAddressSpace()); |
1077 | // Vector GEP |
1078 | if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) { |
1079 | ElementCount EltCount = PtrVTy->getElementCount(); |
1080 | return VectorType::get(PtrTy, EltCount); |
1081 | } |
1082 | for (Value *Index : IdxList) |
1083 | if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) { |
1084 | ElementCount EltCount = IndexVTy->getElementCount(); |
1085 | return VectorType::get(PtrTy, EltCount); |
1086 | } |
1087 | // Scalar GEP |
1088 | return PtrTy; |
1089 | } |
1090 | |
1091 | unsigned getNumIndices() const { // Note: always non-negative |
1092 | return getNumOperands() - 1; |
1093 | } |
1094 | |
1095 | bool hasIndices() const { |
1096 | return getNumOperands() > 1; |
1097 | } |
1098 | |
1099 | /// Return true if all of the indices of this GEP are |
1100 | /// zeros. If so, the result pointer and the first operand have the same |
1101 | /// value, just potentially different types. |
1102 | bool hasAllZeroIndices() const; |
1103 | |
1104 | /// Return true if all of the indices of this GEP are |
1105 | /// constant integers. If so, the result pointer and the first operand have |
1106 | /// a constant offset between them. |
1107 | bool hasAllConstantIndices() const; |
1108 | |
1109 | /// Set or clear the inbounds flag on this GEP instruction. |
1110 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
1111 | void setIsInBounds(bool b = true); |
1112 | |
1113 | /// Determine whether the GEP has the inbounds flag. |
1114 | bool isInBounds() const; |
1115 | |
1116 | /// Accumulate the constant address offset of this GEP if possible. |
1117 | /// |
1118 | /// This routine accepts an APInt into which it will accumulate the constant |
1119 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
1120 | /// all-constant, it returns false and the value of the offset APInt is |
1121 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
1122 | /// must be at least as wide as the IntPtr type for the address space of |
1123 | /// the base GEP pointer. |
1124 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
1125 | |
1126 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1127 | static bool classof(const Instruction *I) { |
1128 | return (I->getOpcode() == Instruction::GetElementPtr); |
1129 | } |
1130 | static bool classof(const Value *V) { |
1131 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1132 | } |
1133 | }; |
1134 | |
1135 | template <> |
1136 | struct OperandTraits<GetElementPtrInst> : |
1137 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
1138 | }; |
1139 | |
1140 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1141 | ArrayRef<Value *> IdxList, unsigned Values, |
1142 | const Twine &NameStr, |
1143 | Instruction *InsertBefore) |
1144 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1145 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1146 | Values, InsertBefore), |
1147 | SourceElementType(PointeeType), |
1148 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1149 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)) |
1150 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)); |
1151 | init(Ptr, IdxList, NameStr); |
1152 | } |
1153 | |
1154 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1155 | ArrayRef<Value *> IdxList, unsigned Values, |
1156 | const Twine &NameStr, |
1157 | BasicBlock *InsertAtEnd) |
1158 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1159 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1160 | Values, InsertAtEnd), |
1161 | SourceElementType(PointeeType), |
1162 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1163 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)) |
1164 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)); |
1165 | init(Ptr, IdxList, NameStr); |
1166 | } |
1167 | |
1168 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() { return OperandTraits<GetElementPtrInst>::op_begin(this ); } GetElementPtrInst::const_op_iterator GetElementPtrInst:: op_begin() const { return OperandTraits<GetElementPtrInst> ::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst ::op_iterator GetElementPtrInst::op_end() { return OperandTraits <GetElementPtrInst>::op_end(this); } GetElementPtrInst:: const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits <GetElementPtrInst>::op_end(const_cast<GetElementPtrInst *>(this)); } Value *GetElementPtrInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<GetElementPtrInst>::op_begin(const_cast <GetElementPtrInst*>(this))[i_nocapture].get()); } void GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<GetElementPtrInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned GetElementPtrInst::getNumOperands() const { return OperandTraits <GetElementPtrInst>::operands(this); } template <int Idx_nocapture> Use &GetElementPtrInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &GetElementPtrInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1169 | |
1170 | //===----------------------------------------------------------------------===// |
1171 | // ICmpInst Class |
1172 | //===----------------------------------------------------------------------===// |
1173 | |
1174 | /// This instruction compares its operands according to the predicate given |
1175 | /// to the constructor. It only operates on integers or pointers. The operands |
1176 | /// must be identical types. |
1177 | /// Represent an integer comparison operator. |
1178 | class ICmpInst: public CmpInst { |
1179 | void AssertOK() { |
1180 | assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)) |
1181 | "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)); |
1182 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)) |
1183 | "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)); |
1184 | // Check that the operands are the right type |
1185 | assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1186 | getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1187 | "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)); |
1188 | } |
1189 | |
1190 | protected: |
1191 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1192 | friend class Instruction; |
1193 | |
1194 | /// Clone an identical ICmpInst |
1195 | ICmpInst *cloneImpl() const; |
1196 | |
1197 | public: |
1198 | /// Constructor with insert-before-instruction semantics. |
1199 | ICmpInst( |
1200 | Instruction *InsertBefore, ///< Where to insert |
1201 | Predicate pred, ///< The predicate to use for the comparison |
1202 | Value *LHS, ///< The left-hand-side of the expression |
1203 | Value *RHS, ///< The right-hand-side of the expression |
1204 | const Twine &NameStr = "" ///< Name of the instruction |
1205 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1206 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1207 | InsertBefore) { |
1208 | #ifndef NDEBUG |
1209 | AssertOK(); |
1210 | #endif |
1211 | } |
1212 | |
1213 | /// Constructor with insert-at-end semantics. |
1214 | ICmpInst( |
1215 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1216 | Predicate pred, ///< The predicate to use for the comparison |
1217 | Value *LHS, ///< The left-hand-side of the expression |
1218 | Value *RHS, ///< The right-hand-side of the expression |
1219 | const Twine &NameStr = "" ///< Name of the instruction |
1220 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1221 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1222 | &InsertAtEnd) { |
1223 | #ifndef NDEBUG |
1224 | AssertOK(); |
1225 | #endif |
1226 | } |
1227 | |
1228 | /// Constructor with no-insertion semantics |
1229 | ICmpInst( |
1230 | Predicate pred, ///< The predicate to use for the comparison |
1231 | Value *LHS, ///< The left-hand-side of the expression |
1232 | Value *RHS, ///< The right-hand-side of the expression |
1233 | const Twine &NameStr = "" ///< Name of the instruction |
1234 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1235 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
1236 | #ifndef NDEBUG |
1237 | AssertOK(); |
1238 | #endif |
1239 | } |
1240 | |
1241 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
1242 | /// @returns the predicate that would be the result if the operand were |
1243 | /// regarded as signed. |
1244 | /// Return the signed version of the predicate |
1245 | Predicate getSignedPredicate() const { |
1246 | return getSignedPredicate(getPredicate()); |
1247 | } |
1248 | |
1249 | /// This is a static version that you can use without an instruction. |
1250 | /// Return the signed version of the predicate. |
1251 | static Predicate getSignedPredicate(Predicate pred); |
1252 | |
1253 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
1254 | /// @returns the predicate that would be the result if the operand were |
1255 | /// regarded as unsigned. |
1256 | /// Return the unsigned version of the predicate |
1257 | Predicate getUnsignedPredicate() const { |
1258 | return getUnsignedPredicate(getPredicate()); |
1259 | } |
1260 | |
1261 | /// This is a static version that you can use without an instruction. |
1262 | /// Return the unsigned version of the predicate. |
1263 | static Predicate getUnsignedPredicate(Predicate pred); |
1264 | |
1265 | /// Return true if this predicate is either EQ or NE. This also |
1266 | /// tests for commutativity. |
1267 | static bool isEquality(Predicate P) { |
1268 | return P == ICMP_EQ || P == ICMP_NE; |
1269 | } |
1270 | |
1271 | /// Return true if this predicate is either EQ or NE. This also |
1272 | /// tests for commutativity. |
1273 | bool isEquality() const { |
1274 | return isEquality(getPredicate()); |
1275 | } |
1276 | |
1277 | /// @returns true if the predicate of this ICmpInst is commutative |
1278 | /// Determine if this relation is commutative. |
1279 | bool isCommutative() const { return isEquality(); } |
1280 | |
1281 | /// Return true if the predicate is relational (not EQ or NE). |
1282 | /// |
1283 | bool isRelational() const { |
1284 | return !isEquality(); |
1285 | } |
1286 | |
1287 | /// Return true if the predicate is relational (not EQ or NE). |
1288 | /// |
1289 | static bool isRelational(Predicate P) { |
1290 | return !isEquality(P); |
1291 | } |
1292 | |
1293 | /// Return true if the predicate is SGT or UGT. |
1294 | /// |
1295 | static bool isGT(Predicate P) { |
1296 | return P == ICMP_SGT || P == ICMP_UGT; |
1297 | } |
1298 | |
1299 | /// Return true if the predicate is SLT or ULT. |
1300 | /// |
1301 | static bool isLT(Predicate P) { |
1302 | return P == ICMP_SLT || P == ICMP_ULT; |
1303 | } |
1304 | |
1305 | /// Return true if the predicate is SGE or UGE. |
1306 | /// |
1307 | static bool isGE(Predicate P) { |
1308 | return P == ICMP_SGE || P == ICMP_UGE; |
1309 | } |
1310 | |
1311 | /// Return true if the predicate is SLE or ULE. |
1312 | /// |
1313 | static bool isLE(Predicate P) { |
1314 | return P == ICMP_SLE || P == ICMP_ULE; |
1315 | } |
1316 | |
1317 | /// Exchange the two operands to this instruction in such a way that it does |
1318 | /// not modify the semantics of the instruction. The predicate value may be |
1319 | /// changed to retain the same result if the predicate is order dependent |
1320 | /// (e.g. ult). |
1321 | /// Swap operands and adjust predicate. |
1322 | void swapOperands() { |
1323 | setPredicate(getSwappedPredicate()); |
1324 | Op<0>().swap(Op<1>()); |
1325 | } |
1326 | |
1327 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1328 | static bool classof(const Instruction *I) { |
1329 | return I->getOpcode() == Instruction::ICmp; |
1330 | } |
1331 | static bool classof(const Value *V) { |
1332 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1333 | } |
1334 | }; |
1335 | |
1336 | //===----------------------------------------------------------------------===// |
1337 | // FCmpInst Class |
1338 | //===----------------------------------------------------------------------===// |
1339 | |
1340 | /// This instruction compares its operands according to the predicate given |
1341 | /// to the constructor. It only operates on floating point values or packed |
1342 | /// vectors of floating point values. The operands must be identical types. |
1343 | /// Represents a floating point comparison operator. |
1344 | class FCmpInst: public CmpInst { |
1345 | void AssertOK() { |
1346 | assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ? static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1346, __PRETTY_FUNCTION__)); |
1347 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1348, __PRETTY_FUNCTION__)) |
1348 | "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1348, __PRETTY_FUNCTION__)); |
1349 | // Check that the operands are the right type |
1350 | assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1351, __PRETTY_FUNCTION__)) |
1351 | "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1351, __PRETTY_FUNCTION__)); |
1352 | } |
1353 | |
1354 | protected: |
1355 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1356 | friend class Instruction; |
1357 | |
1358 | /// Clone an identical FCmpInst |
1359 | FCmpInst *cloneImpl() const; |
1360 | |
1361 | public: |
1362 | /// Constructor with insert-before-instruction semantics. |
1363 | FCmpInst( |
1364 | Instruction *InsertBefore, ///< Where to insert |
1365 | Predicate pred, ///< The predicate to use for the comparison |
1366 | Value *LHS, ///< The left-hand-side of the expression |
1367 | Value *RHS, ///< The right-hand-side of the expression |
1368 | const Twine &NameStr = "" ///< Name of the instruction |
1369 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1370 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1371 | InsertBefore) { |
1372 | AssertOK(); |
1373 | } |
1374 | |
1375 | /// Constructor with insert-at-end semantics. |
1376 | FCmpInst( |
1377 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1378 | Predicate pred, ///< The predicate to use for the comparison |
1379 | Value *LHS, ///< The left-hand-side of the expression |
1380 | Value *RHS, ///< The right-hand-side of the expression |
1381 | const Twine &NameStr = "" ///< Name of the instruction |
1382 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1383 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1384 | &InsertAtEnd) { |
1385 | AssertOK(); |
1386 | } |
1387 | |
1388 | /// Constructor with no-insertion semantics |
1389 | FCmpInst( |
1390 | Predicate Pred, ///< The predicate to use for the comparison |
1391 | Value *LHS, ///< The left-hand-side of the expression |
1392 | Value *RHS, ///< The right-hand-side of the expression |
1393 | const Twine &NameStr = "", ///< Name of the instruction |
1394 | Instruction *FlagsSource = nullptr |
1395 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
1396 | RHS, NameStr, nullptr, FlagsSource) { |
1397 | AssertOK(); |
1398 | } |
1399 | |
1400 | /// @returns true if the predicate of this instruction is EQ or NE. |
1401 | /// Determine if this is an equality predicate. |
1402 | static bool isEquality(Predicate Pred) { |
1403 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
1404 | Pred == FCMP_UNE; |
1405 | } |
1406 | |
1407 | /// @returns true if the predicate of this instruction is EQ or NE. |
1408 | /// Determine if this is an equality predicate. |
1409 | bool isEquality() const { return isEquality(getPredicate()); } |
1410 | |
1411 | /// @returns true if the predicate of this instruction is commutative. |
1412 | /// Determine if this is a commutative predicate. |
1413 | bool isCommutative() const { |
1414 | return isEquality() || |
1415 | getPredicate() == FCMP_FALSE || |
1416 | getPredicate() == FCMP_TRUE || |
1417 | getPredicate() == FCMP_ORD || |
1418 | getPredicate() == FCMP_UNO; |
1419 | } |
1420 | |
1421 | /// @returns true if the predicate is relational (not EQ or NE). |
1422 | /// Determine if this a relational predicate. |
1423 | bool isRelational() const { return !isEquality(); } |
1424 | |
1425 | /// Exchange the two operands to this instruction in such a way that it does |
1426 | /// not modify the semantics of the instruction. The predicate value may be |
1427 | /// changed to retain the same result if the predicate is order dependent |
1428 | /// (e.g. ult). |
1429 | /// Swap operands and adjust predicate. |
1430 | void swapOperands() { |
1431 | setPredicate(getSwappedPredicate()); |
1432 | Op<0>().swap(Op<1>()); |
1433 | } |
1434 | |
1435 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1436 | static bool classof(const Instruction *I) { |
1437 | return I->getOpcode() == Instruction::FCmp; |
1438 | } |
1439 | static bool classof(const Value *V) { |
1440 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1441 | } |
1442 | }; |
1443 | |
1444 | //===----------------------------------------------------------------------===// |
1445 | /// This class represents a function call, abstracting a target |
1446 | /// machine's calling convention. This class uses low bit of the SubClassData |
1447 | /// field to indicate whether or not this is a tail call. The rest of the bits |
1448 | /// hold the calling convention of the call. |
1449 | /// |
1450 | class CallInst : public CallBase { |
1451 | CallInst(const CallInst &CI); |
1452 | |
1453 | /// Construct a CallInst given a range of arguments. |
1454 | /// Construct a CallInst from a range of arguments |
1455 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1456 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1457 | Instruction *InsertBefore); |
1458 | |
1459 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1460 | const Twine &NameStr, Instruction *InsertBefore) |
1461 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
1462 | |
1463 | /// Construct a CallInst given a range of arguments. |
1464 | /// Construct a CallInst from a range of arguments |
1465 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1466 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1467 | BasicBlock *InsertAtEnd); |
1468 | |
1469 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
1470 | Instruction *InsertBefore); |
1471 | |
1472 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
1473 | BasicBlock *InsertAtEnd); |
1474 | |
1475 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
1476 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
1477 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
1478 | |
1479 | /// Compute the number of operands to allocate. |
1480 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
1481 | // We need one operand for the called function, plus the input operand |
1482 | // counts provided. |
1483 | return 1 + NumArgs + NumBundleInputs; |
1484 | } |
1485 | |
1486 | protected: |
1487 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1488 | friend class Instruction; |
1489 | |
1490 | CallInst *cloneImpl() const; |
1491 | |
1492 | public: |
1493 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
1494 | Instruction *InsertBefore = nullptr) { |
1495 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
1496 | } |
1497 | |
1498 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1499 | const Twine &NameStr, |
1500 | Instruction *InsertBefore = nullptr) { |
1501 | return new (ComputeNumOperands(Args.size())) |
1502 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
1503 | } |
1504 | |
1505 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1506 | ArrayRef<OperandBundleDef> Bundles = None, |
1507 | const Twine &NameStr = "", |
1508 | Instruction *InsertBefore = nullptr) { |
1509 | const int NumOperands = |
1510 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1511 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1512 | |
1513 | return new (NumOperands, DescriptorBytes) |
1514 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
1515 | } |
1516 | |
1517 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
1518 | BasicBlock *InsertAtEnd) { |
1519 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
1520 | } |
1521 | |
1522 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1523 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1524 | return new (ComputeNumOperands(Args.size())) |
1525 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
1526 | } |
1527 | |
1528 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1529 | ArrayRef<OperandBundleDef> Bundles, |
1530 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1531 | const int NumOperands = |
1532 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1533 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1534 | |
1535 | return new (NumOperands, DescriptorBytes) |
1536 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
1537 | } |
1538 | |
1539 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
1540 | Instruction *InsertBefore = nullptr) { |
1541 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1542 | InsertBefore); |
1543 | } |
1544 | |
1545 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1546 | ArrayRef<OperandBundleDef> Bundles = None, |
1547 | const Twine &NameStr = "", |
1548 | Instruction *InsertBefore = nullptr) { |
1549 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1550 | NameStr, InsertBefore); |
1551 | } |
1552 | |
1553 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1554 | const Twine &NameStr, |
1555 | Instruction *InsertBefore = nullptr) { |
1556 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1557 | InsertBefore); |
1558 | } |
1559 | |
1560 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
1561 | BasicBlock *InsertAtEnd) { |
1562 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1563 | InsertAtEnd); |
1564 | } |
1565 | |
1566 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1567 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1568 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1569 | InsertAtEnd); |
1570 | } |
1571 | |
1572 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1573 | ArrayRef<OperandBundleDef> Bundles, |
1574 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1575 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1576 | NameStr, InsertAtEnd); |
1577 | } |
1578 | |
1579 | /// Create a clone of \p CI with a different set of operand bundles and |
1580 | /// insert it before \p InsertPt. |
1581 | /// |
1582 | /// The returned call instruction is identical \p CI in every way except that |
1583 | /// the operand bundles for the new instruction are set to the operand bundles |
1584 | /// in \p Bundles. |
1585 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
1586 | Instruction *InsertPt = nullptr); |
1587 | |
1588 | /// Create a clone of \p CI with a different set of operand bundles and |
1589 | /// insert it before \p InsertPt. |
1590 | /// |
1591 | /// The returned call instruction is identical \p CI in every way except that |
1592 | /// the operand bundle for the new instruction is set to the operand bundle |
1593 | /// in \p Bundle. |
1594 | static CallInst *CreateWithReplacedBundle(CallInst *CI, |
1595 | OperandBundleDef Bundle, |
1596 | Instruction *InsertPt = nullptr); |
1597 | |
1598 | /// Generate the IR for a call to malloc: |
1599 | /// 1. Compute the malloc call's argument as the specified type's size, |
1600 | /// possibly multiplied by the array size if the array size is not |
1601 | /// constant 1. |
1602 | /// 2. Call malloc with that argument. |
1603 | /// 3. Bitcast the result of the malloc call to the specified type. |
1604 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1605 | Type *AllocTy, Value *AllocSize, |
1606 | Value *ArraySize = nullptr, |
1607 | Function *MallocF = nullptr, |
1608 | const Twine &Name = ""); |
1609 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1610 | Type *AllocTy, Value *AllocSize, |
1611 | Value *ArraySize = nullptr, |
1612 | Function *MallocF = nullptr, |
1613 | const Twine &Name = ""); |
1614 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1615 | Type *AllocTy, Value *AllocSize, |
1616 | Value *ArraySize = nullptr, |
1617 | ArrayRef<OperandBundleDef> Bundles = None, |
1618 | Function *MallocF = nullptr, |
1619 | const Twine &Name = ""); |
1620 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1621 | Type *AllocTy, Value *AllocSize, |
1622 | Value *ArraySize = nullptr, |
1623 | ArrayRef<OperandBundleDef> Bundles = None, |
1624 | Function *MallocF = nullptr, |
1625 | const Twine &Name = ""); |
1626 | /// Generate the IR for a call to the builtin free function. |
1627 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
1628 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
1629 | static Instruction *CreateFree(Value *Source, |
1630 | ArrayRef<OperandBundleDef> Bundles, |
1631 | Instruction *InsertBefore); |
1632 | static Instruction *CreateFree(Value *Source, |
1633 | ArrayRef<OperandBundleDef> Bundles, |
1634 | BasicBlock *InsertAtEnd); |
1635 | |
1636 | // Note that 'musttail' implies 'tail'. |
1637 | enum TailCallKind : unsigned { |
1638 | TCK_None = 0, |
1639 | TCK_Tail = 1, |
1640 | TCK_MustTail = 2, |
1641 | TCK_NoTail = 3, |
1642 | TCK_LAST = TCK_NoTail |
1643 | }; |
1644 | |
1645 | using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>; |
1646 | static_assert( |
1647 | Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(), |
1648 | "Bitfields must be contiguous"); |
1649 | |
1650 | TailCallKind getTailCallKind() const { |
1651 | return getSubclassData<TailCallKindField>(); |
1652 | } |
1653 | |
1654 | bool isTailCall() const { |
1655 | TailCallKind Kind = getTailCallKind(); |
1656 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
1657 | } |
1658 | |
1659 | bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } |
1660 | |
1661 | bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } |
1662 | |
1663 | void setTailCallKind(TailCallKind TCK) { |
1664 | setSubclassData<TailCallKindField>(TCK); |
1665 | } |
1666 | |
1667 | void setTailCall(bool IsTc = true) { |
1668 | setTailCallKind(IsTc ? TCK_Tail : TCK_None); |
1669 | } |
1670 | |
1671 | /// Return true if the call can return twice |
1672 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
1673 | void setCanReturnTwice() { |
1674 | addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice); |
1675 | } |
1676 | |
1677 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1678 | static bool classof(const Instruction *I) { |
1679 | return I->getOpcode() == Instruction::Call; |
1680 | } |
1681 | static bool classof(const Value *V) { |
1682 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1683 | } |
1684 | |
1685 | /// Updates profile metadata by scaling it by \p S / \p T. |
1686 | void updateProfWeight(uint64_t S, uint64_t T); |
1687 | |
1688 | private: |
1689 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
1690 | // method so that subclasses cannot accidentally use it. |
1691 | template <typename Bitfield> |
1692 | void setSubclassData(typename Bitfield::Type Value) { |
1693 | Instruction::setSubclassData<Bitfield>(Value); |
1694 | } |
1695 | }; |
1696 | |
1697 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1698 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1699 | BasicBlock *InsertAtEnd) |
1700 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1701 | OperandTraits<CallBase>::op_end(this) - |
1702 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1703 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1704 | InsertAtEnd) { |
1705 | init(Ty, Func, Args, Bundles, NameStr); |
1706 | } |
1707 | |
1708 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1709 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1710 | Instruction *InsertBefore) |
1711 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1712 | OperandTraits<CallBase>::op_end(this) - |
1713 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1714 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1715 | InsertBefore) { |
1716 | init(Ty, Func, Args, Bundles, NameStr); |
1717 | } |
1718 | |
1719 | //===----------------------------------------------------------------------===// |
1720 | // SelectInst Class |
1721 | //===----------------------------------------------------------------------===// |
1722 | |
1723 | /// This class represents the LLVM 'select' instruction. |
1724 | /// |
1725 | class SelectInst : public Instruction { |
1726 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1727 | Instruction *InsertBefore) |
1728 | : Instruction(S1->getType(), Instruction::Select, |
1729 | &Op<0>(), 3, InsertBefore) { |
1730 | init(C, S1, S2); |
1731 | setName(NameStr); |
1732 | } |
1733 | |
1734 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1735 | BasicBlock *InsertAtEnd) |
1736 | : Instruction(S1->getType(), Instruction::Select, |
1737 | &Op<0>(), 3, InsertAtEnd) { |
1738 | init(C, S1, S2); |
1739 | setName(NameStr); |
1740 | } |
1741 | |
1742 | void init(Value *C, Value *S1, Value *S2) { |
1743 | assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select" ) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1743, __PRETTY_FUNCTION__)); |
1744 | Op<0>() = C; |
1745 | Op<1>() = S1; |
1746 | Op<2>() = S2; |
1747 | } |
1748 | |
1749 | protected: |
1750 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1751 | friend class Instruction; |
1752 | |
1753 | SelectInst *cloneImpl() const; |
1754 | |
1755 | public: |
1756 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1757 | const Twine &NameStr = "", |
1758 | Instruction *InsertBefore = nullptr, |
1759 | Instruction *MDFrom = nullptr) { |
1760 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
1761 | if (MDFrom) |
1762 | Sel->copyMetadata(*MDFrom); |
1763 | return Sel; |
1764 | } |
1765 | |
1766 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1767 | const Twine &NameStr, |
1768 | BasicBlock *InsertAtEnd) { |
1769 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
1770 | } |
1771 | |
1772 | const Value *getCondition() const { return Op<0>(); } |
1773 | const Value *getTrueValue() const { return Op<1>(); } |
1774 | const Value *getFalseValue() const { return Op<2>(); } |
1775 | Value *getCondition() { return Op<0>(); } |
1776 | Value *getTrueValue() { return Op<1>(); } |
1777 | Value *getFalseValue() { return Op<2>(); } |
1778 | |
1779 | void setCondition(Value *V) { Op<0>() = V; } |
1780 | void setTrueValue(Value *V) { Op<1>() = V; } |
1781 | void setFalseValue(Value *V) { Op<2>() = V; } |
1782 | |
1783 | /// Swap the true and false values of the select instruction. |
1784 | /// This doesn't swap prof metadata. |
1785 | void swapValues() { Op<1>().swap(Op<2>()); } |
1786 | |
1787 | /// Return a string if the specified operands are invalid |
1788 | /// for a select operation, otherwise return null. |
1789 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
1790 | |
1791 | /// Transparently provide more efficient getOperand methods. |
1792 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1793 | |
1794 | OtherOps getOpcode() const { |
1795 | return static_cast<OtherOps>(Instruction::getOpcode()); |
1796 | } |
1797 | |
1798 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1799 | static bool classof(const Instruction *I) { |
1800 | return I->getOpcode() == Instruction::Select; |
1801 | } |
1802 | static bool classof(const Value *V) { |
1803 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1804 | } |
1805 | }; |
1806 | |
1807 | template <> |
1808 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
1809 | }; |
1810 | |
1811 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits <SelectInst>::op_begin(this); } SelectInst::const_op_iterator SelectInst::op_begin() const { return OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this)); } SelectInst ::op_iterator SelectInst::op_end() { return OperandTraits< SelectInst>::op_end(this); } SelectInst::const_op_iterator SelectInst::op_end() const { return OperandTraits<SelectInst >::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1811, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst *>(this))[i_nocapture].get()); } void SelectInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1811, __PRETTY_FUNCTION__)); OperandTraits<SelectInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst ::getNumOperands() const { return OperandTraits<SelectInst >::operands(this); } template <int Idx_nocapture> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SelectInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
1812 | |
1813 | //===----------------------------------------------------------------------===// |
1814 | // VAArgInst Class |
1815 | //===----------------------------------------------------------------------===// |
1816 | |
1817 | /// This class represents the va_arg llvm instruction, which returns |
1818 | /// an argument of the specified type given a va_list and increments that list |
1819 | /// |
1820 | class VAArgInst : public UnaryInstruction { |
1821 | protected: |
1822 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1823 | friend class Instruction; |
1824 | |
1825 | VAArgInst *cloneImpl() const; |
1826 | |
1827 | public: |
1828 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
1829 | Instruction *InsertBefore = nullptr) |
1830 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
1831 | setName(NameStr); |
1832 | } |
1833 | |
1834 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
1835 | BasicBlock *InsertAtEnd) |
1836 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
1837 | setName(NameStr); |
1838 | } |
1839 | |
1840 | Value *getPointerOperand() { return getOperand(0); } |
1841 | const Value *getPointerOperand() const { return getOperand(0); } |
1842 | static unsigned getPointerOperandIndex() { return 0U; } |
1843 | |
1844 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1845 | static bool classof(const Instruction *I) { |
1846 | return I->getOpcode() == VAArg; |
1847 | } |
1848 | static bool classof(const Value *V) { |
1849 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1850 | } |
1851 | }; |
1852 | |
1853 | //===----------------------------------------------------------------------===// |
1854 | // ExtractElementInst Class |
1855 | //===----------------------------------------------------------------------===// |
1856 | |
1857 | /// This instruction extracts a single (scalar) |
1858 | /// element from a VectorType value |
1859 | /// |
1860 | class ExtractElementInst : public Instruction { |
1861 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
1862 | Instruction *InsertBefore = nullptr); |
1863 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
1864 | BasicBlock *InsertAtEnd); |
1865 | |
1866 | protected: |
1867 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1868 | friend class Instruction; |
1869 | |
1870 | ExtractElementInst *cloneImpl() const; |
1871 | |
1872 | public: |
1873 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1874 | const Twine &NameStr = "", |
1875 | Instruction *InsertBefore = nullptr) { |
1876 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
1877 | } |
1878 | |
1879 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1880 | const Twine &NameStr, |
1881 | BasicBlock *InsertAtEnd) { |
1882 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
1883 | } |
1884 | |
1885 | /// Return true if an extractelement instruction can be |
1886 | /// formed with the specified operands. |
1887 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
1888 | |
1889 | Value *getVectorOperand() { return Op<0>(); } |
1890 | Value *getIndexOperand() { return Op<1>(); } |
1891 | const Value *getVectorOperand() const { return Op<0>(); } |
1892 | const Value *getIndexOperand() const { return Op<1>(); } |
1893 | |
1894 | VectorType *getVectorOperandType() const { |
1895 | return cast<VectorType>(getVectorOperand()->getType()); |
1896 | } |
1897 | |
1898 | /// Transparently provide more efficient getOperand methods. |
1899 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1900 | |
1901 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1902 | static bool classof(const Instruction *I) { |
1903 | return I->getOpcode() == Instruction::ExtractElement; |
1904 | } |
1905 | static bool classof(const Value *V) { |
1906 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1907 | } |
1908 | }; |
1909 | |
1910 | template <> |
1911 | struct OperandTraits<ExtractElementInst> : |
1912 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
1913 | }; |
1914 | |
1915 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin( ) { return OperandTraits<ExtractElementInst>::op_begin( this); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_begin() const { return OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this)); } ExtractElementInst::op_iterator ExtractElementInst::op_end() { return OperandTraits<ExtractElementInst>::op_end(this ); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_end() const { return OperandTraits<ExtractElementInst >::op_end(const_cast<ExtractElementInst*>(this)); } Value *ExtractElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ExtractElementInst>:: operands(this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1915, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ExtractElementInst>::op_begin(const_cast <ExtractElementInst*>(this))[i_nocapture].get()); } void ExtractElementInst::setOperand(unsigned i_nocapture, Value * Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst >::operands(this) && "setOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1915, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ExtractElementInst::getNumOperands() const { return OperandTraits <ExtractElementInst>::operands(this); } template <int Idx_nocapture> Use &ExtractElementInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ExtractElementInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
1916 | |
1917 | //===----------------------------------------------------------------------===// |
1918 | // InsertElementInst Class |
1919 | //===----------------------------------------------------------------------===// |
1920 | |
1921 | /// This instruction inserts a single (scalar) |
1922 | /// element into a VectorType value |
1923 | /// |
1924 | class InsertElementInst : public Instruction { |
1925 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
1926 | const Twine &NameStr = "", |
1927 | Instruction *InsertBefore = nullptr); |
1928 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
1929 | BasicBlock *InsertAtEnd); |
1930 | |
1931 | protected: |
1932 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1933 | friend class Instruction; |
1934 | |
1935 | InsertElementInst *cloneImpl() const; |
1936 | |
1937 | public: |
1938 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1939 | const Twine &NameStr = "", |
1940 | Instruction *InsertBefore = nullptr) { |
1941 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
1942 | } |
1943 | |
1944 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1945 | const Twine &NameStr, |
1946 | BasicBlock *InsertAtEnd) { |
1947 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
1948 | } |
1949 | |
1950 | /// Return true if an insertelement instruction can be |
1951 | /// formed with the specified operands. |
1952 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
1953 | const Value *Idx); |
1954 | |
1955 | /// Overload to return most specific vector type. |
1956 | /// |
1957 | VectorType *getType() const { |
1958 | return cast<VectorType>(Instruction::getType()); |
1959 | } |
1960 | |
1961 | /// Transparently provide more efficient getOperand methods. |
1962 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1963 | |
1964 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1965 | static bool classof(const Instruction *I) { |
1966 | return I->getOpcode() == Instruction::InsertElement; |
1967 | } |
1968 | static bool classof(const Value *V) { |
1969 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1970 | } |
1971 | }; |
1972 | |
1973 | template <> |
1974 | struct OperandTraits<InsertElementInst> : |
1975 | public FixedNumOperandTraits<InsertElementInst, 3> { |
1976 | }; |
1977 | |
1978 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() { return OperandTraits<InsertElementInst>::op_begin(this ); } InsertElementInst::const_op_iterator InsertElementInst:: op_begin() const { return OperandTraits<InsertElementInst> ::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst ::op_iterator InsertElementInst::op_end() { return OperandTraits <InsertElementInst>::op_end(this); } InsertElementInst:: const_op_iterator InsertElementInst::op_end() const { return OperandTraits <InsertElementInst>::op_end(const_cast<InsertElementInst *>(this)); } Value *InsertElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1978, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertElementInst>::op_begin(const_cast <InsertElementInst*>(this))[i_nocapture].get()); } void InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<InsertElementInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 1978, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertElementInst::getNumOperands() const { return OperandTraits <InsertElementInst>::operands(this); } template <int Idx_nocapture> Use &InsertElementInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &InsertElementInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1979 | |
1980 | //===----------------------------------------------------------------------===// |
1981 | // ShuffleVectorInst Class |
1982 | //===----------------------------------------------------------------------===// |
1983 | |
1984 | constexpr int UndefMaskElem = -1; |
1985 | |
1986 | /// This instruction constructs a fixed permutation of two |
1987 | /// input vectors. |
1988 | /// |
1989 | /// For each element of the result vector, the shuffle mask selects an element |
1990 | /// from one of the input vectors to copy to the result. Non-negative elements |
1991 | /// in the mask represent an index into the concatenated pair of input vectors. |
1992 | /// UndefMaskElem (-1) specifies that the result element is undefined. |
1993 | /// |
1994 | /// For scalable vectors, all the elements of the mask must be 0 or -1. This |
1995 | /// requirement may be relaxed in the future. |
1996 | class ShuffleVectorInst : public Instruction { |
1997 | SmallVector<int, 4> ShuffleMask; |
1998 | Constant *ShuffleMaskForBitcode; |
1999 | |
2000 | protected: |
2001 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2002 | friend class Instruction; |
2003 | |
2004 | ShuffleVectorInst *cloneImpl() const; |
2005 | |
2006 | public: |
2007 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
2008 | const Twine &NameStr = "", |
2009 | Instruction *InsertBefor = nullptr); |
2010 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
2011 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2012 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2013 | const Twine &NameStr = "", |
2014 | Instruction *InsertBefor = nullptr); |
2015 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2016 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2017 | |
2018 | void *operator new(size_t s) { return User::operator new(s, 2); } |
2019 | |
2020 | /// Swap the operands and adjust the mask to preserve the semantics |
2021 | /// of the instruction. |
2022 | void commute(); |
2023 | |
2024 | /// Return true if a shufflevector instruction can be |
2025 | /// formed with the specified operands. |
2026 | static bool isValidOperands(const Value *V1, const Value *V2, |
2027 | const Value *Mask); |
2028 | static bool isValidOperands(const Value *V1, const Value *V2, |
2029 | ArrayRef<int> Mask); |
2030 | |
2031 | /// Overload to return most specific vector type. |
2032 | /// |
2033 | VectorType *getType() const { |
2034 | return cast<VectorType>(Instruction::getType()); |
2035 | } |
2036 | |
2037 | /// Transparently provide more efficient getOperand methods. |
2038 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2039 | |
2040 | /// Return the shuffle mask value of this instruction for the given element |
2041 | /// index. Return UndefMaskElem if the element is undef. |
2042 | int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; } |
2043 | |
2044 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
2045 | /// elements of the mask are returned as UndefMaskElem. |
2046 | static void getShuffleMask(const Constant *Mask, |
2047 | SmallVectorImpl<int> &Result); |
2048 | |
2049 | /// Return the mask for this instruction as a vector of integers. Undefined |
2050 | /// elements of the mask are returned as UndefMaskElem. |
2051 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
2052 | Result.assign(ShuffleMask.begin(), ShuffleMask.end()); |
2053 | } |
2054 | |
2055 | /// Return the mask for this instruction, for use in bitcode. |
2056 | /// |
2057 | /// TODO: This is temporary until we decide a new bitcode encoding for |
2058 | /// shufflevector. |
2059 | Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; } |
2060 | |
2061 | static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
2062 | Type *ResultTy); |
2063 | |
2064 | void setShuffleMask(ArrayRef<int> Mask); |
2065 | |
2066 | ArrayRef<int> getShuffleMask() const { return ShuffleMask; } |
2067 | |
2068 | /// Return true if this shuffle returns a vector with a different number of |
2069 | /// elements than its source vectors. |
2070 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
2071 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
2072 | bool changesLength() const { |
2073 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2074 | ->getElementCount() |
2075 | .getKnownMinValue(); |
2076 | unsigned NumMaskElts = ShuffleMask.size(); |
2077 | return NumSourceElts != NumMaskElts; |
2078 | } |
2079 | |
2080 | /// Return true if this shuffle returns a vector with a greater number of |
2081 | /// elements than its source vectors. |
2082 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
2083 | bool increasesLength() const { |
2084 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2085 | ->getElementCount() |
2086 | .getKnownMinValue(); |
2087 | unsigned NumMaskElts = ShuffleMask.size(); |
2088 | return NumSourceElts < NumMaskElts; |
2089 | } |
2090 | |
2091 | /// Return true if this shuffle mask chooses elements from exactly one source |
2092 | /// vector. |
2093 | /// Example: <7,5,undef,7> |
2094 | /// This assumes that vector operands are the same length as the mask. |
2095 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
2096 | static bool isSingleSourceMask(const Constant *Mask) { |
2097 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2097, __PRETTY_FUNCTION__)); |
2098 | SmallVector<int, 16> MaskAsInts; |
2099 | getShuffleMask(Mask, MaskAsInts); |
2100 | return isSingleSourceMask(MaskAsInts); |
2101 | } |
2102 | |
2103 | /// Return true if this shuffle chooses elements from exactly one source |
2104 | /// vector without changing the length of that vector. |
2105 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
2106 | /// TODO: Optionally allow length-changing shuffles. |
2107 | bool isSingleSource() const { |
2108 | return !changesLength() && isSingleSourceMask(ShuffleMask); |
2109 | } |
2110 | |
2111 | /// Return true if this shuffle mask chooses elements from exactly one source |
2112 | /// vector without lane crossings. A shuffle using this mask is not |
2113 | /// necessarily a no-op because it may change the number of elements from its |
2114 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
2115 | /// Example: <undef,undef,2,3> |
2116 | static bool isIdentityMask(ArrayRef<int> Mask); |
2117 | static bool isIdentityMask(const Constant *Mask) { |
2118 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2118, __PRETTY_FUNCTION__)); |
2119 | SmallVector<int, 16> MaskAsInts; |
2120 | getShuffleMask(Mask, MaskAsInts); |
2121 | return isIdentityMask(MaskAsInts); |
2122 | } |
2123 | |
2124 | /// Return true if this shuffle chooses elements from exactly one source |
2125 | /// vector without lane crossings and does not change the number of elements |
2126 | /// from its input vectors. |
2127 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
2128 | bool isIdentity() const { |
2129 | return !changesLength() && isIdentityMask(ShuffleMask); |
2130 | } |
2131 | |
2132 | /// Return true if this shuffle lengthens exactly one source vector with |
2133 | /// undefs in the high elements. |
2134 | bool isIdentityWithPadding() const; |
2135 | |
2136 | /// Return true if this shuffle extracts the first N elements of exactly one |
2137 | /// source vector. |
2138 | bool isIdentityWithExtract() const; |
2139 | |
2140 | /// Return true if this shuffle concatenates its 2 source vectors. This |
2141 | /// returns false if either input is undefined. In that case, the shuffle is |
2142 | /// is better classified as an identity with padding operation. |
2143 | bool isConcat() const; |
2144 | |
2145 | /// Return true if this shuffle mask chooses elements from its source vectors |
2146 | /// without lane crossings. A shuffle using this mask would be |
2147 | /// equivalent to a vector select with a constant condition operand. |
2148 | /// Example: <4,1,6,undef> |
2149 | /// This returns false if the mask does not choose from both input vectors. |
2150 | /// In that case, the shuffle is better classified as an identity shuffle. |
2151 | /// This assumes that vector operands are the same length as the mask |
2152 | /// (a length-changing shuffle can never be equivalent to a vector select). |
2153 | static bool isSelectMask(ArrayRef<int> Mask); |
2154 | static bool isSelectMask(const Constant *Mask) { |
2155 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2155, __PRETTY_FUNCTION__)); |
2156 | SmallVector<int, 16> MaskAsInts; |
2157 | getShuffleMask(Mask, MaskAsInts); |
2158 | return isSelectMask(MaskAsInts); |
2159 | } |
2160 | |
2161 | /// Return true if this shuffle chooses elements from its source vectors |
2162 | /// without lane crossings and all operands have the same number of elements. |
2163 | /// In other words, this shuffle is equivalent to a vector select with a |
2164 | /// constant condition operand. |
2165 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
2166 | /// This returns false if the mask does not choose from both input vectors. |
2167 | /// In that case, the shuffle is better classified as an identity shuffle. |
2168 | /// TODO: Optionally allow length-changing shuffles. |
2169 | bool isSelect() const { |
2170 | return !changesLength() && isSelectMask(ShuffleMask); |
2171 | } |
2172 | |
2173 | /// Return true if this shuffle mask swaps the order of elements from exactly |
2174 | /// one source vector. |
2175 | /// Example: <7,6,undef,4> |
2176 | /// This assumes that vector operands are the same length as the mask. |
2177 | static bool isReverseMask(ArrayRef<int> Mask); |
2178 | static bool isReverseMask(const Constant *Mask) { |
2179 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2179, __PRETTY_FUNCTION__)); |
2180 | SmallVector<int, 16> MaskAsInts; |
2181 | getShuffleMask(Mask, MaskAsInts); |
2182 | return isReverseMask(MaskAsInts); |
2183 | } |
2184 | |
2185 | /// Return true if this shuffle swaps the order of elements from exactly |
2186 | /// one source vector. |
2187 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
2188 | /// TODO: Optionally allow length-changing shuffles. |
2189 | bool isReverse() const { |
2190 | return !changesLength() && isReverseMask(ShuffleMask); |
2191 | } |
2192 | |
2193 | /// Return true if this shuffle mask chooses all elements with the same value |
2194 | /// as the first element of exactly one source vector. |
2195 | /// Example: <4,undef,undef,4> |
2196 | /// This assumes that vector operands are the same length as the mask. |
2197 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
2198 | static bool isZeroEltSplatMask(const Constant *Mask) { |
2199 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2199, __PRETTY_FUNCTION__)); |
2200 | SmallVector<int, 16> MaskAsInts; |
2201 | getShuffleMask(Mask, MaskAsInts); |
2202 | return isZeroEltSplatMask(MaskAsInts); |
2203 | } |
2204 | |
2205 | /// Return true if all elements of this shuffle are the same value as the |
2206 | /// first element of exactly one source vector without changing the length |
2207 | /// of that vector. |
2208 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
2209 | /// TODO: Optionally allow length-changing shuffles. |
2210 | /// TODO: Optionally allow splats from other elements. |
2211 | bool isZeroEltSplat() const { |
2212 | return !changesLength() && isZeroEltSplatMask(ShuffleMask); |
2213 | } |
2214 | |
2215 | /// Return true if this shuffle mask is a transpose mask. |
2216 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
2217 | /// even- or odd-numbered vector elements from two n-dimensional source |
2218 | /// vectors and write each result into consecutive elements of an |
2219 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
2220 | /// the transpose, one for the even elements and another for the odd elements. |
2221 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
2222 | /// instructions operate. |
2223 | /// |
2224 | /// For example, a simple 2x2 matrix can be transposed with: |
2225 | /// |
2226 | /// ; Original matrix |
2227 | /// m0 = < a, b > |
2228 | /// m1 = < c, d > |
2229 | /// |
2230 | /// ; Transposed matrix |
2231 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
2232 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
2233 | /// |
2234 | /// For matrices having greater than n columns, the resulting nx2 transposed |
2235 | /// matrix is stored in two result vectors such that one vector contains |
2236 | /// interleaved elements from all the even-numbered rows and the other vector |
2237 | /// contains interleaved elements from all the odd-numbered rows. For example, |
2238 | /// a 2x4 matrix can be transposed with: |
2239 | /// |
2240 | /// ; Original matrix |
2241 | /// m0 = < a, b, c, d > |
2242 | /// m1 = < e, f, g, h > |
2243 | /// |
2244 | /// ; Transposed matrix |
2245 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
2246 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
2247 | static bool isTransposeMask(ArrayRef<int> Mask); |
2248 | static bool isTransposeMask(const Constant *Mask) { |
2249 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2249, __PRETTY_FUNCTION__)); |
2250 | SmallVector<int, 16> MaskAsInts; |
2251 | getShuffleMask(Mask, MaskAsInts); |
2252 | return isTransposeMask(MaskAsInts); |
2253 | } |
2254 | |
2255 | /// Return true if this shuffle transposes the elements of its inputs without |
2256 | /// changing the length of the vectors. This operation may also be known as a |
2257 | /// merge or interleave. See the description for isTransposeMask() for the |
2258 | /// exact specification. |
2259 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
2260 | bool isTranspose() const { |
2261 | return !changesLength() && isTransposeMask(ShuffleMask); |
2262 | } |
2263 | |
2264 | /// Return true if this shuffle mask is an extract subvector mask. |
2265 | /// A valid extract subvector mask returns a smaller vector from a single |
2266 | /// source operand. The base extraction index is returned as well. |
2267 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2268 | int &Index); |
2269 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
2270 | int &Index) { |
2271 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2271, __PRETTY_FUNCTION__)); |
2272 | // Not possible to express a shuffle mask for a scalable vector for this |
2273 | // case. |
2274 | if (isa<ScalableVectorType>(Mask->getType())) |
2275 | return false; |
2276 | SmallVector<int, 16> MaskAsInts; |
2277 | getShuffleMask(Mask, MaskAsInts); |
2278 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
2279 | } |
2280 | |
2281 | /// Return true if this shuffle mask is an extract subvector mask. |
2282 | bool isExtractSubvectorMask(int &Index) const { |
2283 | // Not possible to express a shuffle mask for a scalable vector for this |
2284 | // case. |
2285 | if (isa<ScalableVectorType>(getType())) |
2286 | return false; |
2287 | |
2288 | int NumSrcElts = |
2289 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2290 | return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index); |
2291 | } |
2292 | |
2293 | /// Change values in a shuffle permute mask assuming the two vector operands |
2294 | /// of length InVecNumElts have swapped position. |
2295 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
2296 | unsigned InVecNumElts) { |
2297 | for (int &Idx : Mask) { |
2298 | if (Idx == -1) |
2299 | continue; |
2300 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
2301 | assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2302, __PRETTY_FUNCTION__)) |
2302 | "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2302, __PRETTY_FUNCTION__)); |
2303 | } |
2304 | } |
2305 | |
2306 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2307 | static bool classof(const Instruction *I) { |
2308 | return I->getOpcode() == Instruction::ShuffleVector; |
2309 | } |
2310 | static bool classof(const Value *V) { |
2311 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2312 | } |
2313 | }; |
2314 | |
2315 | template <> |
2316 | struct OperandTraits<ShuffleVectorInst> |
2317 | : public FixedNumOperandTraits<ShuffleVectorInst, 2> {}; |
2318 | |
2319 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() { return OperandTraits<ShuffleVectorInst>::op_begin(this ); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst:: op_begin() const { return OperandTraits<ShuffleVectorInst> ::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst ::op_iterator ShuffleVectorInst::op_end() { return OperandTraits <ShuffleVectorInst>::op_end(this); } ShuffleVectorInst:: const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits <ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst *>(this)); } Value *ShuffleVectorInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2319, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ShuffleVectorInst>::op_begin(const_cast <ShuffleVectorInst*>(this))[i_nocapture].get()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<ShuffleVectorInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2319, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ShuffleVectorInst::getNumOperands() const { return OperandTraits <ShuffleVectorInst>::operands(this); } template <int Idx_nocapture> Use &ShuffleVectorInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &ShuffleVectorInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
2320 | |
2321 | //===----------------------------------------------------------------------===// |
2322 | // ExtractValueInst Class |
2323 | //===----------------------------------------------------------------------===// |
2324 | |
2325 | /// This instruction extracts a struct member or array |
2326 | /// element value from an aggregate value. |
2327 | /// |
2328 | class ExtractValueInst : public UnaryInstruction { |
2329 | SmallVector<unsigned, 4> Indices; |
2330 | |
2331 | ExtractValueInst(const ExtractValueInst &EVI); |
2332 | |
2333 | /// Constructors - Create a extractvalue instruction with a base aggregate |
2334 | /// value and a list of indices. The first ctor can optionally insert before |
2335 | /// an existing instruction, the second appends the new instruction to the |
2336 | /// specified BasicBlock. |
2337 | inline ExtractValueInst(Value *Agg, |
2338 | ArrayRef<unsigned> Idxs, |
2339 | const Twine &NameStr, |
2340 | Instruction *InsertBefore); |
2341 | inline ExtractValueInst(Value *Agg, |
2342 | ArrayRef<unsigned> Idxs, |
2343 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2344 | |
2345 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
2346 | |
2347 | protected: |
2348 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2349 | friend class Instruction; |
2350 | |
2351 | ExtractValueInst *cloneImpl() const; |
2352 | |
2353 | public: |
2354 | static ExtractValueInst *Create(Value *Agg, |
2355 | ArrayRef<unsigned> Idxs, |
2356 | const Twine &NameStr = "", |
2357 | Instruction *InsertBefore = nullptr) { |
2358 | return new |
2359 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
2360 | } |
2361 | |
2362 | static ExtractValueInst *Create(Value *Agg, |
2363 | ArrayRef<unsigned> Idxs, |
2364 | const Twine &NameStr, |
2365 | BasicBlock *InsertAtEnd) { |
2366 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
2367 | } |
2368 | |
2369 | /// Returns the type of the element that would be extracted |
2370 | /// with an extractvalue instruction with the specified parameters. |
2371 | /// |
2372 | /// Null is returned if the indices are invalid for the specified type. |
2373 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
2374 | |
2375 | using idx_iterator = const unsigned*; |
2376 | |
2377 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2378 | inline idx_iterator idx_end() const { return Indices.end(); } |
2379 | inline iterator_range<idx_iterator> indices() const { |
2380 | return make_range(idx_begin(), idx_end()); |
2381 | } |
2382 | |
2383 | Value *getAggregateOperand() { |
2384 | return getOperand(0); |
2385 | } |
2386 | const Value *getAggregateOperand() const { |
2387 | return getOperand(0); |
2388 | } |
2389 | static unsigned getAggregateOperandIndex() { |
2390 | return 0U; // get index for modifying correct operand |
2391 | } |
2392 | |
2393 | ArrayRef<unsigned> getIndices() const { |
2394 | return Indices; |
2395 | } |
2396 | |
2397 | unsigned getNumIndices() const { |
2398 | return (unsigned)Indices.size(); |
2399 | } |
2400 | |
2401 | bool hasIndices() const { |
2402 | return true; |
2403 | } |
2404 | |
2405 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2406 | static bool classof(const Instruction *I) { |
2407 | return I->getOpcode() == Instruction::ExtractValue; |
2408 | } |
2409 | static bool classof(const Value *V) { |
2410 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2411 | } |
2412 | }; |
2413 | |
2414 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2415 | ArrayRef<unsigned> Idxs, |
2416 | const Twine &NameStr, |
2417 | Instruction *InsertBefore) |
2418 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2419 | ExtractValue, Agg, InsertBefore) { |
2420 | init(Idxs, NameStr); |
2421 | } |
2422 | |
2423 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2424 | ArrayRef<unsigned> Idxs, |
2425 | const Twine &NameStr, |
2426 | BasicBlock *InsertAtEnd) |
2427 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2428 | ExtractValue, Agg, InsertAtEnd) { |
2429 | init(Idxs, NameStr); |
2430 | } |
2431 | |
2432 | //===----------------------------------------------------------------------===// |
2433 | // InsertValueInst Class |
2434 | //===----------------------------------------------------------------------===// |
2435 | |
2436 | /// This instruction inserts a struct field of array element |
2437 | /// value into an aggregate value. |
2438 | /// |
2439 | class InsertValueInst : public Instruction { |
2440 | SmallVector<unsigned, 4> Indices; |
2441 | |
2442 | InsertValueInst(const InsertValueInst &IVI); |
2443 | |
2444 | /// Constructors - Create a insertvalue instruction with a base aggregate |
2445 | /// value, a value to insert, and a list of indices. The first ctor can |
2446 | /// optionally insert before an existing instruction, the second appends |
2447 | /// the new instruction to the specified BasicBlock. |
2448 | inline InsertValueInst(Value *Agg, Value *Val, |
2449 | ArrayRef<unsigned> Idxs, |
2450 | const Twine &NameStr, |
2451 | Instruction *InsertBefore); |
2452 | inline InsertValueInst(Value *Agg, Value *Val, |
2453 | ArrayRef<unsigned> Idxs, |
2454 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2455 | |
2456 | /// Constructors - These two constructors are convenience methods because one |
2457 | /// and two index insertvalue instructions are so common. |
2458 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
2459 | const Twine &NameStr = "", |
2460 | Instruction *InsertBefore = nullptr); |
2461 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
2462 | BasicBlock *InsertAtEnd); |
2463 | |
2464 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
2465 | const Twine &NameStr); |
2466 | |
2467 | protected: |
2468 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2469 | friend class Instruction; |
2470 | |
2471 | InsertValueInst *cloneImpl() const; |
2472 | |
2473 | public: |
2474 | // allocate space for exactly two operands |
2475 | void *operator new(size_t s) { |
2476 | return User::operator new(s, 2); |
2477 | } |
2478 | |
2479 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2480 | ArrayRef<unsigned> Idxs, |
2481 | const Twine &NameStr = "", |
2482 | Instruction *InsertBefore = nullptr) { |
2483 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
2484 | } |
2485 | |
2486 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2487 | ArrayRef<unsigned> Idxs, |
2488 | const Twine &NameStr, |
2489 | BasicBlock *InsertAtEnd) { |
2490 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
2491 | } |
2492 | |
2493 | /// Transparently provide more efficient getOperand methods. |
2494 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2495 | |
2496 | using idx_iterator = const unsigned*; |
2497 | |
2498 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2499 | inline idx_iterator idx_end() const { return Indices.end(); } |
2500 | inline iterator_range<idx_iterator> indices() const { |
2501 | return make_range(idx_begin(), idx_end()); |
2502 | } |
2503 | |
2504 | Value *getAggregateOperand() { |
2505 | return getOperand(0); |
2506 | } |
2507 | const Value *getAggregateOperand() const { |
2508 | return getOperand(0); |
2509 | } |
2510 | static unsigned getAggregateOperandIndex() { |
2511 | return 0U; // get index for modifying correct operand |
2512 | } |
2513 | |
2514 | Value *getInsertedValueOperand() { |
2515 | return getOperand(1); |
2516 | } |
2517 | const Value *getInsertedValueOperand() const { |
2518 | return getOperand(1); |
2519 | } |
2520 | static unsigned getInsertedValueOperandIndex() { |
2521 | return 1U; // get index for modifying correct operand |
2522 | } |
2523 | |
2524 | ArrayRef<unsigned> getIndices() const { |
2525 | return Indices; |
2526 | } |
2527 | |
2528 | unsigned getNumIndices() const { |
2529 | return (unsigned)Indices.size(); |
2530 | } |
2531 | |
2532 | bool hasIndices() const { |
2533 | return true; |
2534 | } |
2535 | |
2536 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2537 | static bool classof(const Instruction *I) { |
2538 | return I->getOpcode() == Instruction::InsertValue; |
2539 | } |
2540 | static bool classof(const Value *V) { |
2541 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2542 | } |
2543 | }; |
2544 | |
2545 | template <> |
2546 | struct OperandTraits<InsertValueInst> : |
2547 | public FixedNumOperandTraits<InsertValueInst, 2> { |
2548 | }; |
2549 | |
2550 | InsertValueInst::InsertValueInst(Value *Agg, |
2551 | Value *Val, |
2552 | ArrayRef<unsigned> Idxs, |
2553 | const Twine &NameStr, |
2554 | Instruction *InsertBefore) |
2555 | : Instruction(Agg->getType(), InsertValue, |
2556 | OperandTraits<InsertValueInst>::op_begin(this), |
2557 | 2, InsertBefore) { |
2558 | init(Agg, Val, Idxs, NameStr); |
2559 | } |
2560 | |
2561 | InsertValueInst::InsertValueInst(Value *Agg, |
2562 | Value *Val, |
2563 | ArrayRef<unsigned> Idxs, |
2564 | const Twine &NameStr, |
2565 | BasicBlock *InsertAtEnd) |
2566 | : Instruction(Agg->getType(), InsertValue, |
2567 | OperandTraits<InsertValueInst>::op_begin(this), |
2568 | 2, InsertAtEnd) { |
2569 | init(Agg, Val, Idxs, NameStr); |
2570 | } |
2571 | |
2572 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst ::const_op_iterator InsertValueInst::op_begin() const { return OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst ::op_end() { return OperandTraits<InsertValueInst>::op_end (this); } InsertValueInst::const_op_iterator InsertValueInst:: op_end() const { return OperandTraits<InsertValueInst>:: op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertValueInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2572, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<InsertValueInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2572, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertValueInst::getNumOperands() const { return OperandTraits <InsertValueInst>::operands(this); } template <int Idx_nocapture > Use &InsertValueInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertValueInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
2573 | |
2574 | //===----------------------------------------------------------------------===// |
2575 | // PHINode Class |
2576 | //===----------------------------------------------------------------------===// |
2577 | |
2578 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
2579 | // node, that can not exist in nature, but can be synthesized in a computer |
2580 | // scientist's overactive imagination. |
2581 | // |
2582 | class PHINode : public Instruction { |
2583 | /// The number of operands actually allocated. NumOperands is |
2584 | /// the number actually in use. |
2585 | unsigned ReservedSpace; |
2586 | |
2587 | PHINode(const PHINode &PN); |
2588 | |
2589 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
2590 | const Twine &NameStr = "", |
2591 | Instruction *InsertBefore = nullptr) |
2592 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
2593 | ReservedSpace(NumReservedValues) { |
2594 | setName(NameStr); |
2595 | allocHungoffUses(ReservedSpace); |
2596 | } |
2597 | |
2598 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
2599 | BasicBlock *InsertAtEnd) |
2600 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
2601 | ReservedSpace(NumReservedValues) { |
2602 | setName(NameStr); |
2603 | allocHungoffUses(ReservedSpace); |
2604 | } |
2605 | |
2606 | protected: |
2607 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2608 | friend class Instruction; |
2609 | |
2610 | PHINode *cloneImpl() const; |
2611 | |
2612 | // allocHungoffUses - this is more complicated than the generic |
2613 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
2614 | // values and pointers to the incoming blocks, all in one allocation. |
2615 | void allocHungoffUses(unsigned N) { |
2616 | User::allocHungoffUses(N, /* IsPhi */ true); |
2617 | } |
2618 | |
2619 | public: |
2620 | /// Constructors - NumReservedValues is a hint for the number of incoming |
2621 | /// edges that this phi node will have (use 0 if you really have no idea). |
2622 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2623 | const Twine &NameStr = "", |
2624 | Instruction *InsertBefore = nullptr) { |
2625 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
2626 | } |
2627 | |
2628 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2629 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
2630 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
2631 | } |
2632 | |
2633 | /// Provide fast operand accessors |
2634 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2635 | |
2636 | // Block iterator interface. This provides access to the list of incoming |
2637 | // basic blocks, which parallels the list of incoming values. |
2638 | |
2639 | using block_iterator = BasicBlock **; |
2640 | using const_block_iterator = BasicBlock * const *; |
2641 | |
2642 | block_iterator block_begin() { |
2643 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
2644 | } |
2645 | |
2646 | const_block_iterator block_begin() const { |
2647 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
2648 | } |
2649 | |
2650 | block_iterator block_end() { |
2651 | return block_begin() + getNumOperands(); |
2652 | } |
2653 | |
2654 | const_block_iterator block_end() const { |
2655 | return block_begin() + getNumOperands(); |
2656 | } |
2657 | |
2658 | iterator_range<block_iterator> blocks() { |
2659 | return make_range(block_begin(), block_end()); |
2660 | } |
2661 | |
2662 | iterator_range<const_block_iterator> blocks() const { |
2663 | return make_range(block_begin(), block_end()); |
2664 | } |
2665 | |
2666 | op_range incoming_values() { return operands(); } |
2667 | |
2668 | const_op_range incoming_values() const { return operands(); } |
2669 | |
2670 | /// Return the number of incoming edges |
2671 | /// |
2672 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
2673 | |
2674 | /// Return incoming value number x |
2675 | /// |
2676 | Value *getIncomingValue(unsigned i) const { |
2677 | return getOperand(i); |
2678 | } |
2679 | void setIncomingValue(unsigned i, Value *V) { |
2680 | assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast< void> (0) : __assert_fail ("V && \"PHI node got a null value!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2680, __PRETTY_FUNCTION__)); |
2681 | assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2682, __PRETTY_FUNCTION__)) |
2682 | "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2682, __PRETTY_FUNCTION__)); |
2683 | setOperand(i, V); |
2684 | } |
2685 | |
2686 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
2687 | return i; |
2688 | } |
2689 | |
2690 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
2691 | return i; |
2692 | } |
2693 | |
2694 | /// Return incoming basic block number @p i. |
2695 | /// |
2696 | BasicBlock *getIncomingBlock(unsigned i) const { |
2697 | return block_begin()[i]; |
2698 | } |
2699 | |
2700 | /// Return incoming basic block corresponding |
2701 | /// to an operand of the PHI. |
2702 | /// |
2703 | BasicBlock *getIncomingBlock(const Use &U) const { |
2704 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?" ) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2704, __PRETTY_FUNCTION__)); |
2705 | return getIncomingBlock(unsigned(&U - op_begin())); |
2706 | } |
2707 | |
2708 | /// Return incoming basic block corresponding |
2709 | /// to value use iterator. |
2710 | /// |
2711 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
2712 | return getIncomingBlock(I.getUse()); |
2713 | } |
2714 | |
2715 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
2716 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2716, __PRETTY_FUNCTION__)); |
2717 | block_begin()[i] = BB; |
2718 | } |
2719 | |
2720 | /// Replace every incoming basic block \p Old to basic block \p New. |
2721 | void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) { |
2722 | assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!" ) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2722, __PRETTY_FUNCTION__)); |
2723 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2724 | if (getIncomingBlock(Op) == Old) |
2725 | setIncomingBlock(Op, New); |
2726 | } |
2727 | |
2728 | /// Add an incoming value to the end of the PHI list |
2729 | /// |
2730 | void addIncoming(Value *V, BasicBlock *BB) { |
2731 | if (getNumOperands() == ReservedSpace) |
2732 | growOperands(); // Get more space! |
2733 | // Initialize some new operands. |
2734 | setNumHungOffUseOperands(getNumOperands() + 1); |
2735 | setIncomingValue(getNumOperands() - 1, V); |
2736 | setIncomingBlock(getNumOperands() - 1, BB); |
2737 | } |
2738 | |
2739 | /// Remove an incoming value. This is useful if a |
2740 | /// predecessor basic block is deleted. The value removed is returned. |
2741 | /// |
2742 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
2743 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
2744 | /// dummy values. The only time there should be zero incoming values to a PHI |
2745 | /// node is when the block is dead, so this strategy is sound. |
2746 | /// |
2747 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
2748 | |
2749 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
2750 | int Idx = getBasicBlockIndex(BB); |
2751 | assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!" ) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2751, __PRETTY_FUNCTION__)); |
2752 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
2753 | } |
2754 | |
2755 | /// Return the first index of the specified basic |
2756 | /// block in the value list for this PHI. Returns -1 if no instance. |
2757 | /// |
2758 | int getBasicBlockIndex(const BasicBlock *BB) const { |
2759 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
2760 | if (block_begin()[i] == BB) |
2761 | return i; |
2762 | return -1; |
2763 | } |
2764 | |
2765 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
2766 | int Idx = getBasicBlockIndex(BB); |
2767 | assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast <void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2767, __PRETTY_FUNCTION__)); |
2768 | return getIncomingValue(Idx); |
2769 | } |
2770 | |
2771 | /// Set every incoming value(s) for block \p BB to \p V. |
2772 | void setIncomingValueForBlock(const BasicBlock *BB, Value *V) { |
2773 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2773, __PRETTY_FUNCTION__)); |
2774 | bool Found = false; |
2775 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2776 | if (getIncomingBlock(Op) == BB) { |
2777 | Found = true; |
2778 | setIncomingValue(Op, V); |
2779 | } |
2780 | (void)Found; |
2781 | assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast <void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2781, __PRETTY_FUNCTION__)); |
2782 | } |
2783 | |
2784 | /// If the specified PHI node always merges together the |
2785 | /// same value, return the value, otherwise return null. |
2786 | Value *hasConstantValue() const; |
2787 | |
2788 | /// Whether the specified PHI node always merges |
2789 | /// together the same value, assuming undefs are equal to a unique |
2790 | /// non-undef value. |
2791 | bool hasConstantOrUndefValue() const; |
2792 | |
2793 | /// If the PHI node is complete which means all of its parent's predecessors |
2794 | /// have incoming value in this PHI, return true, otherwise return false. |
2795 | bool isComplete() const { |
2796 | return llvm::all_of(predecessors(getParent()), |
2797 | [this](const BasicBlock *Pred) { |
2798 | return getBasicBlockIndex(Pred) >= 0; |
2799 | }); |
2800 | } |
2801 | |
2802 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
2803 | static bool classof(const Instruction *I) { |
2804 | return I->getOpcode() == Instruction::PHI; |
2805 | } |
2806 | static bool classof(const Value *V) { |
2807 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2808 | } |
2809 | |
2810 | private: |
2811 | void growOperands(); |
2812 | }; |
2813 | |
2814 | template <> |
2815 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
2816 | }; |
2817 | |
2818 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits <PHINode>::op_begin(this); } PHINode::const_op_iterator PHINode::op_begin() const { return OperandTraits<PHINode> ::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator PHINode::op_end() { return OperandTraits<PHINode>::op_end (this); } PHINode::const_op_iterator PHINode::op_end() const { return OperandTraits<PHINode>::op_end(const_cast<PHINode *>(this)); } Value *PHINode::getOperand(unsigned i_nocapture ) const { ((i_nocapture < OperandTraits<PHINode>::operands (this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2818, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<PHINode>::op_begin(const_cast<PHINode *>(this))[i_nocapture].get()); } void PHINode::setOperand( unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<PHINode>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2818, __PRETTY_FUNCTION__)); OperandTraits<PHINode>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode ::getNumOperands() const { return OperandTraits<PHINode> ::operands(this); } template <int Idx_nocapture> Use & PHINode::Op() { return this->OpFrom<Idx_nocapture>(this ); } template <int Idx_nocapture> const Use &PHINode ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2819 | |
2820 | //===----------------------------------------------------------------------===// |
2821 | // LandingPadInst Class |
2822 | //===----------------------------------------------------------------------===// |
2823 | |
2824 | //===--------------------------------------------------------------------------- |
2825 | /// The landingpad instruction holds all of the information |
2826 | /// necessary to generate correct exception handling. The landingpad instruction |
2827 | /// cannot be moved from the top of a landing pad block, which itself is |
2828 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
2829 | /// SubclassData field in Value to store whether or not the landingpad is a |
2830 | /// cleanup. |
2831 | /// |
2832 | class LandingPadInst : public Instruction { |
2833 | using CleanupField = BoolBitfieldElementT<0>; |
2834 | |
2835 | /// The number of operands actually allocated. NumOperands is |
2836 | /// the number actually in use. |
2837 | unsigned ReservedSpace; |
2838 | |
2839 | LandingPadInst(const LandingPadInst &LP); |
2840 | |
2841 | public: |
2842 | enum ClauseType { Catch, Filter }; |
2843 | |
2844 | private: |
2845 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2846 | const Twine &NameStr, Instruction *InsertBefore); |
2847 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2848 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2849 | |
2850 | // Allocate space for exactly zero operands. |
2851 | void *operator new(size_t s) { |
2852 | return User::operator new(s); |
2853 | } |
2854 | |
2855 | void growOperands(unsigned Size); |
2856 | void init(unsigned NumReservedValues, const Twine &NameStr); |
2857 | |
2858 | protected: |
2859 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2860 | friend class Instruction; |
2861 | |
2862 | LandingPadInst *cloneImpl() const; |
2863 | |
2864 | public: |
2865 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
2866 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
2867 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2868 | const Twine &NameStr = "", |
2869 | Instruction *InsertBefore = nullptr); |
2870 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2871 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2872 | |
2873 | /// Provide fast operand accessors |
2874 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2875 | |
2876 | /// Return 'true' if this landingpad instruction is a |
2877 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
2878 | /// doesn't catch the exception. |
2879 | bool isCleanup() const { return getSubclassData<CleanupField>(); } |
2880 | |
2881 | /// Indicate that this landingpad instruction is a cleanup. |
2882 | void setCleanup(bool V) { setSubclassData<CleanupField>(V); } |
2883 | |
2884 | /// Add a catch or filter clause to the landing pad. |
2885 | void addClause(Constant *ClauseVal); |
2886 | |
2887 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
2888 | /// determine what type of clause this is. |
2889 | Constant *getClause(unsigned Idx) const { |
2890 | return cast<Constant>(getOperandList()[Idx]); |
2891 | } |
2892 | |
2893 | /// Return 'true' if the clause and index Idx is a catch clause. |
2894 | bool isCatch(unsigned Idx) const { |
2895 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
2896 | } |
2897 | |
2898 | /// Return 'true' if the clause and index Idx is a filter clause. |
2899 | bool isFilter(unsigned Idx) const { |
2900 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
2901 | } |
2902 | |
2903 | /// Get the number of clauses for this landing pad. |
2904 | unsigned getNumClauses() const { return getNumOperands(); } |
2905 | |
2906 | /// Grow the size of the operand list to accommodate the new |
2907 | /// number of clauses. |
2908 | void reserveClauses(unsigned Size) { growOperands(Size); } |
2909 | |
2910 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2911 | static bool classof(const Instruction *I) { |
2912 | return I->getOpcode() == Instruction::LandingPad; |
2913 | } |
2914 | static bool classof(const Value *V) { |
2915 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2916 | } |
2917 | }; |
2918 | |
2919 | template <> |
2920 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
2921 | }; |
2922 | |
2923 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst ::const_op_iterator LandingPadInst::op_begin() const { return OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst ::op_end() { return OperandTraits<LandingPadInst>::op_end (this); } LandingPadInst::const_op_iterator LandingPadInst::op_end () const { return OperandTraits<LandingPadInst>::op_end (const_cast<LandingPadInst*>(this)); } Value *LandingPadInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<LandingPadInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2923, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<LandingPadInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2923, __PRETTY_FUNCTION__)); OperandTraits<LandingPadInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned LandingPadInst::getNumOperands() const { return OperandTraits <LandingPadInst>::operands(this); } template <int Idx_nocapture > Use &LandingPadInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &LandingPadInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
2924 | |
2925 | //===----------------------------------------------------------------------===// |
2926 | // ReturnInst Class |
2927 | //===----------------------------------------------------------------------===// |
2928 | |
2929 | //===--------------------------------------------------------------------------- |
2930 | /// Return a value (possibly void), from a function. Execution |
2931 | /// does not continue in this function any longer. |
2932 | /// |
2933 | class ReturnInst : public Instruction { |
2934 | ReturnInst(const ReturnInst &RI); |
2935 | |
2936 | private: |
2937 | // ReturnInst constructors: |
2938 | // ReturnInst() - 'ret void' instruction |
2939 | // ReturnInst( null) - 'ret void' instruction |
2940 | // ReturnInst(Value* X) - 'ret X' instruction |
2941 | // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I |
2942 | // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I |
2943 | // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B |
2944 | // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B |
2945 | // |
2946 | // NOTE: If the Value* passed is of type void then the constructor behaves as |
2947 | // if it was passed NULL. |
2948 | explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr, |
2949 | Instruction *InsertBefore = nullptr); |
2950 | ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd); |
2951 | explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
2952 | |
2953 | protected: |
2954 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2955 | friend class Instruction; |
2956 | |
2957 | ReturnInst *cloneImpl() const; |
2958 | |
2959 | public: |
2960 | static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr, |
2961 | Instruction *InsertBefore = nullptr) { |
2962 | return new(!!retVal) ReturnInst(C, retVal, InsertBefore); |
2963 | } |
2964 | |
2965 | static ReturnInst* Create(LLVMContext &C, Value *retVal, |
2966 | BasicBlock *InsertAtEnd) { |
2967 | return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd); |
2968 | } |
2969 | |
2970 | static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) { |
2971 | return new(0) ReturnInst(C, InsertAtEnd); |
2972 | } |
2973 | |
2974 | /// Provide fast operand accessors |
2975 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2976 | |
2977 | /// Convenience accessor. Returns null if there is no return value. |
2978 | Value *getReturnValue() const { |
2979 | return getNumOperands() != 0 ? getOperand(0) : nullptr; |
2980 | } |
2981 | |
2982 | unsigned getNumSuccessors() const { return 0; } |
2983 | |
2984 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2985 | static bool classof(const Instruction *I) { |
2986 | return (I->getOpcode() == Instruction::Ret); |
2987 | } |
2988 | static bool classof(const Value *V) { |
2989 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2990 | } |
2991 | |
2992 | private: |
2993 | BasicBlock *getSuccessor(unsigned idx) const { |
2994 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2994); |
2995 | } |
2996 | |
2997 | void setSuccessor(unsigned idx, BasicBlock *B) { |
2998 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 2998); |
2999 | } |
3000 | }; |
3001 | |
3002 | template <> |
3003 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
3004 | }; |
3005 | |
3006 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits <ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator ReturnInst::op_begin() const { return OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst ::op_iterator ReturnInst::op_end() { return OperandTraits< ReturnInst>::op_end(this); } ReturnInst::const_op_iterator ReturnInst::op_end() const { return OperandTraits<ReturnInst >::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3006, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ReturnInst>::op_begin(const_cast<ReturnInst *>(this))[i_nocapture].get()); } void ReturnInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3006, __PRETTY_FUNCTION__)); OperandTraits<ReturnInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ReturnInst ::getNumOperands() const { return OperandTraits<ReturnInst >::operands(this); } template <int Idx_nocapture> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ReturnInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3007 | |
3008 | //===----------------------------------------------------------------------===// |
3009 | // BranchInst Class |
3010 | //===----------------------------------------------------------------------===// |
3011 | |
3012 | //===--------------------------------------------------------------------------- |
3013 | /// Conditional or Unconditional Branch instruction. |
3014 | /// |
3015 | class BranchInst : public Instruction { |
3016 | /// Ops list - Branches are strange. The operands are ordered: |
3017 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
3018 | /// they don't have to check for cond/uncond branchness. These are mostly |
3019 | /// accessed relative from op_end(). |
3020 | BranchInst(const BranchInst &BI); |
3021 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
3022 | // BranchInst(BB *B) - 'br B' |
3023 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
3024 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
3025 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
3026 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
3027 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
3028 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
3029 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3030 | Instruction *InsertBefore = nullptr); |
3031 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
3032 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3033 | BasicBlock *InsertAtEnd); |
3034 | |
3035 | void AssertOK(); |
3036 | |
3037 | protected: |
3038 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3039 | friend class Instruction; |
3040 | |
3041 | BranchInst *cloneImpl() const; |
3042 | |
3043 | public: |
3044 | /// Iterator type that casts an operand to a basic block. |
3045 | /// |
3046 | /// This only makes sense because the successors are stored as adjacent |
3047 | /// operands for branch instructions. |
3048 | struct succ_op_iterator |
3049 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3050 | std::random_access_iterator_tag, BasicBlock *, |
3051 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3052 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3053 | |
3054 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3055 | BasicBlock *operator->() const { return operator*(); } |
3056 | }; |
3057 | |
3058 | /// The const version of `succ_op_iterator`. |
3059 | struct const_succ_op_iterator |
3060 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3061 | std::random_access_iterator_tag, |
3062 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3063 | const BasicBlock *> { |
3064 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3065 | : iterator_adaptor_base(I) {} |
3066 | |
3067 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3068 | const BasicBlock *operator->() const { return operator*(); } |
3069 | }; |
3070 | |
3071 | static BranchInst *Create(BasicBlock *IfTrue, |
3072 | Instruction *InsertBefore = nullptr) { |
3073 | return new(1) BranchInst(IfTrue, InsertBefore); |
3074 | } |
3075 | |
3076 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3077 | Value *Cond, Instruction *InsertBefore = nullptr) { |
3078 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
3079 | } |
3080 | |
3081 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
3082 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
3083 | } |
3084 | |
3085 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3086 | Value *Cond, BasicBlock *InsertAtEnd) { |
3087 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
3088 | } |
3089 | |
3090 | /// Transparently provide more efficient getOperand methods. |
3091 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3092 | |
3093 | bool isUnconditional() const { return getNumOperands() == 1; } |
3094 | bool isConditional() const { return getNumOperands() == 3; } |
3095 | |
3096 | Value *getCondition() const { |
3097 | assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3097, __PRETTY_FUNCTION__)); |
3098 | return Op<-3>(); |
3099 | } |
3100 | |
3101 | void setCondition(Value *V) { |
3102 | assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3102, __PRETTY_FUNCTION__)); |
3103 | Op<-3>() = V; |
3104 | } |
3105 | |
3106 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
3107 | |
3108 | BasicBlock *getSuccessor(unsigned i) const { |
3109 | assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3109, __PRETTY_FUNCTION__)); |
3110 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
3111 | } |
3112 | |
3113 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3114 | assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3114, __PRETTY_FUNCTION__)); |
3115 | *(&Op<-1>() - idx) = NewSucc; |
3116 | } |
3117 | |
3118 | /// Swap the successors of this branch instruction. |
3119 | /// |
3120 | /// Swaps the successors of the branch instruction. This also swaps any |
3121 | /// branch weight metadata associated with the instruction so that it |
3122 | /// continues to map correctly to each operand. |
3123 | void swapSuccessors(); |
3124 | |
3125 | iterator_range<succ_op_iterator> successors() { |
3126 | return make_range( |
3127 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3128 | succ_op_iterator(value_op_end())); |
3129 | } |
3130 | |
3131 | iterator_range<const_succ_op_iterator> successors() const { |
3132 | return make_range(const_succ_op_iterator( |
3133 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3134 | const_succ_op_iterator(value_op_end())); |
3135 | } |
3136 | |
3137 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3138 | static bool classof(const Instruction *I) { |
3139 | return (I->getOpcode() == Instruction::Br); |
3140 | } |
3141 | static bool classof(const Value *V) { |
3142 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3143 | } |
3144 | }; |
3145 | |
3146 | template <> |
3147 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
3148 | }; |
3149 | |
3150 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits <BranchInst>::op_begin(this); } BranchInst::const_op_iterator BranchInst::op_begin() const { return OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this)); } BranchInst ::op_iterator BranchInst::op_end() { return OperandTraits< BranchInst>::op_end(this); } BranchInst::const_op_iterator BranchInst::op_end() const { return OperandTraits<BranchInst >::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3150, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<BranchInst>::op_begin(const_cast<BranchInst *>(this))[i_nocapture].get()); } void BranchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3150, __PRETTY_FUNCTION__)); OperandTraits<BranchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BranchInst ::getNumOperands() const { return OperandTraits<BranchInst >::operands(this); } template <int Idx_nocapture> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & BranchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3151 | |
3152 | //===----------------------------------------------------------------------===// |
3153 | // SwitchInst Class |
3154 | //===----------------------------------------------------------------------===// |
3155 | |
3156 | //===--------------------------------------------------------------------------- |
3157 | /// Multiway switch |
3158 | /// |
3159 | class SwitchInst : public Instruction { |
3160 | unsigned ReservedSpace; |
3161 | |
3162 | // Operand[0] = Value to switch on |
3163 | // Operand[1] = Default basic block destination |
3164 | // Operand[2n ] = Value to match |
3165 | // Operand[2n+1] = BasicBlock to go to on match |
3166 | SwitchInst(const SwitchInst &SI); |
3167 | |
3168 | /// Create a new switch instruction, specifying a value to switch on and a |
3169 | /// default destination. The number of additional cases can be specified here |
3170 | /// to make memory allocation more efficient. This constructor can also |
3171 | /// auto-insert before another instruction. |
3172 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3173 | Instruction *InsertBefore); |
3174 | |
3175 | /// Create a new switch instruction, specifying a value to switch on and a |
3176 | /// default destination. The number of additional cases can be specified here |
3177 | /// to make memory allocation more efficient. This constructor also |
3178 | /// auto-inserts at the end of the specified BasicBlock. |
3179 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3180 | BasicBlock *InsertAtEnd); |
3181 | |
3182 | // allocate space for exactly zero operands |
3183 | void *operator new(size_t s) { |
3184 | return User::operator new(s); |
3185 | } |
3186 | |
3187 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
3188 | void growOperands(); |
3189 | |
3190 | protected: |
3191 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3192 | friend class Instruction; |
3193 | |
3194 | SwitchInst *cloneImpl() const; |
3195 | |
3196 | public: |
3197 | // -2 |
3198 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
3199 | |
3200 | template <typename CaseHandleT> class CaseIteratorImpl; |
3201 | |
3202 | /// A handle to a particular switch case. It exposes a convenient interface |
3203 | /// to both the case value and the successor block. |
3204 | /// |
3205 | /// We define this as a template and instantiate it to form both a const and |
3206 | /// non-const handle. |
3207 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
3208 | class CaseHandleImpl { |
3209 | // Directly befriend both const and non-const iterators. |
3210 | friend class SwitchInst::CaseIteratorImpl< |
3211 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
3212 | |
3213 | protected: |
3214 | // Expose the switch type we're parameterized with to the iterator. |
3215 | using SwitchInstType = SwitchInstT; |
3216 | |
3217 | SwitchInstT *SI; |
3218 | ptrdiff_t Index; |
3219 | |
3220 | CaseHandleImpl() = default; |
3221 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
3222 | |
3223 | public: |
3224 | /// Resolves case value for current case. |
3225 | ConstantIntT *getCaseValue() const { |
3226 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3227, __PRETTY_FUNCTION__)) |
3227 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3227, __PRETTY_FUNCTION__)); |
3228 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
3229 | } |
3230 | |
3231 | /// Resolves successor for current case. |
3232 | BasicBlockT *getCaseSuccessor() const { |
3233 | assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3235, __PRETTY_FUNCTION__)) |
3234 | (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3235, __PRETTY_FUNCTION__)) |
3235 | "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3235, __PRETTY_FUNCTION__)); |
3236 | return SI->getSuccessor(getSuccessorIndex()); |
3237 | } |
3238 | |
3239 | /// Returns number of current case. |
3240 | unsigned getCaseIndex() const { return Index; } |
3241 | |
3242 | /// Returns successor index for current case successor. |
3243 | unsigned getSuccessorIndex() const { |
3244 | assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3246, __PRETTY_FUNCTION__)) |
3245 | (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3246, __PRETTY_FUNCTION__)) |
3246 | "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3246, __PRETTY_FUNCTION__)); |
3247 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
3248 | } |
3249 | |
3250 | bool operator==(const CaseHandleImpl &RHS) const { |
3251 | assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast <void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3251, __PRETTY_FUNCTION__)); |
3252 | return Index == RHS.Index; |
3253 | } |
3254 | }; |
3255 | |
3256 | using ConstCaseHandle = |
3257 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
3258 | |
3259 | class CaseHandle |
3260 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
3261 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
3262 | |
3263 | public: |
3264 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
3265 | |
3266 | /// Sets the new value for current case. |
3267 | void setValue(ConstantInt *V) { |
3268 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3269, __PRETTY_FUNCTION__)) |
3269 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3269, __PRETTY_FUNCTION__)); |
3270 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
3271 | } |
3272 | |
3273 | /// Sets the new successor for current case. |
3274 | void setSuccessor(BasicBlock *S) { |
3275 | SI->setSuccessor(getSuccessorIndex(), S); |
3276 | } |
3277 | }; |
3278 | |
3279 | template <typename CaseHandleT> |
3280 | class CaseIteratorImpl |
3281 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
3282 | std::random_access_iterator_tag, |
3283 | CaseHandleT> { |
3284 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
3285 | |
3286 | CaseHandleT Case; |
3287 | |
3288 | public: |
3289 | /// Default constructed iterator is in an invalid state until assigned to |
3290 | /// a case for a particular switch. |
3291 | CaseIteratorImpl() = default; |
3292 | |
3293 | /// Initializes case iterator for given SwitchInst and for given |
3294 | /// case number. |
3295 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
3296 | |
3297 | /// Initializes case iterator for given SwitchInst and for given |
3298 | /// successor index. |
3299 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
3300 | unsigned SuccessorIndex) { |
3301 | assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3302, __PRETTY_FUNCTION__)) |
3302 | "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3302, __PRETTY_FUNCTION__)); |
3303 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
3304 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
3305 | } |
3306 | |
3307 | /// Support converting to the const variant. This will be a no-op for const |
3308 | /// variant. |
3309 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
3310 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
3311 | } |
3312 | |
3313 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
3314 | // Check index correctness after addition. |
3315 | // Note: Index == getNumCases() means end(). |
3316 | assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3318, __PRETTY_FUNCTION__)) |
3317 | (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3318, __PRETTY_FUNCTION__)) |
3318 | "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3318, __PRETTY_FUNCTION__)); |
3319 | Case.Index += N; |
3320 | return *this; |
3321 | } |
3322 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
3323 | // Check index correctness after subtraction. |
3324 | // Note: Case.Index == getNumCases() means end(). |
3325 | assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3327, __PRETTY_FUNCTION__)) |
3326 | (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3327, __PRETTY_FUNCTION__)) |
3327 | "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3327, __PRETTY_FUNCTION__)); |
3328 | Case.Index -= N; |
3329 | return *this; |
3330 | } |
3331 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
3332 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3332, __PRETTY_FUNCTION__)); |
3333 | return Case.Index - RHS.Case.Index; |
3334 | } |
3335 | bool operator==(const CaseIteratorImpl &RHS) const { |
3336 | return Case == RHS.Case; |
3337 | } |
3338 | bool operator<(const CaseIteratorImpl &RHS) const { |
3339 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3339, __PRETTY_FUNCTION__)); |
3340 | return Case.Index < RHS.Case.Index; |
3341 | } |
3342 | CaseHandleT &operator*() { return Case; } |
3343 | const CaseHandleT &operator*() const { return Case; } |
3344 | }; |
3345 | |
3346 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
3347 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
3348 | |
3349 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3350 | unsigned NumCases, |
3351 | Instruction *InsertBefore = nullptr) { |
3352 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
3353 | } |
3354 | |
3355 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3356 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
3357 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
3358 | } |
3359 | |
3360 | /// Provide fast operand accessors |
3361 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3362 | |
3363 | // Accessor Methods for Switch stmt |
3364 | Value *getCondition() const { return getOperand(0); } |
3365 | void setCondition(Value *V) { setOperand(0, V); } |
3366 | |
3367 | BasicBlock *getDefaultDest() const { |
3368 | return cast<BasicBlock>(getOperand(1)); |
3369 | } |
3370 | |
3371 | void setDefaultDest(BasicBlock *DefaultCase) { |
3372 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
3373 | } |
3374 | |
3375 | /// Return the number of 'cases' in this switch instruction, excluding the |
3376 | /// default case. |
3377 | unsigned getNumCases() const { |
3378 | return getNumOperands()/2 - 1; |
3379 | } |
3380 | |
3381 | /// Returns a read/write iterator that points to the first case in the |
3382 | /// SwitchInst. |
3383 | CaseIt case_begin() { |
3384 | return CaseIt(this, 0); |
3385 | } |
3386 | |
3387 | /// Returns a read-only iterator that points to the first case in the |
3388 | /// SwitchInst. |
3389 | ConstCaseIt case_begin() const { |
3390 | return ConstCaseIt(this, 0); |
3391 | } |
3392 | |
3393 | /// Returns a read/write iterator that points one past the last in the |
3394 | /// SwitchInst. |
3395 | CaseIt case_end() { |
3396 | return CaseIt(this, getNumCases()); |
3397 | } |
3398 | |
3399 | /// Returns a read-only iterator that points one past the last in the |
3400 | /// SwitchInst. |
3401 | ConstCaseIt case_end() const { |
3402 | return ConstCaseIt(this, getNumCases()); |
3403 | } |
3404 | |
3405 | /// Iteration adapter for range-for loops. |
3406 | iterator_range<CaseIt> cases() { |
3407 | return make_range(case_begin(), case_end()); |
3408 | } |
3409 | |
3410 | /// Constant iteration adapter for range-for loops. |
3411 | iterator_range<ConstCaseIt> cases() const { |
3412 | return make_range(case_begin(), case_end()); |
3413 | } |
3414 | |
3415 | /// Returns an iterator that points to the default case. |
3416 | /// Note: this iterator allows to resolve successor only. Attempt |
3417 | /// to resolve case value causes an assertion. |
3418 | /// Also note, that increment and decrement also causes an assertion and |
3419 | /// makes iterator invalid. |
3420 | CaseIt case_default() { |
3421 | return CaseIt(this, DefaultPseudoIndex); |
3422 | } |
3423 | ConstCaseIt case_default() const { |
3424 | return ConstCaseIt(this, DefaultPseudoIndex); |
3425 | } |
3426 | |
3427 | /// Search all of the case values for the specified constant. If it is |
3428 | /// explicitly handled, return the case iterator of it, otherwise return |
3429 | /// default case iterator to indicate that it is handled by the default |
3430 | /// handler. |
3431 | CaseIt findCaseValue(const ConstantInt *C) { |
3432 | CaseIt I = llvm::find_if( |
3433 | cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; }); |
3434 | if (I != case_end()) |
3435 | return I; |
3436 | |
3437 | return case_default(); |
3438 | } |
3439 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
3440 | ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) { |
3441 | return Case.getCaseValue() == C; |
3442 | }); |
3443 | if (I != case_end()) |
3444 | return I; |
3445 | |
3446 | return case_default(); |
3447 | } |
3448 | |
3449 | /// Finds the unique case value for a given successor. Returns null if the |
3450 | /// successor is not found, not unique, or is the default case. |
3451 | ConstantInt *findCaseDest(BasicBlock *BB) { |
3452 | if (BB == getDefaultDest()) |
3453 | return nullptr; |
3454 | |
3455 | ConstantInt *CI = nullptr; |
3456 | for (auto Case : cases()) { |
3457 | if (Case.getCaseSuccessor() != BB) |
3458 | continue; |
3459 | |
3460 | if (CI) |
3461 | return nullptr; // Multiple cases lead to BB. |
3462 | |
3463 | CI = Case.getCaseValue(); |
3464 | } |
3465 | |
3466 | return CI; |
3467 | } |
3468 | |
3469 | /// Add an entry to the switch instruction. |
3470 | /// Note: |
3471 | /// This action invalidates case_end(). Old case_end() iterator will |
3472 | /// point to the added case. |
3473 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
3474 | |
3475 | /// This method removes the specified case and its successor from the switch |
3476 | /// instruction. Note that this operation may reorder the remaining cases at |
3477 | /// index idx and above. |
3478 | /// Note: |
3479 | /// This action invalidates iterators for all cases following the one removed, |
3480 | /// including the case_end() iterator. It returns an iterator for the next |
3481 | /// case. |
3482 | CaseIt removeCase(CaseIt I); |
3483 | |
3484 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
3485 | BasicBlock *getSuccessor(unsigned idx) const { |
3486 | assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((idx < getNumSuccessors() &&"Successor idx out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3486, __PRETTY_FUNCTION__)); |
3487 | return cast<BasicBlock>(getOperand(idx*2+1)); |
3488 | } |
3489 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3490 | assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((idx < getNumSuccessors() && "Successor # out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3490, __PRETTY_FUNCTION__)); |
3491 | setOperand(idx * 2 + 1, NewSucc); |
3492 | } |
3493 | |
3494 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3495 | static bool classof(const Instruction *I) { |
3496 | return I->getOpcode() == Instruction::Switch; |
3497 | } |
3498 | static bool classof(const Value *V) { |
3499 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3500 | } |
3501 | }; |
3502 | |
3503 | /// A wrapper class to simplify modification of SwitchInst cases along with |
3504 | /// their prof branch_weights metadata. |
3505 | class SwitchInstProfUpdateWrapper { |
3506 | SwitchInst &SI; |
3507 | Optional<SmallVector<uint32_t, 8> > Weights = None; |
3508 | bool Changed = false; |
3509 | |
3510 | protected: |
3511 | static MDNode *getProfBranchWeightsMD(const SwitchInst &SI); |
3512 | |
3513 | MDNode *buildProfBranchWeightsMD(); |
3514 | |
3515 | void init(); |
3516 | |
3517 | public: |
3518 | using CaseWeightOpt = Optional<uint32_t>; |
3519 | SwitchInst *operator->() { return &SI; } |
3520 | SwitchInst &operator*() { return SI; } |
3521 | operator SwitchInst *() { return &SI; } |
3522 | |
3523 | SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); } |
3524 | |
3525 | ~SwitchInstProfUpdateWrapper() { |
3526 | if (Changed) |
3527 | SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD()); |
3528 | } |
3529 | |
3530 | /// Delegate the call to the underlying SwitchInst::removeCase() and remove |
3531 | /// correspondent branch weight. |
3532 | SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I); |
3533 | |
3534 | /// Delegate the call to the underlying SwitchInst::addCase() and set the |
3535 | /// specified branch weight for the added case. |
3536 | void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W); |
3537 | |
3538 | /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark |
3539 | /// this object to not touch the underlying SwitchInst in destructor. |
3540 | SymbolTableList<Instruction>::iterator eraseFromParent(); |
3541 | |
3542 | void setSuccessorWeight(unsigned idx, CaseWeightOpt W); |
3543 | CaseWeightOpt getSuccessorWeight(unsigned idx); |
3544 | |
3545 | static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx); |
3546 | }; |
3547 | |
3548 | template <> |
3549 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
3550 | }; |
3551 | |
3552 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits <SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator SwitchInst::op_begin() const { return OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst ::op_iterator SwitchInst::op_end() { return OperandTraits< SwitchInst>::op_end(this); } SwitchInst::const_op_iterator SwitchInst::op_end() const { return OperandTraits<SwitchInst >::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3552, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SwitchInst>::op_begin(const_cast<SwitchInst *>(this))[i_nocapture].get()); } void SwitchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/IR/Instructions.h" , 3552, __PRETTY_FUNCTION__)); OperandTraits<SwitchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SwitchInst ::getNumOperands() const { return OperandTraits<SwitchInst >::operands(this); } template <int Idx_nocapture> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SwitchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3553 | |
3554 | //===----------------------------------------------------------------------===// |
3555 | // IndirectBrInst Class |
3556 | //===----------------------------------------------------------------------===// |
3557 | |
3558 | //===--------------------------------------------------------------------------- |
3559 | /// Indirect Branch Instruction. |
3560 | /// |
3561 | class IndirectBrInst : public Instruction { |
3562 | unsigned ReservedSpace; |
3563 | |
3564 | // Operand[0] = Address to jump to |
3565 | // Operand[n+1] = n-th destination |
3566 | IndirectBrInst(const IndirectBrInst &IBI); |
3567 | |
3568 | /// Create a new indirectbr instruction, specifying an |
3569 | /// Address to jump to. The number of expected destinations can be specified |
3570 | /// here to make memory allocation more efficient. This constructor can also |
3571 | /// autoinsert before another instruction. |
3572 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
3573 | |
3574 | /// Create a new indirectbr instruction, specifying an |
3575 | /// Address to jump to. The number of expected destinations can be specified |
3576 | /// here to make memory allocation more efficient. This constructor also |
3577 | /// autoinserts at the end of the specified BasicBlock. |
3578 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
3579 | |
3580 | // allocate space for exactly zero operands |
3581 | void *operator new(size_t s) { |
3582 | return User::operator new(s); |
3583 | } |
3584 | |
3585 | void init(Value *Address, unsigned NumDests); |
3586 | void growOperands(); |
3587 | |
3588 | protected: |
3589 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3590 | friend class Instruction; |
3591 | |
3592 | IndirectBrInst *cloneImpl() const; |
3593 | |
3594 | public: |
3595 | /// Iterator type that casts an operand to a basic block. |
3596 | /// |
3597 | /// This only makes sense because the successors are stored as adjacent |
3598 | /// operands for indirectbr instructions. |
3599 | struct succ_op_iterator |
3600 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3601 | std::random_access_iterator_tag, BasicBlock *, |
3602 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3603 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3604 | |
3605 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3606 | BasicBlock *operator->() const { return operator*(); } |
3607 | }; |
3608 | |
3609 | /// The const version of `succ_op_iterator`. |
3610 | struct const_succ_op_iterator |
3611 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3612 | std::random_access_iterator_tag, |
3613 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3614 | const BasicBlock *> { |
3615 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3616 | : iterator_adaptor_base(I) {} |
3617 | |
3618 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3619 | const BasicBlock *operator->() const { return operator*(); } |
3620 | }; |
3621 | |
3622 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3623 | Instruction *InsertBefore = nullptr) { |
3624 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
3625 | } |
3626 | |
3627 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3628 | BasicBlock *InsertAtEnd) { |
3629 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
3630 | } |
3631 | |
3632 | /// Provide fast operand accessors. |
3633 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3634 | |
3635 | // Accessor Methods for IndirectBrInst instruction. |
3636 | Value *getAddress() { return getOperand(0); } |
3637 | const Value *getAddress() const { return getOperand(0); } |
3638 | void setAddress(Value *V) { setOperand(0, V); } |
3639 | |
3640 | /// return the number of possible destinations in this |
3641 | /// indirectbr instruction. |
3642 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
3643 | |
3644 | /// Return the specified destination. |
3645 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
3646 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
3647 | |
3648 | /// Add a destination. |
3649 | /// |
3650 | void addDestination(BasicBlock *Dest); |
3651 | |
3652 | /// This method removes the specified successor from the |
3653 | /// indirectbr instruction. |
3654 | void removeDestination(unsigned i); |
3655 | |
3656 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
3657 | BasicBlock *getSuccessor(unsigned i) const { |
3658 | return cast<BasicBlock>(getOperand(i+1)); |
3659 | } |
3660 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3661 | setOperand(i + 1, NewSucc); |
3662 | } |
3663 | |
3664 | iterator_range<succ_op_iterator> successors() { |
3665 |