1 | //===-- llvm/Instruction.h - Instruction class definition -------*- 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 contains the declaration of the Instruction class, which is the |
10 | // base class for all of the LLVM instructions. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_IR_INSTRUCTION_H |
15 | #define LLVM_IR_INSTRUCTION_H |
16 | |
17 | #include "llvm/ADT/ArrayRef.h" |
18 | #include "llvm/ADT/Bitfields.h" |
19 | #include "llvm/ADT/StringRef.h" |
20 | #include "llvm/ADT/ilist_node.h" |
21 | #include "llvm/IR/DebugLoc.h" |
22 | #include "llvm/IR/SymbolTableListTraits.h" |
23 | #include "llvm/IR/User.h" |
24 | #include "llvm/IR/Value.h" |
25 | #include "llvm/Support/AtomicOrdering.h" |
26 | #include <cstdint> |
27 | #include <utility> |
28 | |
29 | namespace llvm { |
30 | |
31 | class BasicBlock; |
32 | class DPMarker; |
33 | class FastMathFlags; |
34 | class MDNode; |
35 | class Module; |
36 | struct AAMDNodes; |
37 | class DPMarker; |
38 | |
39 | template <> struct ilist_alloc_traits<Instruction> { |
40 | static inline void deleteNode(Instruction *V); |
41 | }; |
42 | |
43 | iterator_range<simple_ilist<DPValue>::iterator> getDbgValueRange(DPMarker *); |
44 | |
45 | class Instruction : public User, |
46 | public ilist_node_with_parent<Instruction, BasicBlock, |
47 | ilist_iterator_bits<true>> { |
48 | public: |
49 | using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>>; |
50 | private: |
51 | BasicBlock *Parent; |
52 | DebugLoc DbgLoc; // 'dbg' Metadata cache. |
53 | |
54 | /// Relative order of this instruction in its parent basic block. Used for |
55 | /// O(1) local dominance checks between instructions. |
56 | mutable unsigned Order = 0; |
57 | |
58 | public: |
59 | /// Optional marker recording the position for debugging information that |
60 | /// takes effect immediately before this instruction. Null unless there is |
61 | /// debugging information present. |
62 | DPMarker *DbgMarker = nullptr; |
63 | |
64 | /// Clone any debug-info attached to \p From onto this instruction. Used to |
65 | /// copy debugging information from one block to another, when copying entire |
66 | /// blocks. \see DebugProgramInstruction.h , because the ordering of DPValues |
67 | /// is still important, fine grain control of which instructions are moved and |
68 | /// where they go is necessary. |
69 | /// \p From The instruction to clone debug-info from. |
70 | /// \p from_here Optional iterator to limit DPValues cloned to be a range from |
71 | /// from_here to end(). |
72 | /// \p InsertAtHead Whether the cloned DPValues should be placed at the end |
73 | /// or the beginning of existing DPValues attached to this. |
74 | /// \returns A range over the newly cloned DPValues. |
75 | iterator_range<simple_ilist<DPValue>::iterator> cloneDebugInfoFrom( |
76 | const Instruction *From, |
77 | std::optional<simple_ilist<DPValue>::iterator> FromHere = std::nullopt, |
78 | bool InsertAtHead = false); |
79 | |
80 | /// Return a range over the DPValues attached to this instruction. |
81 | iterator_range<simple_ilist<DPValue>::iterator> getDbgValueRange() const { |
82 | return llvm::getDbgValueRange(DbgMarker); |
83 | } |
84 | |
85 | /// Return an iterator to the position of the "Next" DPValue after this |
86 | /// instruction, or std::nullopt. This is the position to pass to |
87 | /// BasicBlock::reinsertInstInDPValues when re-inserting an instruction. |
88 | std::optional<simple_ilist<DPValue>::iterator> getDbgReinsertionPosition(); |
89 | |
90 | /// Returns true if any DPValues are attached to this instruction. |
91 | bool hasDbgValues() const; |
92 | |
93 | /// Transfer any DPValues on the position \p It onto this instruction, |
94 | /// by simply adopting the sequence of DPValues (which is efficient) if |
95 | /// possible, by merging two sequences otherwise. |
96 | void adoptDbgValues(BasicBlock *BB, InstListType::iterator It, |
97 | bool InsertAtHead); |
98 | |
99 | /// Erase any DPValues attached to this instruction. |
100 | void dropDbgValues(); |
101 | |
102 | /// Erase a single DPValue \p I that is attached to this instruction. |
103 | void dropOneDbgValue(DPValue *I); |
104 | |
105 | /// Handle the debug-info implications of this instruction being removed. Any |
106 | /// attached DPValues need to "fall" down onto the next instruction. |
107 | void handleMarkerRemoval(); |
108 | |
109 | protected: |
110 | // The 15 first bits of `Value::SubclassData` are available for subclasses of |
111 | // `Instruction` to use. |
112 | using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; |
113 | |
114 | // Template alias so that all Instruction storing alignment use the same |
115 | // definiton. |
116 | // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = |
117 | // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 |
118 | // possible values. |
119 | template <unsigned Offset> |
120 | using AlignmentBitfieldElementT = |
121 | typename Bitfield::Element<unsigned, Offset, 6, |
122 | Value::MaxAlignmentExponent>; |
123 | |
124 | template <unsigned Offset> |
125 | using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; |
126 | |
127 | template <unsigned Offset> |
128 | using AtomicOrderingBitfieldElementT = |
129 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
130 | AtomicOrdering::LAST>; |
131 | |
132 | private: |
133 | // The last bit is used to store whether the instruction has metadata attached |
134 | // or not. |
135 | using HasMetadataField = Bitfield::Element<bool, 15, 1>; |
136 | |
137 | protected: |
138 | ~Instruction(); // Use deleteValue() to delete a generic Instruction. |
139 | |
140 | public: |
141 | Instruction(const Instruction &) = delete; |
142 | Instruction &operator=(const Instruction &) = delete; |
143 | |
144 | /// Specialize the methods defined in Value, as we know that an instruction |
145 | /// can only be used by other instructions. |
146 | Instruction *user_back() { return cast<Instruction>(Val: *user_begin());} |
147 | const Instruction *user_back() const { return cast<Instruction>(Val: *user_begin());} |
148 | |
149 | inline const BasicBlock *getParent() const { return Parent; } |
150 | inline BasicBlock *getParent() { return Parent; } |
151 | |
152 | /// Return the module owning the function this instruction belongs to |
153 | /// or nullptr it the function does not have a module. |
154 | /// |
155 | /// Note: this is undefined behavior if the instruction does not have a |
156 | /// parent, or the parent basic block does not have a parent function. |
157 | const Module *getModule() const; |
158 | Module *getModule() { |
159 | return const_cast<Module *>( |
160 | static_cast<const Instruction *>(this)->getModule()); |
161 | } |
162 | |
163 | /// Return the function this instruction belongs to. |
164 | /// |
165 | /// Note: it is undefined behavior to call this on an instruction not |
166 | /// currently inserted into a function. |
167 | const Function *getFunction() const; |
168 | Function *getFunction() { |
169 | return const_cast<Function *>( |
170 | static_cast<const Instruction *>(this)->getFunction()); |
171 | } |
172 | |
173 | /// This method unlinks 'this' from the containing basic block, but does not |
174 | /// delete it. |
175 | void removeFromParent(); |
176 | |
177 | /// This method unlinks 'this' from the containing basic block and deletes it. |
178 | /// |
179 | /// \returns an iterator pointing to the element after the erased one |
180 | InstListType::iterator eraseFromParent(); |
181 | |
182 | /// Insert an unlinked instruction into a basic block immediately before |
183 | /// the specified instruction. |
184 | void insertBefore(Instruction *InsertPos); |
185 | void insertBefore(InstListType::iterator InsertPos); |
186 | |
187 | /// Insert an unlinked instruction into a basic block immediately after the |
188 | /// specified instruction. |
189 | void insertAfter(Instruction *InsertPos); |
190 | |
191 | /// Inserts an unlinked instruction into \p ParentBB at position \p It and |
192 | /// returns the iterator of the inserted instruction. |
193 | InstListType::iterator insertInto(BasicBlock *ParentBB, |
194 | InstListType::iterator It); |
195 | |
196 | void insertBefore(BasicBlock &BB, InstListType::iterator InsertPos); |
197 | |
198 | /// Unlink this instruction from its current basic block and insert it into |
199 | /// the basic block that MovePos lives in, right before MovePos. |
200 | void moveBefore(Instruction *MovePos); |
201 | |
202 | /// Perform a \ref moveBefore operation, while signalling that the caller |
203 | /// intends to preserve the original ordering of instructions. This implicitly |
204 | /// means that any adjacent debug-info should move with this instruction. |
205 | /// This method is currently a no-op placeholder, but it will become meaningful |
206 | /// when the "RemoveDIs" project is enabled. |
207 | void moveBeforePreserving(Instruction *MovePos); |
208 | |
209 | private: |
210 | /// RemoveDIs project: all other moves implemented with this method, |
211 | /// centralising debug-info updates into one place. |
212 | void moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve); |
213 | |
214 | public: |
215 | /// Unlink this instruction and insert into BB before I. |
216 | /// |
217 | /// \pre I is a valid iterator into BB. |
218 | void moveBefore(BasicBlock &BB, InstListType::iterator I); |
219 | |
220 | /// (See other overload for moveBeforePreserving). |
221 | void moveBeforePreserving(BasicBlock &BB, InstListType::iterator I); |
222 | |
223 | /// Unlink this instruction from its current basic block and insert it into |
224 | /// the basic block that MovePos lives in, right after MovePos. |
225 | void moveAfter(Instruction *MovePos); |
226 | |
227 | /// See \ref moveBeforePreserving . |
228 | void moveAfterPreserving(Instruction *MovePos); |
229 | |
230 | /// Given an instruction Other in the same basic block as this instruction, |
231 | /// return true if this instruction comes before Other. In this worst case, |
232 | /// this takes linear time in the number of instructions in the block. The |
233 | /// results are cached, so in common cases when the block remains unmodified, |
234 | /// it takes constant time. |
235 | bool comesBefore(const Instruction *Other) const; |
236 | |
237 | /// Get the first insertion point at which the result of this instruction |
238 | /// is defined. This is *not* the directly following instruction in a number |
239 | /// of cases, e.g. phi nodes or terminators that return values. This function |
240 | /// may return null if the insertion after the definition is not possible, |
241 | /// e.g. due to a catchswitch terminator. |
242 | std::optional<InstListType::iterator> getInsertionPointAfterDef(); |
243 | |
244 | //===--------------------------------------------------------------------===// |
245 | // Subclass classification. |
246 | //===--------------------------------------------------------------------===// |
247 | |
248 | /// Returns a member of one of the enums like Instruction::Add. |
249 | unsigned getOpcode() const { return getValueID() - InstructionVal; } |
250 | |
251 | const char *getOpcodeName() const { return getOpcodeName(Opcode: getOpcode()); } |
252 | bool isTerminator() const { return isTerminator(Opcode: getOpcode()); } |
253 | bool isUnaryOp() const { return isUnaryOp(Opcode: getOpcode()); } |
254 | bool isBinaryOp() const { return isBinaryOp(Opcode: getOpcode()); } |
255 | bool isIntDivRem() const { return isIntDivRem(Opcode: getOpcode()); } |
256 | bool isShift() const { return isShift(Opcode: getOpcode()); } |
257 | bool isCast() const { return isCast(Opcode: getOpcode()); } |
258 | bool isFuncletPad() const { return isFuncletPad(Opcode: getOpcode()); } |
259 | bool isSpecialTerminator() const { return isSpecialTerminator(Opcode: getOpcode()); } |
260 | |
261 | /// It checks if this instruction is the only user of at least one of |
262 | /// its operands. |
263 | bool isOnlyUserOfAnyOperand(); |
264 | |
265 | static const char *getOpcodeName(unsigned Opcode); |
266 | |
267 | static inline bool isTerminator(unsigned Opcode) { |
268 | return Opcode >= TermOpsBegin && Opcode < TermOpsEnd; |
269 | } |
270 | |
271 | static inline bool isUnaryOp(unsigned Opcode) { |
272 | return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; |
273 | } |
274 | static inline bool isBinaryOp(unsigned Opcode) { |
275 | return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; |
276 | } |
277 | |
278 | static inline bool isIntDivRem(unsigned Opcode) { |
279 | return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; |
280 | } |
281 | |
282 | /// Determine if the Opcode is one of the shift instructions. |
283 | static inline bool isShift(unsigned Opcode) { |
284 | return Opcode >= Shl && Opcode <= AShr; |
285 | } |
286 | |
287 | /// Return true if this is a logical shift left or a logical shift right. |
288 | inline bool isLogicalShift() const { |
289 | return getOpcode() == Shl || getOpcode() == LShr; |
290 | } |
291 | |
292 | /// Return true if this is an arithmetic shift right. |
293 | inline bool isArithmeticShift() const { |
294 | return getOpcode() == AShr; |
295 | } |
296 | |
297 | /// Determine if the Opcode is and/or/xor. |
298 | static inline bool isBitwiseLogicOp(unsigned Opcode) { |
299 | return Opcode == And || Opcode == Or || Opcode == Xor; |
300 | } |
301 | |
302 | /// Return true if this is and/or/xor. |
303 | inline bool isBitwiseLogicOp() const { |
304 | return isBitwiseLogicOp(Opcode: getOpcode()); |
305 | } |
306 | |
307 | /// Determine if the Opcode is one of the CastInst instructions. |
308 | static inline bool isCast(unsigned Opcode) { |
309 | return Opcode >= CastOpsBegin && Opcode < CastOpsEnd; |
310 | } |
311 | |
312 | /// Determine if the Opcode is one of the FuncletPadInst instructions. |
313 | static inline bool isFuncletPad(unsigned Opcode) { |
314 | return Opcode >= FuncletPadOpsBegin && Opcode < FuncletPadOpsEnd; |
315 | } |
316 | |
317 | /// Returns true if the Opcode is a "special" terminator that does more than |
318 | /// branch to a successor (e.g. have a side effect or return a value). |
319 | static inline bool isSpecialTerminator(unsigned Opcode) { |
320 | switch (Opcode) { |
321 | case Instruction::CatchSwitch: |
322 | case Instruction::CatchRet: |
323 | case Instruction::CleanupRet: |
324 | case Instruction::Invoke: |
325 | case Instruction::Resume: |
326 | case Instruction::CallBr: |
327 | return true; |
328 | default: |
329 | return false; |
330 | } |
331 | } |
332 | |
333 | //===--------------------------------------------------------------------===// |
334 | // Metadata manipulation. |
335 | //===--------------------------------------------------------------------===// |
336 | |
337 | /// Return true if this instruction has any metadata attached to it. |
338 | bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } |
339 | |
340 | /// Return true if this instruction has metadata attached to it other than a |
341 | /// debug location. |
342 | bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } |
343 | |
344 | /// Return true if this instruction has the given type of metadata attached. |
345 | bool hasMetadata(unsigned KindID) const { |
346 | return getMetadata(KindID) != nullptr; |
347 | } |
348 | |
349 | /// Return true if this instruction has the given type of metadata attached. |
350 | bool hasMetadata(StringRef Kind) const { |
351 | return getMetadata(Kind) != nullptr; |
352 | } |
353 | |
354 | /// Get the metadata of given kind attached to this Instruction. |
355 | /// If the metadata is not found then return null. |
356 | MDNode *getMetadata(unsigned KindID) const { |
357 | // Handle 'dbg' as a special case since it is not stored in the hash table. |
358 | if (KindID == LLVMContext::MD_dbg) |
359 | return DbgLoc.getAsMDNode(); |
360 | return Value::getMetadata(KindID); |
361 | } |
362 | |
363 | /// Get the metadata of given kind attached to this Instruction. |
364 | /// If the metadata is not found then return null. |
365 | MDNode *getMetadata(StringRef Kind) const { |
366 | if (!hasMetadata()) return nullptr; |
367 | return getMetadataImpl(Kind); |
368 | } |
369 | |
370 | /// Get all metadata attached to this Instruction. The first element of each |
371 | /// pair returned is the KindID, the second element is the metadata value. |
372 | /// This list is returned sorted by the KindID. |
373 | void |
374 | getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { |
375 | if (hasMetadata()) |
376 | getAllMetadataImpl(MDs); |
377 | } |
378 | |
379 | /// This does the same thing as getAllMetadata, except that it filters out the |
380 | /// debug location. |
381 | void getAllMetadataOtherThanDebugLoc( |
382 | SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { |
383 | Value::getAllMetadata(MDs); |
384 | } |
385 | |
386 | /// Set the metadata of the specified kind to the specified node. This updates |
387 | /// or replaces metadata if already present, or removes it if Node is null. |
388 | void setMetadata(unsigned KindID, MDNode *Node); |
389 | void setMetadata(StringRef Kind, MDNode *Node); |
390 | |
391 | /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, |
392 | /// specifies the list of meta data that needs to be copied. If \p WL is |
393 | /// empty, all meta data will be copied. |
394 | void copyMetadata(const Instruction &SrcInst, |
395 | ArrayRef<unsigned> WL = ArrayRef<unsigned>()); |
396 | |
397 | /// Erase all metadata that matches the predicate. |
398 | void eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred); |
399 | |
400 | /// If the instruction has "branch_weights" MD_prof metadata and the MDNode |
401 | /// has three operands (including name string), swap the order of the |
402 | /// metadata. |
403 | void swapProfMetadata(); |
404 | |
405 | /// Drop all unknown metadata except for debug locations. |
406 | /// @{ |
407 | /// Passes are required to drop metadata they don't understand. This is a |
408 | /// convenience method for passes to do so. |
409 | /// dropUBImplyingAttrsAndUnknownMetadata should be used instead of |
410 | /// this API if the Instruction being modified is a call. |
411 | void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs); |
412 | void dropUnknownNonDebugMetadata() { |
413 | return dropUnknownNonDebugMetadata(KnownIDs: std::nullopt); |
414 | } |
415 | void dropUnknownNonDebugMetadata(unsigned ID1) { |
416 | return dropUnknownNonDebugMetadata(KnownIDs: ArrayRef(ID1)); |
417 | } |
418 | void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) { |
419 | unsigned IDs[] = {ID1, ID2}; |
420 | return dropUnknownNonDebugMetadata(KnownIDs: IDs); |
421 | } |
422 | /// @} |
423 | |
424 | /// Adds an !annotation metadata node with \p Annotation to this instruction. |
425 | /// If this instruction already has !annotation metadata, append \p Annotation |
426 | /// to the existing node. |
427 | void addAnnotationMetadata(StringRef Annotation); |
428 | /// Adds an !annotation metadata node with an array of \p Annotations |
429 | /// as a tuple to this instruction. If this instruction already has |
430 | /// !annotation metadata, append the tuple to |
431 | /// the existing node. |
432 | void addAnnotationMetadata(SmallVector<StringRef> Annotations); |
433 | /// Returns the AA metadata for this instruction. |
434 | AAMDNodes getAAMetadata() const; |
435 | |
436 | /// Sets the AA metadata on this instruction from the AAMDNodes structure. |
437 | void setAAMetadata(const AAMDNodes &N); |
438 | |
439 | /// Sets the nosanitize metadata on this instruction. |
440 | void setNoSanitizeMetadata(); |
441 | |
442 | /// Retrieve total raw weight values of a branch. |
443 | /// Returns true on success with profile total weights filled in. |
444 | /// Returns false if no metadata was found. |
445 | bool (uint64_t &TotalVal) const; |
446 | |
447 | /// Set the debug location information for this instruction. |
448 | void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } |
449 | |
450 | /// Return the debug location for this node as a DebugLoc. |
451 | const DebugLoc &getDebugLoc() const { return DbgLoc; } |
452 | |
453 | /// Fetch the debug location for this node, unless this is a debug intrinsic, |
454 | /// in which case fetch the debug location of the next non-debug node. |
455 | const DebugLoc &getStableDebugLoc() const; |
456 | |
457 | /// Set or clear the nuw flag on this instruction, which must be an operator |
458 | /// which supports this flag. See LangRef.html for the meaning of this flag. |
459 | void setHasNoUnsignedWrap(bool b = true); |
460 | |
461 | /// Set or clear the nsw flag on this instruction, which must be an operator |
462 | /// which supports this flag. See LangRef.html for the meaning of this flag. |
463 | void setHasNoSignedWrap(bool b = true); |
464 | |
465 | /// Set or clear the exact flag on this instruction, which must be an operator |
466 | /// which supports this flag. See LangRef.html for the meaning of this flag. |
467 | void setIsExact(bool b = true); |
468 | |
469 | /// Set or clear the nneg flag on this instruction, which must be a zext |
470 | /// instruction. |
471 | void setNonNeg(bool b = true); |
472 | |
473 | /// Determine whether the no unsigned wrap flag is set. |
474 | bool hasNoUnsignedWrap() const LLVM_READONLY; |
475 | |
476 | /// Determine whether the no signed wrap flag is set. |
477 | bool hasNoSignedWrap() const LLVM_READONLY; |
478 | |
479 | /// Determine whether the the nneg flag is set. |
480 | bool hasNonNeg() const LLVM_READONLY; |
481 | |
482 | /// Return true if this operator has flags which may cause this instruction |
483 | /// to evaluate to poison despite having non-poison inputs. |
484 | bool hasPoisonGeneratingFlags() const LLVM_READONLY; |
485 | |
486 | /// Drops flags that may cause this instruction to evaluate to poison despite |
487 | /// having non-poison inputs. |
488 | void dropPoisonGeneratingFlags(); |
489 | |
490 | /// Return true if this instruction has poison-generating metadata. |
491 | bool hasPoisonGeneratingMetadata() const LLVM_READONLY; |
492 | |
493 | /// Drops metadata that may generate poison. |
494 | void dropPoisonGeneratingMetadata(); |
495 | |
496 | /// Return true if this instruction has poison-generating flags or metadata. |
497 | bool hasPoisonGeneratingFlagsOrMetadata() const { |
498 | return hasPoisonGeneratingFlags() || hasPoisonGeneratingMetadata(); |
499 | } |
500 | |
501 | /// Drops flags and metadata that may generate poison. |
502 | void dropPoisonGeneratingFlagsAndMetadata() { |
503 | dropPoisonGeneratingFlags(); |
504 | dropPoisonGeneratingMetadata(); |
505 | } |
506 | |
507 | /// This function drops non-debug unknown metadata (through |
508 | /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and |
509 | /// return attributes that can cause undefined behaviour. Both of these should |
510 | /// be done by passes which move instructions in IR. |
511 | void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); |
512 | |
513 | /// Drop any attributes or metadata that can cause immediate undefined |
514 | /// behavior. Retain other attributes/metadata on a best-effort basis. |
515 | /// This should be used when speculating instructions. |
516 | void dropUBImplyingAttrsAndMetadata(); |
517 | |
518 | /// Determine whether the exact flag is set. |
519 | bool isExact() const LLVM_READONLY; |
520 | |
521 | /// Set or clear all fast-math-flags on this instruction, which must be an |
522 | /// operator which supports this flag. See LangRef.html for the meaning of |
523 | /// this flag. |
524 | void setFast(bool B); |
525 | |
526 | /// Set or clear the reassociation flag on this instruction, which must be |
527 | /// an operator which supports this flag. See LangRef.html for the meaning of |
528 | /// this flag. |
529 | void setHasAllowReassoc(bool B); |
530 | |
531 | /// Set or clear the no-nans flag on this instruction, which must be an |
532 | /// operator which supports this flag. See LangRef.html for the meaning of |
533 | /// this flag. |
534 | void setHasNoNaNs(bool B); |
535 | |
536 | /// Set or clear the no-infs flag on this instruction, which must be an |
537 | /// operator which supports this flag. See LangRef.html for the meaning of |
538 | /// this flag. |
539 | void setHasNoInfs(bool B); |
540 | |
541 | /// Set or clear the no-signed-zeros flag on this instruction, which must be |
542 | /// an operator which supports this flag. See LangRef.html for the meaning of |
543 | /// this flag. |
544 | void setHasNoSignedZeros(bool B); |
545 | |
546 | /// Set or clear the allow-reciprocal flag on this instruction, which must be |
547 | /// an operator which supports this flag. See LangRef.html for the meaning of |
548 | /// this flag. |
549 | void setHasAllowReciprocal(bool B); |
550 | |
551 | /// Set or clear the allow-contract flag on this instruction, which must be |
552 | /// an operator which supports this flag. See LangRef.html for the meaning of |
553 | /// this flag. |
554 | void setHasAllowContract(bool B); |
555 | |
556 | /// Set or clear the approximate-math-functions flag on this instruction, |
557 | /// which must be an operator which supports this flag. See LangRef.html for |
558 | /// the meaning of this flag. |
559 | void setHasApproxFunc(bool B); |
560 | |
561 | /// Convenience function for setting multiple fast-math flags on this |
562 | /// instruction, which must be an operator which supports these flags. See |
563 | /// LangRef.html for the meaning of these flags. |
564 | void setFastMathFlags(FastMathFlags FMF); |
565 | |
566 | /// Convenience function for transferring all fast-math flag values to this |
567 | /// instruction, which must be an operator which supports these flags. See |
568 | /// LangRef.html for the meaning of these flags. |
569 | void copyFastMathFlags(FastMathFlags FMF); |
570 | |
571 | /// Determine whether all fast-math-flags are set. |
572 | bool isFast() const LLVM_READONLY; |
573 | |
574 | /// Determine whether the allow-reassociation flag is set. |
575 | bool hasAllowReassoc() const LLVM_READONLY; |
576 | |
577 | /// Determine whether the no-NaNs flag is set. |
578 | bool hasNoNaNs() const LLVM_READONLY; |
579 | |
580 | /// Determine whether the no-infs flag is set. |
581 | bool hasNoInfs() const LLVM_READONLY; |
582 | |
583 | /// Determine whether the no-signed-zeros flag is set. |
584 | bool hasNoSignedZeros() const LLVM_READONLY; |
585 | |
586 | /// Determine whether the allow-reciprocal flag is set. |
587 | bool hasAllowReciprocal() const LLVM_READONLY; |
588 | |
589 | /// Determine whether the allow-contract flag is set. |
590 | bool hasAllowContract() const LLVM_READONLY; |
591 | |
592 | /// Determine whether the approximate-math-functions flag is set. |
593 | bool hasApproxFunc() const LLVM_READONLY; |
594 | |
595 | /// Convenience function for getting all the fast-math flags, which must be an |
596 | /// operator which supports these flags. See LangRef.html for the meaning of |
597 | /// these flags. |
598 | FastMathFlags getFastMathFlags() const LLVM_READONLY; |
599 | |
600 | /// Copy I's fast-math flags |
601 | void copyFastMathFlags(const Instruction *I); |
602 | |
603 | /// Convenience method to copy supported exact, fast-math, and (optionally) |
604 | /// wrapping flags from V to this instruction. |
605 | void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); |
606 | |
607 | /// Logical 'and' of any supported wrapping, exact, and fast-math flags of |
608 | /// V and this instruction. |
609 | void andIRFlags(const Value *V); |
610 | |
611 | /// Merge 2 debug locations and apply it to the Instruction. If the |
612 | /// instruction is a CallIns, we need to traverse the inline chain to find |
613 | /// the common scope. This is not efficient for N-way merging as each time |
614 | /// you merge 2 iterations, you need to rebuild the hashmap to find the |
615 | /// common scope. However, we still choose this API because: |
616 | /// 1) Simplicity: it takes 2 locations instead of a list of locations. |
617 | /// 2) In worst case, it increases the complexity from O(N*I) to |
618 | /// O(2*N*I), where N is # of Instructions to merge, and I is the |
619 | /// maximum level of inline stack. So it is still linear. |
620 | /// 3) Merging of call instructions should be extremely rare in real |
621 | /// applications, thus the N-way merging should be in code path. |
622 | /// The DebugLoc attached to this instruction will be overwritten by the |
623 | /// merged DebugLoc. |
624 | void applyMergedLocation(DILocation *LocA, DILocation *LocB); |
625 | |
626 | /// Updates the debug location given that the instruction has been hoisted |
627 | /// from a block to a predecessor of that block. |
628 | /// Note: it is undefined behavior to call this on an instruction not |
629 | /// currently inserted into a function. |
630 | void updateLocationAfterHoist(); |
631 | |
632 | /// Drop the instruction's debug location. This does not guarantee removal |
633 | /// of the !dbg source location attachment, as it must set a line 0 location |
634 | /// with scope information attached on call instructions. To guarantee |
635 | /// removal of the !dbg attachment, use the \ref setDebugLoc() API. |
636 | /// Note: it is undefined behavior to call this on an instruction not |
637 | /// currently inserted into a function. |
638 | void dropLocation(); |
639 | |
640 | /// Merge the DIAssignID metadata from this instruction and those attached to |
641 | /// instructions in \p SourceInstructions. This process performs a RAUW on |
642 | /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every |
643 | /// instruction in \p SourceInstructions needs to have DIAssignID |
644 | /// metadata. If none of them do then nothing happens. If this instruction |
645 | /// does not have a DIAssignID attachment but at least one in \p |
646 | /// SourceInstructions does then the merged one will be attached to |
647 | /// it. However, instructions without attachments in \p SourceInstructions |
648 | /// are not modified. |
649 | void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions); |
650 | |
651 | private: |
652 | // These are all implemented in Metadata.cpp. |
653 | MDNode *getMetadataImpl(StringRef Kind) const; |
654 | void |
655 | getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; |
656 | |
657 | /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr |
658 | /// then clear the mapping for this instruction. |
659 | void updateDIAssignIDMapping(DIAssignID *ID); |
660 | |
661 | public: |
662 | //===--------------------------------------------------------------------===// |
663 | // Predicates and helper methods. |
664 | //===--------------------------------------------------------------------===// |
665 | |
666 | /// Return true if the instruction is associative: |
667 | /// |
668 | /// Associative operators satisfy: x op (y op z) === (x op y) op z |
669 | /// |
670 | /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. |
671 | /// |
672 | bool isAssociative() const LLVM_READONLY; |
673 | static bool isAssociative(unsigned Opcode) { |
674 | return Opcode == And || Opcode == Or || Opcode == Xor || |
675 | Opcode == Add || Opcode == Mul; |
676 | } |
677 | |
678 | /// Return true if the instruction is commutative: |
679 | /// |
680 | /// Commutative operators satisfy: (x op y) === (y op x) |
681 | /// |
682 | /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when |
683 | /// applied to any type. |
684 | /// |
685 | bool isCommutative() const LLVM_READONLY; |
686 | static bool isCommutative(unsigned Opcode) { |
687 | switch (Opcode) { |
688 | case Add: case FAdd: |
689 | case Mul: case FMul: |
690 | case And: case Or: case Xor: |
691 | return true; |
692 | default: |
693 | return false; |
694 | } |
695 | } |
696 | |
697 | /// Return true if the instruction is idempotent: |
698 | /// |
699 | /// Idempotent operators satisfy: x op x === x |
700 | /// |
701 | /// In LLVM, the And and Or operators are idempotent. |
702 | /// |
703 | bool isIdempotent() const { return isIdempotent(Opcode: getOpcode()); } |
704 | static bool isIdempotent(unsigned Opcode) { |
705 | return Opcode == And || Opcode == Or; |
706 | } |
707 | |
708 | /// Return true if the instruction is nilpotent: |
709 | /// |
710 | /// Nilpotent operators satisfy: x op x === Id, |
711 | /// |
712 | /// where Id is the identity for the operator, i.e. a constant such that |
713 | /// x op Id === x and Id op x === x for all x. |
714 | /// |
715 | /// In LLVM, the Xor operator is nilpotent. |
716 | /// |
717 | bool isNilpotent() const { return isNilpotent(Opcode: getOpcode()); } |
718 | static bool isNilpotent(unsigned Opcode) { |
719 | return Opcode == Xor; |
720 | } |
721 | |
722 | /// Return true if this instruction may modify memory. |
723 | bool mayWriteToMemory() const LLVM_READONLY; |
724 | |
725 | /// Return true if this instruction may read memory. |
726 | bool mayReadFromMemory() const LLVM_READONLY; |
727 | |
728 | /// Return true if this instruction may read or write memory. |
729 | bool mayReadOrWriteMemory() const { |
730 | return mayReadFromMemory() || mayWriteToMemory(); |
731 | } |
732 | |
733 | /// Return true if this instruction has an AtomicOrdering of unordered or |
734 | /// higher. |
735 | bool isAtomic() const LLVM_READONLY; |
736 | |
737 | /// Return true if this atomic instruction loads from memory. |
738 | bool hasAtomicLoad() const LLVM_READONLY; |
739 | |
740 | /// Return true if this atomic instruction stores to memory. |
741 | bool hasAtomicStore() const LLVM_READONLY; |
742 | |
743 | /// Return true if this instruction has a volatile memory access. |
744 | bool isVolatile() const LLVM_READONLY; |
745 | |
746 | /// Return the type this instruction accesses in memory, if any. |
747 | Type *getAccessType() const LLVM_READONLY; |
748 | |
749 | /// Return true if this instruction may throw an exception. |
750 | /// |
751 | /// If IncludePhaseOneUnwind is set, this will also include cases where |
752 | /// phase one unwinding may unwind past this frame due to skipping of |
753 | /// cleanup landingpads. |
754 | bool mayThrow(bool IncludePhaseOneUnwind = false) const LLVM_READONLY; |
755 | |
756 | /// Return true if this instruction behaves like a memory fence: it can load |
757 | /// or store to memory location without being given a memory location. |
758 | bool isFenceLike() const { |
759 | switch (getOpcode()) { |
760 | default: |
761 | return false; |
762 | // This list should be kept in sync with the list in mayWriteToMemory for |
763 | // all opcodes which don't have a memory location. |
764 | case Instruction::Fence: |
765 | case Instruction::CatchPad: |
766 | case Instruction::CatchRet: |
767 | case Instruction::Call: |
768 | case Instruction::Invoke: |
769 | return true; |
770 | } |
771 | } |
772 | |
773 | /// Return true if the instruction may have side effects. |
774 | /// |
775 | /// Side effects are: |
776 | /// * Writing to memory. |
777 | /// * Unwinding. |
778 | /// * Not returning (e.g. an infinite loop). |
779 | /// |
780 | /// Note that this does not consider malloc and alloca to have side |
781 | /// effects because the newly allocated memory is completely invisible to |
782 | /// instructions which don't use the returned value. For cases where this |
783 | /// matters, isSafeToSpeculativelyExecute may be more appropriate. |
784 | bool mayHaveSideEffects() const LLVM_READONLY; |
785 | |
786 | /// Return true if the instruction can be removed if the result is unused. |
787 | /// |
788 | /// When constant folding some instructions cannot be removed even if their |
789 | /// results are unused. Specifically terminator instructions and calls that |
790 | /// may have side effects cannot be removed without semantically changing the |
791 | /// generated program. |
792 | bool isSafeToRemove() const LLVM_READONLY; |
793 | |
794 | /// Return true if the instruction will return (unwinding is considered as |
795 | /// a form of returning control flow here). |
796 | bool willReturn() const LLVM_READONLY; |
797 | |
798 | /// Return true if the instruction is a variety of EH-block. |
799 | bool isEHPad() const { |
800 | switch (getOpcode()) { |
801 | case Instruction::CatchSwitch: |
802 | case Instruction::CatchPad: |
803 | case Instruction::CleanupPad: |
804 | case Instruction::LandingPad: |
805 | return true; |
806 | default: |
807 | return false; |
808 | } |
809 | } |
810 | |
811 | /// Return true if the instruction is a llvm.lifetime.start or |
812 | /// llvm.lifetime.end marker. |
813 | bool isLifetimeStartOrEnd() const LLVM_READONLY; |
814 | |
815 | /// Return true if the instruction is a llvm.launder.invariant.group or |
816 | /// llvm.strip.invariant.group. |
817 | bool isLaunderOrStripInvariantGroup() const LLVM_READONLY; |
818 | |
819 | /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. |
820 | bool isDebugOrPseudoInst() const LLVM_READONLY; |
821 | |
822 | /// Return a pointer to the next non-debug instruction in the same basic |
823 | /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo |
824 | /// operations if \c SkipPseudoOp is true. |
825 | const Instruction * |
826 | getNextNonDebugInstruction(bool SkipPseudoOp = false) const; |
827 | Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { |
828 | return const_cast<Instruction *>( |
829 | static_cast<const Instruction *>(this)->getNextNonDebugInstruction( |
830 | SkipPseudoOp)); |
831 | } |
832 | |
833 | /// Return a pointer to the previous non-debug instruction in the same basic |
834 | /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo |
835 | /// operations if \c SkipPseudoOp is true. |
836 | const Instruction * |
837 | getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; |
838 | Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { |
839 | return const_cast<Instruction *>( |
840 | static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( |
841 | SkipPseudoOp)); |
842 | } |
843 | |
844 | /// Create a copy of 'this' instruction that is identical in all ways except |
845 | /// the following: |
846 | /// * The instruction has no parent |
847 | /// * The instruction has no name |
848 | /// |
849 | Instruction *clone() const; |
850 | |
851 | /// Return true if the specified instruction is exactly identical to the |
852 | /// current one. This means that all operands match and any extra information |
853 | /// (e.g. load is volatile) agree. |
854 | bool isIdenticalTo(const Instruction *I) const LLVM_READONLY; |
855 | |
856 | /// This is like isIdenticalTo, except that it ignores the |
857 | /// SubclassOptionalData flags, which may specify conditions under which the |
858 | /// instruction's result is undefined. |
859 | bool isIdenticalToWhenDefined(const Instruction *I) const LLVM_READONLY; |
860 | |
861 | /// When checking for operation equivalence (using isSameOperationAs) it is |
862 | /// sometimes useful to ignore certain attributes. |
863 | enum OperationEquivalenceFlags { |
864 | /// Check for equivalence ignoring load/store alignment. |
865 | CompareIgnoringAlignment = 1<<0, |
866 | /// Check for equivalence treating a type and a vector of that type |
867 | /// as equivalent. |
868 | CompareUsingScalarTypes = 1<<1 |
869 | }; |
870 | |
871 | /// This function determines if the specified instruction executes the same |
872 | /// operation as the current one. This means that the opcodes, type, operand |
873 | /// types and any other factors affecting the operation must be the same. This |
874 | /// is similar to isIdenticalTo except the operands themselves don't have to |
875 | /// be identical. |
876 | /// @returns true if the specified instruction is the same operation as |
877 | /// the current one. |
878 | /// Determine if one instruction is the same operation as another. |
879 | bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY; |
880 | |
881 | /// This function determines if the speficied instruction has the same |
882 | /// "special" characteristics as the current one. This means that opcode |
883 | /// specific details are the same. As a common example, if we are comparing |
884 | /// loads, then hasSameSpecialState would compare the alignments (among |
885 | /// other things). |
886 | /// @returns true if the specific instruction has the same opcde specific |
887 | /// characteristics as the current one. Determine if one instruction has the |
888 | /// same state as another. |
889 | bool hasSameSpecialState(const Instruction *I2, |
890 | bool IgnoreAlignment = false) const LLVM_READONLY; |
891 | |
892 | /// Return true if there are any uses of this instruction in blocks other than |
893 | /// the specified block. Note that PHI nodes are considered to evaluate their |
894 | /// operands in the corresponding predecessor block. |
895 | bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY; |
896 | |
897 | /// Return the number of successors that this instruction has. The instruction |
898 | /// must be a terminator. |
899 | unsigned getNumSuccessors() const LLVM_READONLY; |
900 | |
901 | /// Return the specified successor. This instruction must be a terminator. |
902 | BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY; |
903 | |
904 | /// Update the specified successor to point at the provided block. This |
905 | /// instruction must be a terminator. |
906 | void setSuccessor(unsigned Idx, BasicBlock *BB); |
907 | |
908 | /// Replace specified successor OldBB to point at the provided block. |
909 | /// This instruction must be a terminator. |
910 | void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); |
911 | |
912 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
913 | static bool classof(const Value *V) { |
914 | return V->getValueID() >= Value::InstructionVal; |
915 | } |
916 | |
917 | //---------------------------------------------------------------------- |
918 | // Exported enumerations. |
919 | // |
920 | enum TermOps { // These terminate basic blocks |
921 | #define FIRST_TERM_INST(N) TermOpsBegin = N, |
922 | #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, |
923 | #define LAST_TERM_INST(N) TermOpsEnd = N+1 |
924 | #include "llvm/IR/Instruction.def" |
925 | }; |
926 | |
927 | enum UnaryOps { |
928 | #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, |
929 | #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, |
930 | #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 |
931 | #include "llvm/IR/Instruction.def" |
932 | }; |
933 | |
934 | enum BinaryOps { |
935 | #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, |
936 | #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, |
937 | #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 |
938 | #include "llvm/IR/Instruction.def" |
939 | }; |
940 | |
941 | enum MemoryOps { |
942 | #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, |
943 | #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, |
944 | #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 |
945 | #include "llvm/IR/Instruction.def" |
946 | }; |
947 | |
948 | enum CastOps { |
949 | #define FIRST_CAST_INST(N) CastOpsBegin = N, |
950 | #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, |
951 | #define LAST_CAST_INST(N) CastOpsEnd = N+1 |
952 | #include "llvm/IR/Instruction.def" |
953 | }; |
954 | |
955 | enum FuncletPadOps { |
956 | #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, |
957 | #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, |
958 | #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 |
959 | #include "llvm/IR/Instruction.def" |
960 | }; |
961 | |
962 | enum OtherOps { |
963 | #define FIRST_OTHER_INST(N) OtherOpsBegin = N, |
964 | #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, |
965 | #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 |
966 | #include "llvm/IR/Instruction.def" |
967 | }; |
968 | |
969 | private: |
970 | friend class SymbolTableListTraits<Instruction, ilist_iterator_bits<true>>; |
971 | friend class BasicBlock; // For renumbering. |
972 | |
973 | // Shadow Value::setValueSubclassData with a private forwarding method so that |
974 | // subclasses cannot accidentally use it. |
975 | void setValueSubclassData(unsigned short D) { |
976 | Value::setValueSubclassData(D); |
977 | } |
978 | |
979 | unsigned short getSubclassDataFromValue() const { |
980 | return Value::getSubclassDataFromValue(); |
981 | } |
982 | |
983 | void setParent(BasicBlock *P); |
984 | |
985 | protected: |
986 | // Instruction subclasses can stick up to 15 bits of stuff into the |
987 | // SubclassData field of instruction with these members. |
988 | |
989 | template <typename BitfieldElement> |
990 | typename BitfieldElement::Type getSubclassData() const { |
991 | static_assert( |
992 | std::is_same<BitfieldElement, HasMetadataField>::value || |
993 | !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), |
994 | "Must not overlap with the metadata bit" ); |
995 | return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); |
996 | } |
997 | |
998 | template <typename BitfieldElement> |
999 | void setSubclassData(typename BitfieldElement::Type Value) { |
1000 | static_assert( |
1001 | std::is_same<BitfieldElement, HasMetadataField>::value || |
1002 | !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), |
1003 | "Must not overlap with the metadata bit" ); |
1004 | auto Storage = getSubclassDataFromValue(); |
1005 | Bitfield::set<BitfieldElement>(Storage, Value); |
1006 | setValueSubclassData(Storage); |
1007 | } |
1008 | |
1009 | Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, |
1010 | Instruction *InsertBefore = nullptr); |
1011 | Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, |
1012 | BasicBlock *InsertAtEnd); |
1013 | |
1014 | private: |
1015 | /// Create a copy of this instruction. |
1016 | Instruction *cloneImpl() const; |
1017 | }; |
1018 | |
1019 | inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { |
1020 | V->deleteValue(); |
1021 | } |
1022 | |
1023 | } // end namespace llvm |
1024 | |
1025 | #endif // LLVM_IR_INSTRUCTION_H |
1026 | |