LLVM 22.0.0git
SelectionDAGISel.h
Go to the documentation of this file.
1//===-- llvm/CodeGen/SelectionDAGISel.h - Common Base Class------*- 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 implements the SelectionDAGISel class, which is used as the common
10// base class for SelectionDAG-based instruction selectors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_SELECTIONDAGISEL_H
15#define LLVM_CODEGEN_SELECTIONDAGISEL_H
16
21#include "llvm/IR/BasicBlock.h"
22#include <memory>
23
24namespace llvm {
25class AAResults;
26class AssumptionCache;
27class TargetInstrInfo;
28class TargetMachine;
29class SSPLayoutInfo;
31class SDValue;
33class MachineFunction;
35class TargetLowering;
40class GCFunctionInfo;
42
43/// SelectionDAGISel - This is the common base class used for SelectionDAG-based
44/// pattern-matching instruction selectors.
46public:
50 std::unique_ptr<FunctionLoweringInfo> FuncInfo;
51 std::unique_ptr<SwiftErrorValueTracking> SwiftError;
56 std::unique_ptr<SelectionDAGBuilder> SDB;
57 mutable std::optional<BatchAAResults> BatchAA;
58 AssumptionCache *AC = nullptr;
59 GCFunctionInfo *GFI = nullptr;
60 SSPLayoutInfo *SP = nullptr;
61#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
62 TargetTransformInfo *TTI = nullptr;
63#endif
69
70 /// Current optimization remark emitter.
71 /// Used to report things like combines and FastISel failures.
72 std::unique_ptr<OptimizationRemarkEmitter> ORE;
73
74 /// True if the function currently processing is in the function printing list
75 /// (i.e. `-filter-print-funcs`).
76 /// This is primarily used by ISEL_DUMP, which spans in multiple member
77 /// functions. Storing the filter result here so that we only need to do the
78 /// filtering once.
79 bool MatchFilterFuncName = false;
81
84 virtual ~SelectionDAGISel();
85
86 /// Returns a (possibly null) pointer to the current BatchAAResults.
88 if (BatchAA.has_value())
89 return &BatchAA.value();
90 return nullptr;
91 }
92
93 const TargetLowering *getTargetLowering() const { return TLI; }
94
97
98 virtual bool runOnMachineFunction(MachineFunction &mf);
99
100 virtual void emitFunctionEntryCode() {}
101
102 /// PreprocessISelDAG - This hook allows targets to hack on the graph before
103 /// instruction selection starts.
104 virtual void PreprocessISelDAG() {}
105
106 /// PostprocessISelDAG() - This hook allows the target to hack on the graph
107 /// right after selection.
108 virtual void PostprocessISelDAG() {}
109
110 /// Main hook for targets to transform nodes into machine nodes.
111 virtual void Select(SDNode *N) = 0;
112
113 /// SelectInlineAsmMemoryOperand - Select the specified address as a target
114 /// addressing mode, according to the specified constraint. If this does
115 /// not match or is not implemented, return true. The resultant operands
116 /// (which will appear in the machine instruction) should be added to the
117 /// OutOps vector.
118 virtual bool
120 InlineAsm::ConstraintCode ConstraintID,
121 std::vector<SDValue> &OutOps) {
122 return true;
123 }
124
125 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
126 /// operand node N of U during instruction selection that starts at Root.
127 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
128
129 /// IsLegalToFold - Returns true if the specific operand node N of
130 /// U can be folded during instruction selection that starts at Root.
131 /// FIXME: This is a static member function because the MSP430/X86
132 /// targets, which uses it during isel. This could become a proper member.
133 static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
135 bool IgnoreChains = false);
136
137 static void InvalidateNodeId(SDNode *N);
138 static int getUninvalidatedNodeId(SDNode *N);
139
140 static void EnforceNodeIdInvariant(SDNode *N);
141
142 // Opcodes used by the DAG state machine:
203 // Space-optimized forms that implicitly encode VT.
216
225
234
258
260 // Space-optimized forms that implicitly encode integer VT.
266 // Space-optimized forms that implicitly encode integer VT.
297 // Space-optimized forms that implicitly encode number of result VTs.
301 // Space-optimized forms that implicitly encode EmitNodeInfo.
309 // Space-optimized forms that implicitly encode number of result VTs.
313 // Space-optimized forms that implicitly encode EmitNodeInfo.
327 // Contains 32-bit offset in table for pattern being selected
329 };
330
331 enum {
332 OPFL_None = 0, // Node has no chain or glue input and isn't variadic.
333 OPFL_Chain = 1, // Node has a chain input.
334 OPFL_GlueInput = 2, // Node has a glue input.
335 OPFL_GlueOutput = 4, // Node has a glue output.
336 OPFL_MemRefs = 8, // Node gets accumulated MemRefs.
337 OPFL_Variadic0 = 1 << 4, // Node is variadic, root has 0 fixed inputs.
338 OPFL_Variadic1 = 2 << 4, // Node is variadic, root has 1 fixed inputs.
339 OPFL_Variadic2 = 3 << 4, // Node is variadic, root has 2 fixed inputs.
340 OPFL_Variadic3 = 4 << 4, // Node is variadic, root has 3 fixed inputs.
341 OPFL_Variadic4 = 5 << 4, // Node is variadic, root has 4 fixed inputs.
342 OPFL_Variadic5 = 6 << 4, // Node is variadic, root has 5 fixed inputs.
343 OPFL_Variadic6 = 7 << 4, // Node is variadic, root has 6 fixed inputs.
344 OPFL_Variadic7 = 8 << 4, // Node is variadic, root has 7 fixed inputs.
345
346 OPFL_VariadicInfo = 15 << 4 // Mask for extracting the OPFL_VariadicN bits.
347 };
348
349 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
350 /// number of fixed arity values that should be skipped when copying from the
351 /// root.
352 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
353 return ((Flags&OPFL_VariadicInfo) >> 4)-1;
354 }
355
356
357protected:
358 /// DAGSize - Size of DAG being instruction selected.
359 ///
360 unsigned DAGSize = 0;
361
362 /// ReplaceUses - replace all uses of the old node F with the use
363 /// of the new node T.
365 CurDAG->ReplaceAllUsesOfValueWith(F, T);
366 EnforceNodeIdInvariant(T.getNode());
367 }
368
369 /// ReplaceUses - replace all uses of the old nodes F with the use
370 /// of the new nodes T.
371 void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num) {
372 CurDAG->ReplaceAllUsesOfValuesWith(F, T, Num);
373 for (unsigned i = 0; i < Num; ++i)
375 }
376
377 /// ReplaceUses - replace all uses of the old node F with the use
378 /// of the new node T.
380 CurDAG->ReplaceAllUsesWith(F, T);
382 }
383
384 /// Replace all uses of \c F with \c T, then remove \c F from the DAG.
386 CurDAG->ReplaceAllUsesWith(F, T);
388 CurDAG->RemoveDeadNode(F);
389 }
390
391 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
392 /// by tblgen. Others should not call it.
393 void SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
394 const SDLoc &DL);
395
396 /// getPatternForIndex - Patterns selected by tablegen during ISEL
397 virtual StringRef getPatternForIndex(unsigned index) {
398 llvm_unreachable("Tblgen should generate the implementation of this!");
399 }
400
401 /// getIncludePathForIndex - get the td source location of pattern instantiation
402 virtual StringRef getIncludePathForIndex(unsigned index) {
403 llvm_unreachable("Tblgen should generate the implementation of this!");
404 }
405
407 return CurDAG->shouldOptForSize();
408 }
409
410public:
411 // Calls to these predicates are generated by tblgen.
413 int64_t DesiredMaskS) const;
415 int64_t DesiredMaskS) const;
416
417
418 /// CheckPatternPredicate - This function is generated by tblgen in the
419 /// target. It runs the specified pattern predicate and returns true if it
420 /// succeeds or false if it fails. The number is a private implementation
421 /// detail to the code tblgen produces.
422 virtual bool CheckPatternPredicate(unsigned PredNo) const {
423 llvm_unreachable("Tblgen should generate the implementation of this!");
424 }
425
426 /// CheckNodePredicate - This function is generated by tblgen in the target.
427 /// It runs node predicate number PredNo and returns true if it succeeds or
428 /// false if it fails. The number is a private implementation
429 /// detail to the code tblgen produces.
430 virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const {
431 llvm_unreachable("Tblgen should generate the implementation of this!");
432 }
433
434 /// CheckNodePredicateWithOperands - This function is generated by tblgen in
435 /// the target.
436 /// It runs node predicate number PredNo and returns true if it succeeds or
437 /// false if it fails. The number is a private implementation detail to the
438 /// code tblgen produces.
439 virtual bool
441 ArrayRef<SDValue> Operands) const {
442 llvm_unreachable("Tblgen should generate the implementation of this!");
443 }
444
445 virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N,
446 unsigned PatternNo,
447 SmallVectorImpl<std::pair<SDValue, SDNode*> > &Result) {
448 llvm_unreachable("Tblgen should generate the implementation of this!");
449 }
450
451 virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {
452 llvm_unreachable("Tblgen should generate this!");
453 }
454
455 void SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
456 unsigned TableSize);
457
458 /// Return true if complex patterns for this target can mutate the
459 /// DAG.
460 virtual bool ComplexPatternFuncMutatesDAG() const {
461 return false;
462 }
463
464 /// Return whether the node may raise an FP exception.
465 bool mayRaiseFPException(SDNode *Node) const;
466
467 bool isOrEquivalentToAdd(const SDNode *N) const;
468
469private:
470
471 // Calls to these functions are generated by tblgen.
472 void Select_INLINEASM(SDNode *N);
473 void Select_READ_REGISTER(SDNode *Op);
474 void Select_WRITE_REGISTER(SDNode *Op);
475 void Select_UNDEF(SDNode *N);
476 void Select_FAKE_USE(SDNode *N);
477 void Select_RELOC_NONE(SDNode *N);
478 void CannotYetSelect(SDNode *N);
479
480 void Select_FREEZE(SDNode *N);
481 void Select_ARITH_FENCE(SDNode *N);
482 void Select_MEMBARRIER(SDNode *N);
483
484 void Select_CONVERGENCECTRL_ANCHOR(SDNode *N);
485 void Select_CONVERGENCECTRL_ENTRY(SDNode *N);
486 void Select_CONVERGENCECTRL_LOOP(SDNode *N);
487
488 void pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops, SDValue Operand,
489 SDLoc DL);
490 void Select_STACKMAP(SDNode *N);
491 void Select_PATCHPOINT(SDNode *N);
492
493 void Select_JUMP_TABLE_DEBUG_INFO(SDNode *N);
494
495private:
496 void DoInstructionSelection();
497 SDNode *MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
498 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo);
499
500 /// Prepares the landing pad to take incoming values or do other EH
501 /// personality specific tasks. Returns true if the block should be
502 /// instruction selected, false if no code should be emitted for it.
503 bool PrepareEHLandingPad();
504
505 // Mark and Report IPToState for each Block under AsynchEH
506 void reportIPToStateForBlocks(MachineFunction *Fn);
507
508 /// Perform instruction selection on all basic blocks in the function.
509 void SelectAllBasicBlocks(const Function &Fn);
510
511 /// Perform instruction selection on a single basic block, for
512 /// instructions between \p Begin and \p End. \p HadTailCall will be set
513 /// to true if a call in the block was translated as a tail call.
514 void SelectBasicBlock(BasicBlock::const_iterator Begin,
516 bool &HadTailCall);
517 void FinishBasicBlock();
518
519 void CodeGenAndEmitDAG();
520
521 /// Generate instructions for lowering the incoming arguments of the
522 /// given function.
523 void LowerArguments(const Function &F);
524
525 void ComputeLiveOutVRegInfo();
526
527 /// Create the scheduler. If a specific scheduler was specified
528 /// via the SchedulerRegistry, use it, otherwise select the
529 /// one preferred by the target.
530 ///
531 ScheduleDAGSDNodes *CreateScheduler();
532
533 /// OpcodeOffset - This is a cache used to dispatch efficiently into isel
534 /// state machines that start with a OPC_SwitchOpcode node.
535 std::vector<unsigned> OpcodeOffset;
536
537 void UpdateChains(SDNode *NodeToMatch, SDValue InputChain,
538 SmallVectorImpl<SDNode *> &ChainNodesMatched,
539 bool isMorphNodeTo);
540};
541
543 std::unique_ptr<SelectionDAGISel> Selector;
544
545public:
546 SelectionDAGISelLegacy(char &ID, std::unique_ptr<SelectionDAGISel> S);
547
548 ~SelectionDAGISelLegacy() override = default;
549
550 void getAnalysisUsage(AnalysisUsage &AU) const override;
551
552 bool runOnMachineFunction(MachineFunction &MF) override;
553};
554
555class SelectionDAGISelPass : public PassInfoMixin<SelectionDAGISelPass> {
556 std::unique_ptr<SelectionDAGISel> Selector;
557
558protected:
559 SelectionDAGISelPass(std::unique_ptr<SelectionDAGISel> Selector)
560 : Selector(std::move(Selector)) {}
561
562public:
565 static bool isRequired() { return true; }
566};
567}
568
569#endif /* LLVM_CODEGEN_SELECTIONDAGISEL_H */
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:55
#define T
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Garbage collection metadata for a single function.
Definition GCMetadata.h:80
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
This class contains meta information specific to a module.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
~SelectionDAGISelLegacy() override=default
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
SelectionDAGISelLegacy(char &ID, std::unique_ptr< SelectionDAGISel > S)
SelectionDAGISelPass(std::unique_ptr< SelectionDAGISel > Selector)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
std::optional< BatchAAResults > BatchAA
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
MachineModuleInfo * MMI
virtual bool CheckNodePredicateWithOperands(SDValue Op, unsigned PredNo, ArrayRef< SDValue > Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
MachineRegisterInfo * RegInfo
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
bool isOrEquivalentToAdd(const SDNode *N) const
virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N, unsigned PatternNo, SmallVectorImpl< std::pair< SDValue, SDNode * > > &Result)
virtual bool CheckPatternPredicate(unsigned PredNo) const
CheckPatternPredicate - This function is generated by tblgen in the target.
static int getNumFixedFromVariadicInfo(unsigned Flags)
getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the number of fixed arity values ...
const TargetLibraryInfo * LibInfo
static int getUninvalidatedNodeId(SDNode *N)
const TargetInstrInfo * TII
std::unique_ptr< SwiftErrorValueTracking > SwiftError
void SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable, unsigned TableSize)
virtual void Select(SDNode *N)=0
Main hook for targets to transform nodes into machine nodes.
void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num)
ReplaceUses - replace all uses of the old nodes F with the use of the new nodes T.
static void EnforceNodeIdInvariant(SDNode *N)
virtual void emitFunctionEntryCode()
const RTLIB::RuntimeLibcallsInfo * RuntimeLibCallInfo
void ReplaceUses(SDValue F, SDValue T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const
IsProfitableToFold - Returns true if it's profitable to fold the specific operand node N of U during ...
virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo)
bool MatchFilterFuncName
True if the function currently processing is in the function printing list (i.e.
void SelectInlineAsmMemoryOperands(std::vector< SDValue > &Ops, const SDLoc &DL)
SelectInlineAsmMemoryOperands - Calls to this are automatically generated by tblgen.
static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOptLevel OptLevel, bool IgnoreChains=false)
IsLegalToFold - Returns true if the specific operand node N of U can be folded during instruction sel...
virtual bool ComplexPatternFuncMutatesDAG() const
Return true if complex patterns for this target can mutate the DAG.
void ReplaceUses(SDNode *F, SDNode *T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual void PreprocessISelDAG()
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
BatchAAResults * getBatchAA() const
Returns a (possibly null) pointer to the current BatchAAResults.
bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckAndMask - The isel is trying to match something like (and X, 255).
virtual StringRef getPatternForIndex(unsigned index)
getPatternForIndex - Patterns selected by tablegen during ISEL
bool mayRaiseFPException(SDNode *Node) const
Return whether the node may raise an FP exception.
std::unique_ptr< SelectionDAGBuilder > SDB
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL=CodeGenOptLevel::Default)
virtual bool runOnMachineFunction(MachineFunction &mf)
static void InvalidateNodeId(SDNode *N)
const TargetLowering * getTargetLowering() const
bool shouldOptForSize(const MachineFunction *MF) const
virtual StringRef getIncludePathForIndex(unsigned index)
getIncludePathForIndex - get the td source location of pattern instantiation
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
@ Default
-O2, -Os
Definition CodeGen.h:85
TargetTransformInfo TTI
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
#define N
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70
A simple container for information about the supported runtime calls.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.