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