Path: blob/main/contrib/llvm-project/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
35267 views
//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines a DAG pattern matching instruction selector for X86,9// converting from a legalized dag to a X86 dag.10//11//===----------------------------------------------------------------------===//1213#include "X86ISelDAGToDAG.h"14#include "X86.h"15#include "X86MachineFunctionInfo.h"16#include "X86RegisterInfo.h"17#include "X86Subtarget.h"18#include "X86TargetMachine.h"19#include "llvm/ADT/Statistic.h"20#include "llvm/CodeGen/MachineModuleInfo.h"21#include "llvm/CodeGen/SelectionDAGISel.h"22#include "llvm/Config/llvm-config.h"23#include "llvm/IR/ConstantRange.h"24#include "llvm/IR/Function.h"25#include "llvm/IR/Instructions.h"26#include "llvm/IR/Intrinsics.h"27#include "llvm/IR/IntrinsicsX86.h"28#include "llvm/IR/Module.h"29#include "llvm/IR/Type.h"30#include "llvm/Support/Debug.h"31#include "llvm/Support/ErrorHandling.h"32#include "llvm/Support/KnownBits.h"33#include "llvm/Support/MathExtras.h"34#include <cstdint>3536using namespace llvm;3738#define DEBUG_TYPE "x86-isel"39#define PASS_NAME "X86 DAG->DAG Instruction Selection"4041STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");4243static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),44cl::desc("Enable setting constant bits to reduce size of mask immediates"),45cl::Hidden);4647static cl::opt<bool> EnablePromoteAnyextLoad(48"x86-promote-anyext-load", cl::init(true),49cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden);5051extern cl::opt<bool> IndirectBranchTracking;5253//===----------------------------------------------------------------------===//54// Pattern Matcher Implementation55//===----------------------------------------------------------------------===//5657namespace {58/// This corresponds to X86AddressMode, but uses SDValue's instead of register59/// numbers for the leaves of the matched tree.60struct X86ISelAddressMode {61enum {62RegBase,63FrameIndexBase64} BaseType = RegBase;6566// This is really a union, discriminated by BaseType!67SDValue Base_Reg;68int Base_FrameIndex = 0;6970unsigned Scale = 1;71SDValue IndexReg;72int32_t Disp = 0;73SDValue Segment;74const GlobalValue *GV = nullptr;75const Constant *CP = nullptr;76const BlockAddress *BlockAddr = nullptr;77const char *ES = nullptr;78MCSymbol *MCSym = nullptr;79int JT = -1;80Align Alignment; // CP alignment.81unsigned char SymbolFlags = X86II::MO_NO_FLAG; // X86II::MO_*82bool NegateIndex = false;8384X86ISelAddressMode() = default;8586bool hasSymbolicDisplacement() const {87return GV != nullptr || CP != nullptr || ES != nullptr ||88MCSym != nullptr || JT != -1 || BlockAddr != nullptr;89}9091bool hasBaseOrIndexReg() const {92return BaseType == FrameIndexBase ||93IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;94}9596/// Return true if this addressing mode is already RIP-relative.97bool isRIPRelative() const {98if (BaseType != RegBase) return false;99if (RegisterSDNode *RegNode =100dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))101return RegNode->getReg() == X86::RIP;102return false;103}104105void setBaseReg(SDValue Reg) {106BaseType = RegBase;107Base_Reg = Reg;108}109110#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)111void dump(SelectionDAG *DAG = nullptr) {112dbgs() << "X86ISelAddressMode " << this << '\n';113dbgs() << "Base_Reg ";114if (Base_Reg.getNode())115Base_Reg.getNode()->dump(DAG);116else117dbgs() << "nul\n";118if (BaseType == FrameIndexBase)119dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';120dbgs() << " Scale " << Scale << '\n'121<< "IndexReg ";122if (NegateIndex)123dbgs() << "negate ";124if (IndexReg.getNode())125IndexReg.getNode()->dump(DAG);126else127dbgs() << "nul\n";128dbgs() << " Disp " << Disp << '\n'129<< "GV ";130if (GV)131GV->dump();132else133dbgs() << "nul";134dbgs() << " CP ";135if (CP)136CP->dump();137else138dbgs() << "nul";139dbgs() << '\n'140<< "ES ";141if (ES)142dbgs() << ES;143else144dbgs() << "nul";145dbgs() << " MCSym ";146if (MCSym)147dbgs() << MCSym;148else149dbgs() << "nul";150dbgs() << " JT" << JT << " Align" << Alignment.value() << '\n';151}152#endif153};154}155156namespace {157//===--------------------------------------------------------------------===//158/// ISel - X86-specific code to select X86 machine instructions for159/// SelectionDAG operations.160///161class X86DAGToDAGISel final : public SelectionDAGISel {162/// Keep a pointer to the X86Subtarget around so that we can163/// make the right decision when generating code for different targets.164const X86Subtarget *Subtarget;165166/// If true, selector should try to optimize for minimum code size.167bool OptForMinSize;168169/// Disable direct TLS access through segment registers.170bool IndirectTlsSegRefs;171172public:173X86DAGToDAGISel() = delete;174175explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOptLevel OptLevel)176: SelectionDAGISel(tm, OptLevel), Subtarget(nullptr),177OptForMinSize(false), IndirectTlsSegRefs(false) {}178179bool runOnMachineFunction(MachineFunction &MF) override {180// Reset the subtarget each time through.181Subtarget = &MF.getSubtarget<X86Subtarget>();182IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(183"indirect-tls-seg-refs");184185// OptFor[Min]Size are used in pattern predicates that isel is matching.186OptForMinSize = MF.getFunction().hasMinSize();187assert((!OptForMinSize || MF.getFunction().hasOptSize()) &&188"OptForMinSize implies OptForSize");189return SelectionDAGISel::runOnMachineFunction(MF);190}191192void emitFunctionEntryCode() override;193194bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;195196void PreprocessISelDAG() override;197void PostprocessISelDAG() override;198199// Include the pieces autogenerated from the target description.200#include "X86GenDAGISel.inc"201202private:203void Select(SDNode *N) override;204205bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);206bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,207bool AllowSegmentRegForX32 = false);208bool matchWrapper(SDValue N, X86ISelAddressMode &AM);209bool matchAddress(SDValue N, X86ISelAddressMode &AM);210bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);211bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);212SDValue matchIndexRecursively(SDValue N, X86ISelAddressMode &AM,213unsigned Depth);214bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,215unsigned Depth);216bool matchVectorAddressRecursively(SDValue N, X86ISelAddressMode &AM,217unsigned Depth);218bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);219bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,220SDValue &Scale, SDValue &Index, SDValue &Disp,221SDValue &Segment);222bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,223SDValue ScaleOp, SDValue &Base, SDValue &Scale,224SDValue &Index, SDValue &Disp, SDValue &Segment);225bool selectMOV64Imm32(SDValue N, SDValue &Imm);226bool selectLEAAddr(SDValue N, SDValue &Base,227SDValue &Scale, SDValue &Index, SDValue &Disp,228SDValue &Segment);229bool selectLEA64_32Addr(SDValue N, SDValue &Base,230SDValue &Scale, SDValue &Index, SDValue &Disp,231SDValue &Segment);232bool selectTLSADDRAddr(SDValue N, SDValue &Base,233SDValue &Scale, SDValue &Index, SDValue &Disp,234SDValue &Segment);235bool selectRelocImm(SDValue N, SDValue &Op);236237bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,238SDValue &Base, SDValue &Scale,239SDValue &Index, SDValue &Disp,240SDValue &Segment);241242// Convenience method where P is also root.243bool tryFoldLoad(SDNode *P, SDValue N,244SDValue &Base, SDValue &Scale,245SDValue &Index, SDValue &Disp,246SDValue &Segment) {247return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);248}249250bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,251SDValue &Base, SDValue &Scale,252SDValue &Index, SDValue &Disp,253SDValue &Segment);254255bool isProfitableToFormMaskedOp(SDNode *N) const;256257/// Implement addressing mode selection for inline asm expressions.258bool SelectInlineAsmMemoryOperand(const SDValue &Op,259InlineAsm::ConstraintCode ConstraintID,260std::vector<SDValue> &OutOps) override;261262void emitSpecialCodeForMain();263264inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,265MVT VT, SDValue &Base, SDValue &Scale,266SDValue &Index, SDValue &Disp,267SDValue &Segment) {268if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)269Base = CurDAG->getTargetFrameIndex(270AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));271else if (AM.Base_Reg.getNode())272Base = AM.Base_Reg;273else274Base = CurDAG->getRegister(0, VT);275276Scale = getI8Imm(AM.Scale, DL);277278#define GET_ND_IF_ENABLED(OPC) (Subtarget->hasNDD() ? OPC##_ND : OPC)279// Negate the index if needed.280if (AM.NegateIndex) {281unsigned NegOpc = VT == MVT::i64 ? GET_ND_IF_ENABLED(X86::NEG64r)282: GET_ND_IF_ENABLED(X86::NEG32r);283SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,284AM.IndexReg), 0);285AM.IndexReg = Neg;286}287288if (AM.IndexReg.getNode())289Index = AM.IndexReg;290else291Index = CurDAG->getRegister(0, VT);292293// These are 32-bit even in 64-bit mode since RIP-relative offset294// is 32-bit.295if (AM.GV)296Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),297MVT::i32, AM.Disp,298AM.SymbolFlags);299else if (AM.CP)300Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Alignment,301AM.Disp, AM.SymbolFlags);302else if (AM.ES) {303assert(!AM.Disp && "Non-zero displacement is ignored with ES.");304Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);305} else if (AM.MCSym) {306assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");307assert(AM.SymbolFlags == 0 && "oo");308Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);309} else if (AM.JT != -1) {310assert(!AM.Disp && "Non-zero displacement is ignored with JT.");311Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);312} else if (AM.BlockAddr)313Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,314AM.SymbolFlags);315else316Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);317318if (AM.Segment.getNode())319Segment = AM.Segment;320else321Segment = CurDAG->getRegister(0, MVT::i16);322}323324// Utility function to determine whether we should avoid selecting325// immediate forms of instructions for better code size or not.326// At a high level, we'd like to avoid such instructions when327// we have similar constants used within the same basic block328// that can be kept in a register.329//330bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {331uint32_t UseCount = 0;332333// Do not want to hoist if we're not optimizing for size.334// TODO: We'd like to remove this restriction.335// See the comment in X86InstrInfo.td for more info.336if (!CurDAG->shouldOptForSize())337return false;338339// Walk all the users of the immediate.340for (const SDNode *User : N->uses()) {341if (UseCount >= 2)342break;343344// This user is already selected. Count it as a legitimate use and345// move on.346if (User->isMachineOpcode()) {347UseCount++;348continue;349}350351// We want to count stores of immediates as real uses.352if (User->getOpcode() == ISD::STORE &&353User->getOperand(1).getNode() == N) {354UseCount++;355continue;356}357358// We don't currently match users that have > 2 operands (except359// for stores, which are handled above)360// Those instruction won't match in ISEL, for now, and would361// be counted incorrectly.362// This may change in the future as we add additional instruction363// types.364if (User->getNumOperands() != 2)365continue;366367// If this is a sign-extended 8-bit integer immediate used in an ALU368// instruction, there is probably an opcode encoding to save space.369auto *C = dyn_cast<ConstantSDNode>(N);370if (C && isInt<8>(C->getSExtValue()))371continue;372373// Immediates that are used for offsets as part of stack374// manipulation should be left alone. These are typically375// used to indicate SP offsets for argument passing and376// will get pulled into stores/pushes (implicitly).377if (User->getOpcode() == X86ISD::ADD ||378User->getOpcode() == ISD::ADD ||379User->getOpcode() == X86ISD::SUB ||380User->getOpcode() == ISD::SUB) {381382// Find the other operand of the add/sub.383SDValue OtherOp = User->getOperand(0);384if (OtherOp.getNode() == N)385OtherOp = User->getOperand(1);386387// Don't count if the other operand is SP.388RegisterSDNode *RegNode;389if (OtherOp->getOpcode() == ISD::CopyFromReg &&390(RegNode = dyn_cast_or_null<RegisterSDNode>(391OtherOp->getOperand(1).getNode())))392if ((RegNode->getReg() == X86::ESP) ||393(RegNode->getReg() == X86::RSP))394continue;395}396397// ... otherwise, count this and move on.398UseCount++;399}400401// If we have more than 1 use, then recommend for hoisting.402return (UseCount > 1);403}404405/// Return a target constant with the specified value of type i8.406inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {407return CurDAG->getTargetConstant(Imm, DL, MVT::i8);408}409410/// Return a target constant with the specified value, of type i32.411inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {412return CurDAG->getTargetConstant(Imm, DL, MVT::i32);413}414415/// Return a target constant with the specified value, of type i64.416inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {417return CurDAG->getTargetConstant(Imm, DL, MVT::i64);418}419420SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,421const SDLoc &DL) {422assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");423uint64_t Index = N->getConstantOperandVal(1);424MVT VecVT = N->getOperand(0).getSimpleValueType();425return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);426}427428SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,429const SDLoc &DL) {430assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");431uint64_t Index = N->getConstantOperandVal(2);432MVT VecVT = N->getSimpleValueType(0);433return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);434}435436SDValue getPermuteVINSERTCommutedImmediate(SDNode *N, unsigned VecWidth,437const SDLoc &DL) {438assert(VecWidth == 128 && "Unexpected vector width");439uint64_t Index = N->getConstantOperandVal(2);440MVT VecVT = N->getSimpleValueType(0);441uint64_t InsertIdx = (Index * VecVT.getScalarSizeInBits()) / VecWidth;442assert((InsertIdx == 0 || InsertIdx == 1) && "Bad insertf128 index");443// vinsert(0,sub,vec) -> [sub0][vec1] -> vperm2x128(0x30,vec,sub)444// vinsert(1,sub,vec) -> [vec0][sub0] -> vperm2x128(0x02,vec,sub)445return getI8Imm(InsertIdx ? 0x02 : 0x30, DL);446}447448SDValue getSBBZero(SDNode *N) {449SDLoc dl(N);450MVT VT = N->getSimpleValueType(0);451452// Create zero.453SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);454SDValue Zero = SDValue(455CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0);456if (VT == MVT::i64) {457Zero = SDValue(458CurDAG->getMachineNode(459TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,460CurDAG->getTargetConstant(0, dl, MVT::i64), Zero,461CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),4620);463}464465// Copy flags to the EFLAGS register and glue it to next node.466unsigned Opcode = N->getOpcode();467assert((Opcode == X86ISD::SBB || Opcode == X86ISD::SETCC_CARRY) &&468"Unexpected opcode for SBB materialization");469unsigned FlagOpIndex = Opcode == X86ISD::SBB ? 2 : 1;470SDValue EFLAGS =471CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,472N->getOperand(FlagOpIndex), SDValue());473474// Create a 64-bit instruction if the result is 64-bits otherwise use the475// 32-bit version.476unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;477MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;478VTs = CurDAG->getVTList(SBBVT, MVT::i32);479return SDValue(480CurDAG->getMachineNode(Opc, dl, VTs,481{Zero, Zero, EFLAGS, EFLAGS.getValue(1)}),4820);483}484485// Helper to detect unneeded and instructions on shift amounts. Called486// from PatFrags in tablegen.487bool isUnneededShiftMask(SDNode *N, unsigned Width) const {488assert(N->getOpcode() == ISD::AND && "Unexpected opcode");489const APInt &Val = N->getConstantOperandAPInt(1);490491if (Val.countr_one() >= Width)492return true;493494APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;495return Mask.countr_one() >= Width;496}497498/// Return an SDNode that returns the value of the global base register.499/// Output instructions required to initialize the global base register,500/// if necessary.501SDNode *getGlobalBaseReg();502503/// Return a reference to the TargetMachine, casted to the target-specific504/// type.505const X86TargetMachine &getTargetMachine() const {506return static_cast<const X86TargetMachine &>(TM);507}508509/// Return a reference to the TargetInstrInfo, casted to the target-specific510/// type.511const X86InstrInfo *getInstrInfo() const {512return Subtarget->getInstrInfo();513}514515/// Return a condition code of the given SDNode516X86::CondCode getCondFromNode(SDNode *N) const;517518/// Address-mode matching performs shift-of-and to and-of-shift519/// reassociation in order to expose more scaled addressing520/// opportunities.521bool ComplexPatternFuncMutatesDAG() const override {522return true;523}524525bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;526527// Indicates we should prefer to use a non-temporal load for this load.528bool useNonTemporalLoad(LoadSDNode *N) const {529if (!N->isNonTemporal())530return false;531532unsigned StoreSize = N->getMemoryVT().getStoreSize();533534if (N->getAlign().value() < StoreSize)535return false;536537switch (StoreSize) {538default: llvm_unreachable("Unsupported store size");539case 4:540case 8:541return false;542case 16:543return Subtarget->hasSSE41();544case 32:545return Subtarget->hasAVX2();546case 64:547return Subtarget->hasAVX512();548}549}550551bool foldLoadStoreIntoMemOperand(SDNode *Node);552MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);553bool matchBitExtract(SDNode *Node);554bool shrinkAndImmediate(SDNode *N);555bool isMaskZeroExtended(SDNode *N) const;556bool tryShiftAmountMod(SDNode *N);557bool tryShrinkShlLogicImm(SDNode *N);558bool tryVPTERNLOG(SDNode *N);559bool matchVPTERNLOG(SDNode *Root, SDNode *ParentA, SDNode *ParentB,560SDNode *ParentC, SDValue A, SDValue B, SDValue C,561uint8_t Imm);562bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);563bool tryMatchBitSelect(SDNode *N);564565MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,566const SDLoc &dl, MVT VT, SDNode *Node);567MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,568const SDLoc &dl, MVT VT, SDNode *Node,569SDValue &InGlue);570571bool tryOptimizeRem8Extend(SDNode *N);572573bool onlyUsesZeroFlag(SDValue Flags) const;574bool hasNoSignFlagUses(SDValue Flags) const;575bool hasNoCarryFlagUses(SDValue Flags) const;576};577578class X86DAGToDAGISelLegacy : public SelectionDAGISelLegacy {579public:580static char ID;581explicit X86DAGToDAGISelLegacy(X86TargetMachine &tm,582CodeGenOptLevel OptLevel)583: SelectionDAGISelLegacy(584ID, std::make_unique<X86DAGToDAGISel>(tm, OptLevel)) {}585};586}587588char X86DAGToDAGISelLegacy::ID = 0;589590INITIALIZE_PASS(X86DAGToDAGISelLegacy, DEBUG_TYPE, PASS_NAME, false, false)591592// Returns true if this masked compare can be implemented legally with this593// type.594static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {595unsigned Opcode = N->getOpcode();596if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMM ||597Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC ||598Opcode == X86ISD::CMPMM_SAE || Opcode == X86ISD::VFPCLASS) {599// We can get 256-bit 8 element types here without VLX being enabled. When600// this happens we will use 512-bit operations and the mask will not be601// zero extended.602EVT OpVT = N->getOperand(0).getValueType();603// The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the604// second operand.605if (Opcode == X86ISD::STRICT_CMPM)606OpVT = N->getOperand(1).getValueType();607if (OpVT.is256BitVector() || OpVT.is128BitVector())608return Subtarget->hasVLX();609610return true;611}612// Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.613if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||614Opcode == X86ISD::FSETCCM_SAE)615return true;616617return false;618}619620// Returns true if we can assume the writer of the mask has zero extended it621// for us.622bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {623// If this is an AND, check if we have a compare on either side. As long as624// one side guarantees the mask is zero extended, the AND will preserve those625// zeros.626if (N->getOpcode() == ISD::AND)627return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||628isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);629630return isLegalMaskCompare(N, Subtarget);631}632633bool634X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {635if (OptLevel == CodeGenOptLevel::None)636return false;637638if (!N.hasOneUse())639return false;640641if (N.getOpcode() != ISD::LOAD)642return true;643644// Don't fold non-temporal loads if we have an instruction for them.645if (useNonTemporalLoad(cast<LoadSDNode>(N)))646return false;647648// If N is a load, do additional profitability checks.649if (U == Root) {650switch (U->getOpcode()) {651default: break;652case X86ISD::ADD:653case X86ISD::ADC:654case X86ISD::SUB:655case X86ISD::SBB:656case X86ISD::AND:657case X86ISD::XOR:658case X86ISD::OR:659case ISD::ADD:660case ISD::UADDO_CARRY:661case ISD::AND:662case ISD::OR:663case ISD::XOR: {664SDValue Op1 = U->getOperand(1);665666// If the other operand is a 8-bit immediate we should fold the immediate667// instead. This reduces code size.668// e.g.669// movl 4(%esp), %eax670// addl $4, %eax671// vs.672// movl $4, %eax673// addl 4(%esp), %eax674// The former is 2 bytes shorter. In case where the increment is 1, then675// the saving can be 4 bytes (by using incl %eax).676if (auto *Imm = dyn_cast<ConstantSDNode>(Op1)) {677if (Imm->getAPIntValue().isSignedIntN(8))678return false;679680// If this is a 64-bit AND with an immediate that fits in 32-bits,681// prefer using the smaller and over folding the load. This is needed to682// make sure immediates created by shrinkAndImmediate are always folded.683// Ideally we would narrow the load during DAG combine and get the684// best of both worlds.685if (U->getOpcode() == ISD::AND &&686Imm->getAPIntValue().getBitWidth() == 64 &&687Imm->getAPIntValue().isIntN(32))688return false;689690// If this really a zext_inreg that can be represented with a movzx691// instruction, prefer that.692// TODO: We could shrink the load and fold if it is non-volatile.693if (U->getOpcode() == ISD::AND &&694(Imm->getAPIntValue() == UINT8_MAX ||695Imm->getAPIntValue() == UINT16_MAX ||696Imm->getAPIntValue() == UINT32_MAX))697return false;698699// ADD/SUB with can negate the immediate and use the opposite operation700// to fit 128 into a sign extended 8 bit immediate.701if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&702(-Imm->getAPIntValue()).isSignedIntN(8))703return false;704705if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&706(-Imm->getAPIntValue()).isSignedIntN(8) &&707hasNoCarryFlagUses(SDValue(U, 1)))708return false;709}710711// If the other operand is a TLS address, we should fold it instead.712// This produces713// movl %gs:0, %eax714// leal i@NTPOFF(%eax), %eax715// instead of716// movl $i@NTPOFF, %eax717// addl %gs:0, %eax718// if the block also has an access to a second TLS address this will save719// a load.720// FIXME: This is probably also true for non-TLS addresses.721if (Op1.getOpcode() == X86ISD::Wrapper) {722SDValue Val = Op1.getOperand(0);723if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)724return false;725}726727// Don't fold load if this matches the BTS/BTR/BTC patterns.728// BTS: (or X, (shl 1, n))729// BTR: (and X, (rotl -2, n))730// BTC: (xor X, (shl 1, n))731if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {732if (U->getOperand(0).getOpcode() == ISD::SHL &&733isOneConstant(U->getOperand(0).getOperand(0)))734return false;735736if (U->getOperand(1).getOpcode() == ISD::SHL &&737isOneConstant(U->getOperand(1).getOperand(0)))738return false;739}740if (U->getOpcode() == ISD::AND) {741SDValue U0 = U->getOperand(0);742SDValue U1 = U->getOperand(1);743if (U0.getOpcode() == ISD::ROTL) {744auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));745if (C && C->getSExtValue() == -2)746return false;747}748749if (U1.getOpcode() == ISD::ROTL) {750auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));751if (C && C->getSExtValue() == -2)752return false;753}754}755756break;757}758case ISD::SHL:759case ISD::SRA:760case ISD::SRL:761// Don't fold a load into a shift by immediate. The BMI2 instructions762// support folding a load, but not an immediate. The legacy instructions763// support folding an immediate, but can't fold a load. Folding an764// immediate is preferable to folding a load.765if (isa<ConstantSDNode>(U->getOperand(1)))766return false;767768break;769}770}771772// Prevent folding a load if this can implemented with an insert_subreg or773// a move that implicitly zeroes.774if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&775isNullConstant(Root->getOperand(2)) &&776(Root->getOperand(0).isUndef() ||777ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))778return false;779780return true;781}782783// Indicates it is profitable to form an AVX512 masked operation. Returning784// false will favor a masked register-register masked move or vblendm and the785// operation will be selected separately.786bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {787assert(788(N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&789"Unexpected opcode!");790791// If the operation has additional users, the operation will be duplicated.792// Check the use count to prevent that.793// FIXME: Are there cheap opcodes we might want to duplicate?794return N->getOperand(1).hasOneUse();795}796797/// Replace the original chain operand of the call with798/// load's chain operand and move load below the call's chain operand.799static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,800SDValue Call, SDValue OrigChain) {801SmallVector<SDValue, 8> Ops;802SDValue Chain = OrigChain.getOperand(0);803if (Chain.getNode() == Load.getNode())804Ops.push_back(Load.getOperand(0));805else {806assert(Chain.getOpcode() == ISD::TokenFactor &&807"Unexpected chain operand");808for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)809if (Chain.getOperand(i).getNode() == Load.getNode())810Ops.push_back(Load.getOperand(0));811else812Ops.push_back(Chain.getOperand(i));813SDValue NewChain =814CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);815Ops.clear();816Ops.push_back(NewChain);817}818Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());819CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);820CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),821Load.getOperand(1), Load.getOperand(2));822823Ops.clear();824Ops.push_back(SDValue(Load.getNode(), 1));825Ops.append(Call->op_begin() + 1, Call->op_end());826CurDAG->UpdateNodeOperands(Call.getNode(), Ops);827}828829/// Return true if call address is a load and it can be830/// moved below CALLSEQ_START and the chains leading up to the call.831/// Return the CALLSEQ_START by reference as a second output.832/// In the case of a tail call, there isn't a callseq node between the call833/// chain and the load.834static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {835// The transformation is somewhat dangerous if the call's chain was glued to836// the call. After MoveBelowOrigChain the load is moved between the call and837// the chain, this can create a cycle if the load is not folded. So it is838// *really* important that we are sure the load will be folded.839if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())840return false;841auto *LD = dyn_cast<LoadSDNode>(Callee.getNode());842if (!LD ||843!LD->isSimple() ||844LD->getAddressingMode() != ISD::UNINDEXED ||845LD->getExtensionType() != ISD::NON_EXTLOAD)846return false;847848// Now let's find the callseq_start.849while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {850if (!Chain.hasOneUse())851return false;852Chain = Chain.getOperand(0);853}854855if (!Chain.getNumOperands())856return false;857// Since we are not checking for AA here, conservatively abort if the chain858// writes to memory. It's not safe to move the callee (a load) across a store.859if (isa<MemSDNode>(Chain.getNode()) &&860cast<MemSDNode>(Chain.getNode())->writeMem())861return false;862if (Chain.getOperand(0).getNode() == Callee.getNode())863return true;864if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&865Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&866Callee.getValue(1).hasOneUse())867return true;868return false;869}870871static bool isEndbrImm64(uint64_t Imm) {872// There may be some other prefix bytes between 0xF3 and 0x0F1EFA.873// i.g: 0xF3660F1EFA, 0xF3670F1EFA874if ((Imm & 0x00FFFFFF) != 0x0F1EFA)875return false;876877uint8_t OptionalPrefixBytes [] = {0x26, 0x2e, 0x36, 0x3e, 0x64,8780x65, 0x66, 0x67, 0xf0, 0xf2};879int i = 24; // 24bit 0x0F1EFA has matched880while (i < 64) {881uint8_t Byte = (Imm >> i) & 0xFF;882if (Byte == 0xF3)883return true;884if (!llvm::is_contained(OptionalPrefixBytes, Byte))885return false;886i += 8;887}888889return false;890}891892static bool needBWI(MVT VT) {893return (VT == MVT::v32i16 || VT == MVT::v32f16 || VT == MVT::v64i8);894}895896void X86DAGToDAGISel::PreprocessISelDAG() {897bool MadeChange = false;898for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),899E = CurDAG->allnodes_end(); I != E; ) {900SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.901902// This is for CET enhancement.903//904// ENDBR32 and ENDBR64 have specific opcodes:905// ENDBR32: F3 0F 1E FB906// ENDBR64: F3 0F 1E FA907// And we want that attackers won’t find unintended ENDBR32/64908// opcode matches in the binary909// Here’s an example:910// If the compiler had to generate asm for the following code:911// a = 0xF30F1EFA912// it could, for example, generate:913// mov 0xF30F1EFA, dword ptr[a]914// In such a case, the binary would include a gadget that starts915// with a fake ENDBR64 opcode. Therefore, we split such generation916// into multiple operations, let it not shows in the binary917if (N->getOpcode() == ISD::Constant) {918MVT VT = N->getSimpleValueType(0);919int64_t Imm = cast<ConstantSDNode>(N)->getSExtValue();920int32_t EndbrImm = Subtarget->is64Bit() ? 0xF30F1EFA : 0xF30F1EFB;921if (Imm == EndbrImm || isEndbrImm64(Imm)) {922// Check that the cf-protection-branch is enabled.923Metadata *CFProtectionBranch =924MF->getFunction().getParent()->getModuleFlag(925"cf-protection-branch");926if (CFProtectionBranch || IndirectBranchTracking) {927SDLoc dl(N);928SDValue Complement = CurDAG->getConstant(~Imm, dl, VT, false, true);929Complement = CurDAG->getNOT(dl, Complement, VT);930--I;931CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Complement);932++I;933MadeChange = true;934continue;935}936}937}938939// If this is a target specific AND node with no flag usages, turn it back940// into ISD::AND to enable test instruction matching.941if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {942SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),943N->getOperand(0), N->getOperand(1));944--I;945CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);946++I;947MadeChange = true;948continue;949}950951// Convert vector increment or decrement to sub/add with an all-ones952// constant:953// add X, <1, 1...> --> sub X, <-1, -1...>954// sub X, <1, 1...> --> add X, <-1, -1...>955// The all-ones vector constant can be materialized using a pcmpeq956// instruction that is commonly recognized as an idiom (has no register957// dependency), so that's better/smaller than loading a splat 1 constant.958//959// But don't do this if it would inhibit a potentially profitable load960// folding opportunity for the other operand. That only occurs with the961// intersection of:962// (1) The other operand (op0) is load foldable.963// (2) The op is an add (otherwise, we are *creating* an add and can still964// load fold the other op).965// (3) The target has AVX (otherwise, we have a destructive add and can't966// load fold the other op without killing the constant op).967// (4) The constant 1 vector has multiple uses (so it is profitable to load968// into a register anyway).969auto mayPreventLoadFold = [&]() {970return X86::mayFoldLoad(N->getOperand(0), *Subtarget) &&971N->getOpcode() == ISD::ADD && Subtarget->hasAVX() &&972!N->getOperand(1).hasOneUse();973};974if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&975N->getSimpleValueType(0).isVector() && !mayPreventLoadFold()) {976APInt SplatVal;977if (X86::isConstantSplat(N->getOperand(1), SplatVal) &&978SplatVal.isOne()) {979SDLoc DL(N);980981MVT VT = N->getSimpleValueType(0);982unsigned NumElts = VT.getSizeInBits() / 32;983SDValue AllOnes =984CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));985AllOnes = CurDAG->getBitcast(VT, AllOnes);986987unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;988SDValue Res =989CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);990--I;991CurDAG->ReplaceAllUsesWith(N, Res.getNode());992++I;993MadeChange = true;994continue;995}996}997998switch (N->getOpcode()) {999case X86ISD::VBROADCAST: {1000MVT VT = N->getSimpleValueType(0);1001// Emulate v32i16/v64i8 broadcast without BWI.1002if (!Subtarget->hasBWI() && needBWI(VT)) {1003MVT NarrowVT = VT.getHalfNumVectorElementsVT();1004SDLoc dl(N);1005SDValue NarrowBCast =1006CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));1007SDValue Res =1008CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),1009NarrowBCast, CurDAG->getIntPtrConstant(0, dl));1010unsigned Index = NarrowVT.getVectorMinNumElements();1011Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,1012CurDAG->getIntPtrConstant(Index, dl));10131014--I;1015CurDAG->ReplaceAllUsesWith(N, Res.getNode());1016++I;1017MadeChange = true;1018continue;1019}10201021break;1022}1023case X86ISD::VBROADCAST_LOAD: {1024MVT VT = N->getSimpleValueType(0);1025// Emulate v32i16/v64i8 broadcast without BWI.1026if (!Subtarget->hasBWI() && needBWI(VT)) {1027MVT NarrowVT = VT.getHalfNumVectorElementsVT();1028auto *MemNode = cast<MemSDNode>(N);1029SDLoc dl(N);1030SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);1031SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};1032SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(1033X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),1034MemNode->getMemOperand());1035SDValue Res =1036CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),1037NarrowBCast, CurDAG->getIntPtrConstant(0, dl));1038unsigned Index = NarrowVT.getVectorMinNumElements();1039Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,1040CurDAG->getIntPtrConstant(Index, dl));10411042--I;1043SDValue To[] = {Res, NarrowBCast.getValue(1)};1044CurDAG->ReplaceAllUsesWith(N, To);1045++I;1046MadeChange = true;1047continue;1048}10491050break;1051}1052case ISD::LOAD: {1053// If this is a XMM/YMM load of the same lower bits as another YMM/ZMM1054// load, then just extract the lower subvector and avoid the second load.1055auto *Ld = cast<LoadSDNode>(N);1056MVT VT = N->getSimpleValueType(0);1057if (!ISD::isNormalLoad(Ld) || !Ld->isSimple() ||1058!(VT.is128BitVector() || VT.is256BitVector()))1059break;10601061MVT MaxVT = VT;1062SDNode *MaxLd = nullptr;1063SDValue Ptr = Ld->getBasePtr();1064SDValue Chain = Ld->getChain();1065for (SDNode *User : Ptr->uses()) {1066auto *UserLd = dyn_cast<LoadSDNode>(User);1067MVT UserVT = User->getSimpleValueType(0);1068if (User != N && UserLd && ISD::isNormalLoad(User) &&1069UserLd->getBasePtr() == Ptr && UserLd->getChain() == Chain &&1070!User->hasAnyUseOfValue(1) &&1071(UserVT.is256BitVector() || UserVT.is512BitVector()) &&1072UserVT.getSizeInBits() > VT.getSizeInBits() &&1073(!MaxLd || UserVT.getSizeInBits() > MaxVT.getSizeInBits())) {1074MaxLd = User;1075MaxVT = UserVT;1076}1077}1078if (MaxLd) {1079SDLoc dl(N);1080unsigned NumSubElts = VT.getSizeInBits() / MaxVT.getScalarSizeInBits();1081MVT SubVT = MVT::getVectorVT(MaxVT.getScalarType(), NumSubElts);1082SDValue Extract = CurDAG->getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT,1083SDValue(MaxLd, 0),1084CurDAG->getIntPtrConstant(0, dl));1085SDValue Res = CurDAG->getBitcast(VT, Extract);10861087--I;1088SDValue To[] = {Res, SDValue(MaxLd, 1)};1089CurDAG->ReplaceAllUsesWith(N, To);1090++I;1091MadeChange = true;1092continue;1093}1094break;1095}1096case ISD::VSELECT: {1097// Replace VSELECT with non-mask conditions with with BLENDV/VPTERNLOG.1098EVT EleVT = N->getOperand(0).getValueType().getVectorElementType();1099if (EleVT == MVT::i1)1100break;11011102assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");1103assert(N->getValueType(0).getVectorElementType() != MVT::i16 &&1104"We can't replace VSELECT with BLENDV in vXi16!");1105SDValue R;1106if (Subtarget->hasVLX() && CurDAG->ComputeNumSignBits(N->getOperand(0)) ==1107EleVT.getSizeInBits()) {1108R = CurDAG->getNode(X86ISD::VPTERNLOG, SDLoc(N), N->getValueType(0),1109N->getOperand(0), N->getOperand(1), N->getOperand(2),1110CurDAG->getTargetConstant(0xCA, SDLoc(N), MVT::i8));1111} else {1112R = CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),1113N->getOperand(0), N->getOperand(1),1114N->getOperand(2));1115}1116--I;1117CurDAG->ReplaceAllUsesWith(N, R.getNode());1118++I;1119MadeChange = true;1120continue;1121}1122case ISD::FP_ROUND:1123case ISD::STRICT_FP_ROUND:1124case ISD::FP_TO_SINT:1125case ISD::FP_TO_UINT:1126case ISD::STRICT_FP_TO_SINT:1127case ISD::STRICT_FP_TO_UINT: {1128// Replace vector fp_to_s/uint with their X86 specific equivalent so we1129// don't need 2 sets of patterns.1130if (!N->getSimpleValueType(0).isVector())1131break;11321133unsigned NewOpc;1134switch (N->getOpcode()) {1135default: llvm_unreachable("Unexpected opcode!");1136case ISD::FP_ROUND: NewOpc = X86ISD::VFPROUND; break;1137case ISD::STRICT_FP_ROUND: NewOpc = X86ISD::STRICT_VFPROUND; break;1138case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;1139case ISD::FP_TO_SINT: NewOpc = X86ISD::CVTTP2SI; break;1140case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;1141case ISD::FP_TO_UINT: NewOpc = X86ISD::CVTTP2UI; break;1142}1143SDValue Res;1144if (N->isStrictFPOpcode())1145Res =1146CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},1147{N->getOperand(0), N->getOperand(1)});1148else1149Res =1150CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),1151N->getOperand(0));1152--I;1153CurDAG->ReplaceAllUsesWith(N, Res.getNode());1154++I;1155MadeChange = true;1156continue;1157}1158case ISD::SHL:1159case ISD::SRA:1160case ISD::SRL: {1161// Replace vector shifts with their X86 specific equivalent so we don't1162// need 2 sets of patterns.1163if (!N->getValueType(0).isVector())1164break;11651166unsigned NewOpc;1167switch (N->getOpcode()) {1168default: llvm_unreachable("Unexpected opcode!");1169case ISD::SHL: NewOpc = X86ISD::VSHLV; break;1170case ISD::SRA: NewOpc = X86ISD::VSRAV; break;1171case ISD::SRL: NewOpc = X86ISD::VSRLV; break;1172}1173SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),1174N->getOperand(0), N->getOperand(1));1175--I;1176CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);1177++I;1178MadeChange = true;1179continue;1180}1181case ISD::ANY_EXTEND:1182case ISD::ANY_EXTEND_VECTOR_INREG: {1183// Replace vector any extend with the zero extend equivalents so we don't1184// need 2 sets of patterns. Ignore vXi1 extensions.1185if (!N->getValueType(0).isVector())1186break;11871188unsigned NewOpc;1189if (N->getOperand(0).getScalarValueSizeInBits() == 1) {1190assert(N->getOpcode() == ISD::ANY_EXTEND &&1191"Unexpected opcode for mask vector!");1192NewOpc = ISD::SIGN_EXTEND;1193} else {1194NewOpc = N->getOpcode() == ISD::ANY_EXTEND1195? ISD::ZERO_EXTEND1196: ISD::ZERO_EXTEND_VECTOR_INREG;1197}11981199SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),1200N->getOperand(0));1201--I;1202CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);1203++I;1204MadeChange = true;1205continue;1206}1207case ISD::FCEIL:1208case ISD::STRICT_FCEIL:1209case ISD::FFLOOR:1210case ISD::STRICT_FFLOOR:1211case ISD::FTRUNC:1212case ISD::STRICT_FTRUNC:1213case ISD::FROUNDEVEN:1214case ISD::STRICT_FROUNDEVEN:1215case ISD::FNEARBYINT:1216case ISD::STRICT_FNEARBYINT:1217case ISD::FRINT:1218case ISD::STRICT_FRINT: {1219// Replace fp rounding with their X86 specific equivalent so we don't1220// need 2 sets of patterns.1221unsigned Imm;1222switch (N->getOpcode()) {1223default: llvm_unreachable("Unexpected opcode!");1224case ISD::STRICT_FCEIL:1225case ISD::FCEIL: Imm = 0xA; break;1226case ISD::STRICT_FFLOOR:1227case ISD::FFLOOR: Imm = 0x9; break;1228case ISD::STRICT_FTRUNC:1229case ISD::FTRUNC: Imm = 0xB; break;1230case ISD::STRICT_FROUNDEVEN:1231case ISD::FROUNDEVEN: Imm = 0x8; break;1232case ISD::STRICT_FNEARBYINT:1233case ISD::FNEARBYINT: Imm = 0xC; break;1234case ISD::STRICT_FRINT:1235case ISD::FRINT: Imm = 0x4; break;1236}1237SDLoc dl(N);1238bool IsStrict = N->isStrictFPOpcode();1239SDValue Res;1240if (IsStrict)1241Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,1242{N->getValueType(0), MVT::Other},1243{N->getOperand(0), N->getOperand(1),1244CurDAG->getTargetConstant(Imm, dl, MVT::i32)});1245else1246Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),1247N->getOperand(0),1248CurDAG->getTargetConstant(Imm, dl, MVT::i32));1249--I;1250CurDAG->ReplaceAllUsesWith(N, Res.getNode());1251++I;1252MadeChange = true;1253continue;1254}1255case X86ISD::FANDN:1256case X86ISD::FAND:1257case X86ISD::FOR:1258case X86ISD::FXOR: {1259// Widen scalar fp logic ops to vector to reduce isel patterns.1260// FIXME: Can we do this during lowering/combine.1261MVT VT = N->getSimpleValueType(0);1262if (VT.isVector() || VT == MVT::f128)1263break;12641265MVT VecVT = VT == MVT::f64 ? MVT::v2f641266: VT == MVT::f32 ? MVT::v4f321267: MVT::v8f16;12681269SDLoc dl(N);1270SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,1271N->getOperand(0));1272SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,1273N->getOperand(1));12741275SDValue Res;1276if (Subtarget->hasSSE2()) {1277EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();1278Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);1279Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);1280unsigned Opc;1281switch (N->getOpcode()) {1282default: llvm_unreachable("Unexpected opcode!");1283case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;1284case X86ISD::FAND: Opc = ISD::AND; break;1285case X86ISD::FOR: Opc = ISD::OR; break;1286case X86ISD::FXOR: Opc = ISD::XOR; break;1287}1288Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);1289Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);1290} else {1291Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);1292}1293Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,1294CurDAG->getIntPtrConstant(0, dl));1295--I;1296CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);1297++I;1298MadeChange = true;1299continue;1300}1301}13021303if (OptLevel != CodeGenOptLevel::None &&1304// Only do this when the target can fold the load into the call or1305// jmp.1306!Subtarget->useIndirectThunkCalls() &&1307((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||1308(N->getOpcode() == X86ISD::TC_RETURN &&1309(Subtarget->is64Bit() ||1310!getTargetMachine().isPositionIndependent())))) {1311/// Also try moving call address load from outside callseq_start to just1312/// before the call to allow it to be folded.1313///1314/// [Load chain]1315/// ^1316/// |1317/// [Load]1318/// ^ ^1319/// | |1320/// / \--1321/// / |1322///[CALLSEQ_START] |1323/// ^ |1324/// | |1325/// [LOAD/C2Reg] |1326/// | |1327/// \ /1328/// \ /1329/// [CALL]1330bool HasCallSeq = N->getOpcode() == X86ISD::CALL;1331SDValue Chain = N->getOperand(0);1332SDValue Load = N->getOperand(1);1333if (!isCalleeLoad(Load, Chain, HasCallSeq))1334continue;1335moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);1336++NumLoadMoved;1337MadeChange = true;1338continue;1339}13401341// Lower fpround and fpextend nodes that target the FP stack to be store and1342// load to the stack. This is a gross hack. We would like to simply mark1343// these as being illegal, but when we do that, legalize produces these when1344// it expands calls, then expands these in the same legalize pass. We would1345// like dag combine to be able to hack on these between the call expansion1346// and the node legalization. As such this pass basically does "really1347// late" legalization of these inline with the X86 isel pass.1348// FIXME: This should only happen when not compiled with -O0.1349switch (N->getOpcode()) {1350default: continue;1351case ISD::FP_ROUND:1352case ISD::FP_EXTEND:1353{1354MVT SrcVT = N->getOperand(0).getSimpleValueType();1355MVT DstVT = N->getSimpleValueType(0);13561357// If any of the sources are vectors, no fp stack involved.1358if (SrcVT.isVector() || DstVT.isVector())1359continue;13601361// If the source and destination are SSE registers, then this is a legal1362// conversion that should not be lowered.1363const X86TargetLowering *X86Lowering =1364static_cast<const X86TargetLowering *>(TLI);1365bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);1366bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);1367if (SrcIsSSE && DstIsSSE)1368continue;13691370if (!SrcIsSSE && !DstIsSSE) {1371// If this is an FPStack extension, it is a noop.1372if (N->getOpcode() == ISD::FP_EXTEND)1373continue;1374// If this is a value-preserving FPStack truncation, it is a noop.1375if (N->getConstantOperandVal(1))1376continue;1377}13781379// Here we could have an FP stack truncation or an FPStack <-> SSE convert.1380// FPStack has extload and truncstore. SSE can fold direct loads into other1381// operations. Based on this, decide what we want to do.1382MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;1383SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);1384int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();1385MachinePointerInfo MPI =1386MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);1387SDLoc dl(N);13881389// FIXME: optimize the case where the src/dest is a load or store?13901391SDValue Store = CurDAG->getTruncStore(1392CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);1393SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,1394MemTmp, MPI, MemVT);13951396// We're about to replace all uses of the FP_ROUND/FP_EXTEND with the1397// extload we created. This will cause general havok on the dag because1398// anything below the conversion could be folded into other existing nodes.1399// To avoid invalidating 'I', back it up to the convert node.1400--I;1401CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);1402break;1403}14041405//The sequence of events for lowering STRICT_FP versions of these nodes requires1406//dealing with the chain differently, as there is already a preexisting chain.1407case ISD::STRICT_FP_ROUND:1408case ISD::STRICT_FP_EXTEND:1409{1410MVT SrcVT = N->getOperand(1).getSimpleValueType();1411MVT DstVT = N->getSimpleValueType(0);14121413// If any of the sources are vectors, no fp stack involved.1414if (SrcVT.isVector() || DstVT.isVector())1415continue;14161417// If the source and destination are SSE registers, then this is a legal1418// conversion that should not be lowered.1419const X86TargetLowering *X86Lowering =1420static_cast<const X86TargetLowering *>(TLI);1421bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);1422bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);1423if (SrcIsSSE && DstIsSSE)1424continue;14251426if (!SrcIsSSE && !DstIsSSE) {1427// If this is an FPStack extension, it is a noop.1428if (N->getOpcode() == ISD::STRICT_FP_EXTEND)1429continue;1430// If this is a value-preserving FPStack truncation, it is a noop.1431if (N->getConstantOperandVal(2))1432continue;1433}14341435// Here we could have an FP stack truncation or an FPStack <-> SSE convert.1436// FPStack has extload and truncstore. SSE can fold direct loads into other1437// operations. Based on this, decide what we want to do.1438MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;1439SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);1440int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();1441MachinePointerInfo MPI =1442MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);1443SDLoc dl(N);14441445// FIXME: optimize the case where the src/dest is a load or store?14461447//Since the operation is StrictFP, use the preexisting chain.1448SDValue Store, Result;1449if (!SrcIsSSE) {1450SDVTList VTs = CurDAG->getVTList(MVT::Other);1451SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};1452Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,1453MPI, /*Align*/ std::nullopt,1454MachineMemOperand::MOStore);1455if (N->getFlags().hasNoFPExcept()) {1456SDNodeFlags Flags = Store->getFlags();1457Flags.setNoFPExcept(true);1458Store->setFlags(Flags);1459}1460} else {1461assert(SrcVT == MemVT && "Unexpected VT!");1462Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,1463MPI);1464}14651466if (!DstIsSSE) {1467SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);1468SDValue Ops[] = {Store, MemTmp};1469Result = CurDAG->getMemIntrinsicNode(1470X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,1471/*Align*/ std::nullopt, MachineMemOperand::MOLoad);1472if (N->getFlags().hasNoFPExcept()) {1473SDNodeFlags Flags = Result->getFlags();1474Flags.setNoFPExcept(true);1475Result->setFlags(Flags);1476}1477} else {1478assert(DstVT == MemVT && "Unexpected VT!");1479Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);1480}14811482// We're about to replace all uses of the FP_ROUND/FP_EXTEND with the1483// extload we created. This will cause general havok on the dag because1484// anything below the conversion could be folded into other existing nodes.1485// To avoid invalidating 'I', back it up to the convert node.1486--I;1487CurDAG->ReplaceAllUsesWith(N, Result.getNode());1488break;1489}1490}149114921493// Now that we did that, the node is dead. Increment the iterator to the1494// next node to process, then delete N.1495++I;1496MadeChange = true;1497}14981499// Remove any dead nodes that may have been left behind.1500if (MadeChange)1501CurDAG->RemoveDeadNodes();1502}15031504// Look for a redundant movzx/movsx that can occur after an 8-bit divrem.1505bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {1506unsigned Opc = N->getMachineOpcode();1507if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&1508Opc != X86::MOVSX64rr8)1509return false;15101511SDValue N0 = N->getOperand(0);15121513// We need to be extracting the lower bit of an extend.1514if (!N0.isMachineOpcode() ||1515N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||1516N0.getConstantOperandVal(1) != X86::sub_8bit)1517return false;15181519// We're looking for either a movsx or movzx to match the original opcode.1520unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX1521: X86::MOVSX32rr8_NOREX;1522SDValue N00 = N0.getOperand(0);1523if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)1524return false;15251526if (Opc == X86::MOVSX64rr8) {1527// If we had a sign extend from 8 to 64 bits. We still need to go from 321528// to 64.1529MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),1530MVT::i64, N00);1531ReplaceUses(N, Extend);1532} else {1533// Ok we can drop this extend and just use the original extend.1534ReplaceUses(N, N00.getNode());1535}15361537return true;1538}15391540void X86DAGToDAGISel::PostprocessISelDAG() {1541// Skip peepholes at -O0.1542if (TM.getOptLevel() == CodeGenOptLevel::None)1543return;15441545SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();15461547bool MadeChange = false;1548while (Position != CurDAG->allnodes_begin()) {1549SDNode *N = &*--Position;1550// Skip dead nodes and any non-machine opcodes.1551if (N->use_empty() || !N->isMachineOpcode())1552continue;15531554if (tryOptimizeRem8Extend(N)) {1555MadeChange = true;1556continue;1557}15581559unsigned Opc = N->getMachineOpcode();1560switch (Opc) {1561default:1562continue;1563// ANDrr/rm + TESTrr+ -> TESTrr/TESTmr1564case X86::TEST8rr:1565case X86::TEST16rr:1566case X86::TEST32rr:1567case X86::TEST64rr:1568// ANDrr/rm + CTESTrr -> CTESTrr/CTESTmr1569case X86::CTEST8rr:1570case X86::CTEST16rr:1571case X86::CTEST32rr:1572case X86::CTEST64rr: {1573auto &Op0 = N->getOperand(0);1574if (Op0 != N->getOperand(1) || !Op0->hasNUsesOfValue(2, Op0.getResNo()) ||1575!Op0.isMachineOpcode())1576continue;1577SDValue And = N->getOperand(0);1578#define CASE_ND(OP) \1579case X86::OP: \1580case X86::OP##_ND:1581switch (And.getMachineOpcode()) {1582default:1583continue;1584CASE_ND(AND8rr)1585CASE_ND(AND16rr)1586CASE_ND(AND32rr)1587CASE_ND(AND64rr) {1588if (And->hasAnyUseOfValue(1))1589continue;1590SmallVector<SDValue> Ops(N->op_values());1591Ops[0] = And.getOperand(0);1592Ops[1] = And.getOperand(1);1593MachineSDNode *Test =1594CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i32, Ops);1595ReplaceUses(N, Test);1596MadeChange = true;1597continue;1598}1599CASE_ND(AND8rm)1600CASE_ND(AND16rm)1601CASE_ND(AND32rm)1602CASE_ND(AND64rm) {1603if (And->hasAnyUseOfValue(1))1604continue;1605unsigned NewOpc;1606bool IsCTESTCC = X86::isCTESTCC(Opc);1607#define FROM_TO(A, B) \1608CASE_ND(A) NewOpc = IsCTESTCC ? X86::C##B : X86::B; \1609break;1610switch (And.getMachineOpcode()) {1611FROM_TO(AND8rm, TEST8mr);1612FROM_TO(AND16rm, TEST16mr);1613FROM_TO(AND32rm, TEST32mr);1614FROM_TO(AND64rm, TEST64mr);1615}1616#undef FROM_TO1617#undef CASE_ND1618// Need to swap the memory and register operand.1619SmallVector<SDValue> Ops = {And.getOperand(1), And.getOperand(2),1620And.getOperand(3), And.getOperand(4),1621And.getOperand(5), And.getOperand(0)};1622// CC, Cflags.1623if (IsCTESTCC) {1624Ops.push_back(N->getOperand(2));1625Ops.push_back(N->getOperand(3));1626}1627// Chain of memory load1628Ops.push_back(And.getOperand(6));1629// Glue1630if (IsCTESTCC)1631Ops.push_back(N->getOperand(4));16321633MachineSDNode *Test = CurDAG->getMachineNode(1634NewOpc, SDLoc(N), MVT::i32, MVT::Other, Ops);1635CurDAG->setNodeMemRefs(1636Test, cast<MachineSDNode>(And.getNode())->memoperands());1637ReplaceUses(And.getValue(2), SDValue(Test, 1));1638ReplaceUses(SDValue(N, 0), SDValue(Test, 0));1639MadeChange = true;1640continue;1641}1642}1643}1644// Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is1645// used. We're doing this late so we can prefer to fold the AND into masked1646// comparisons. Doing that can be better for the live range of the mask1647// register.1648case X86::KORTESTBrr:1649case X86::KORTESTWrr:1650case X86::KORTESTDrr:1651case X86::KORTESTQrr: {1652SDValue Op0 = N->getOperand(0);1653if (Op0 != N->getOperand(1) || !N->isOnlyUserOf(Op0.getNode()) ||1654!Op0.isMachineOpcode() || !onlyUsesZeroFlag(SDValue(N, 0)))1655continue;1656#define CASE(A) \1657case X86::A: \1658break;1659switch (Op0.getMachineOpcode()) {1660default:1661continue;1662CASE(KANDBrr)1663CASE(KANDWrr)1664CASE(KANDDrr)1665CASE(KANDQrr)1666}1667unsigned NewOpc;1668#define FROM_TO(A, B) \1669case X86::A: \1670NewOpc = X86::B; \1671break;1672switch (Opc) {1673FROM_TO(KORTESTBrr, KTESTBrr)1674FROM_TO(KORTESTWrr, KTESTWrr)1675FROM_TO(KORTESTDrr, KTESTDrr)1676FROM_TO(KORTESTQrr, KTESTQrr)1677}1678// KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other1679// KAND instructions and KTEST use the same ISA feature.1680if (NewOpc == X86::KTESTWrr && !Subtarget->hasDQI())1681continue;1682#undef FROM_TO1683MachineSDNode *KTest = CurDAG->getMachineNode(1684NewOpc, SDLoc(N), MVT::i32, Op0.getOperand(0), Op0.getOperand(1));1685ReplaceUses(N, KTest);1686MadeChange = true;1687continue;1688}1689// Attempt to remove vectors moves that were inserted to zero upper bits.1690case TargetOpcode::SUBREG_TO_REG: {1691unsigned SubRegIdx = N->getConstantOperandVal(2);1692if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)1693continue;16941695SDValue Move = N->getOperand(1);1696if (!Move.isMachineOpcode())1697continue;16981699// Make sure its one of the move opcodes we recognize.1700switch (Move.getMachineOpcode()) {1701default:1702continue;1703CASE(VMOVAPDrr) CASE(VMOVUPDrr)1704CASE(VMOVAPSrr) CASE(VMOVUPSrr)1705CASE(VMOVDQArr) CASE(VMOVDQUrr)1706CASE(VMOVAPDYrr) CASE(VMOVUPDYrr)1707CASE(VMOVAPSYrr) CASE(VMOVUPSYrr)1708CASE(VMOVDQAYrr) CASE(VMOVDQUYrr)1709CASE(VMOVAPDZ128rr) CASE(VMOVUPDZ128rr)1710CASE(VMOVAPSZ128rr) CASE(VMOVUPSZ128rr)1711CASE(VMOVDQA32Z128rr) CASE(VMOVDQU32Z128rr)1712CASE(VMOVDQA64Z128rr) CASE(VMOVDQU64Z128rr)1713CASE(VMOVAPDZ256rr) CASE(VMOVUPDZ256rr)1714CASE(VMOVAPSZ256rr) CASE(VMOVUPSZ256rr)1715CASE(VMOVDQA32Z256rr) CASE(VMOVDQU32Z256rr)1716CASE(VMOVDQA64Z256rr) CASE(VMOVDQU64Z256rr)1717}1718#undef CASE17191720SDValue In = Move.getOperand(0);1721if (!In.isMachineOpcode() ||1722In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)1723continue;17241725// Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers1726// the SHA instructions which use a legacy encoding.1727uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;1728if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&1729(TSFlags & X86II::EncodingMask) != X86II::EVEX &&1730(TSFlags & X86II::EncodingMask) != X86II::XOP)1731continue;17321733// Producing instruction is another vector instruction. We can drop the1734// move.1735CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));1736MadeChange = true;1737}1738}1739}17401741if (MadeChange)1742CurDAG->RemoveDeadNodes();1743}174417451746/// Emit any code that needs to be executed only in the main function.1747void X86DAGToDAGISel::emitSpecialCodeForMain() {1748if (Subtarget->isTargetCygMing()) {1749TargetLowering::ArgListTy Args;1750auto &DL = CurDAG->getDataLayout();17511752TargetLowering::CallLoweringInfo CLI(*CurDAG);1753CLI.setChain(CurDAG->getRoot())1754.setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),1755CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),1756std::move(Args));1757const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();1758std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);1759CurDAG->setRoot(Result.second);1760}1761}17621763void X86DAGToDAGISel::emitFunctionEntryCode() {1764// If this is main, emit special code for main.1765const Function &F = MF->getFunction();1766if (F.hasExternalLinkage() && F.getName() == "main")1767emitSpecialCodeForMain();1768}17691770static bool isDispSafeForFrameIndex(int64_t Val) {1771// On 64-bit platforms, we can run into an issue where a frame index1772// includes a displacement that, when added to the explicit displacement,1773// will overflow the displacement field. Assuming that the frame index1774// displacement fits into a 31-bit integer (which is only slightly more1775// aggressive than the current fundamental assumption that it fits into1776// a 32-bit integer), a 31-bit disp should always be safe.1777return isInt<31>(Val);1778}17791780bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,1781X86ISelAddressMode &AM) {1782// We may have already matched a displacement and the caller just added the1783// symbolic displacement. So we still need to do the checks even if Offset1784// is zero.17851786int64_t Val = AM.Disp + Offset;17871788// Cannot combine ExternalSymbol displacements with integer offsets.1789if (Val != 0 && (AM.ES || AM.MCSym))1790return true;17911792CodeModel::Model M = TM.getCodeModel();1793if (Subtarget->is64Bit()) {1794if (Val != 0 &&1795!X86::isOffsetSuitableForCodeModel(Val, M,1796AM.hasSymbolicDisplacement()))1797return true;1798// In addition to the checks required for a register base, check that1799// we do not try to use an unsafe Disp with a frame index.1800if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&1801!isDispSafeForFrameIndex(Val))1802return true;1803// In ILP32 (x32) mode, pointers are 32 bits and need to be zero-extended to1804// 64 bits. Instructions with 32-bit register addresses perform this zero1805// extension for us and we can safely ignore the high bits of Offset.1806// Instructions with only a 32-bit immediate address do not, though: they1807// sign extend instead. This means only address the low 2GB of address space1808// is directly addressable, we need indirect addressing for the high 2GB of1809// address space.1810// TODO: Some of the earlier checks may be relaxed for ILP32 mode as the1811// implicit zero extension of instructions would cover up any problem.1812// However, we have asserts elsewhere that get triggered if we do, so keep1813// the checks for now.1814// TODO: We would actually be able to accept these, as well as the same1815// addresses in LP64 mode, by adding the EIZ pseudo-register as an operand1816// to get an address size override to be emitted. However, this1817// pseudo-register is not part of any register class and therefore causes1818// MIR verification to fail.1819if (Subtarget->isTarget64BitILP32() && !isUInt<31>(Val) &&1820!AM.hasBaseOrIndexReg())1821return true;1822}1823AM.Disp = Val;1824return false;1825}18261827bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,1828bool AllowSegmentRegForX32) {1829SDValue Address = N->getOperand(1);18301831// load gs:0 -> GS segment register.1832// load fs:0 -> FS segment register.1833//1834// This optimization is generally valid because the GNU TLS model defines that1835// gs:0 (or fs:0 on X86-64) contains its own address. However, for X86-64 mode1836// with 32-bit registers, as we get in ILP32 mode, those registers are first1837// zero-extended to 64 bits and then added it to the base address, which gives1838// unwanted results when the register holds a negative value.1839// For more information see http://people.redhat.com/drepper/tls.pdf1840if (isNullConstant(Address) && AM.Segment.getNode() == nullptr &&1841!IndirectTlsSegRefs &&1842(Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||1843Subtarget->isTargetFuchsia())) {1844if (Subtarget->isTarget64BitILP32() && !AllowSegmentRegForX32)1845return true;1846switch (N->getPointerInfo().getAddrSpace()) {1847case X86AS::GS:1848AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);1849return false;1850case X86AS::FS:1851AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);1852return false;1853// Address space X86AS::SS is not handled here, because it is not used to1854// address TLS areas.1855}1856}18571858return true;1859}18601861/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing1862/// mode. These wrap things that will resolve down into a symbol reference.1863/// If no match is possible, this returns true, otherwise it returns false.1864bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {1865// If the addressing mode already has a symbol as the displacement, we can1866// never match another symbol.1867if (AM.hasSymbolicDisplacement())1868return true;18691870bool IsRIPRelTLS = false;1871bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;1872if (IsRIPRel) {1873SDValue Val = N.getOperand(0);1874if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)1875IsRIPRelTLS = true;1876}18771878// We can't use an addressing mode in the 64-bit large code model.1879// Global TLS addressing is an exception. In the medium code model,1880// we use can use a mode when RIP wrappers are present.1881// That signifies access to globals that are known to be "near",1882// such as the GOT itself.1883CodeModel::Model M = TM.getCodeModel();1884if (Subtarget->is64Bit() && M == CodeModel::Large && !IsRIPRelTLS)1885return true;18861887// Base and index reg must be 0 in order to use %rip as base.1888if (IsRIPRel && AM.hasBaseOrIndexReg())1889return true;18901891// Make a local copy in case we can't do this fold.1892X86ISelAddressMode Backup = AM;18931894int64_t Offset = 0;1895SDValue N0 = N.getOperand(0);1896if (auto *G = dyn_cast<GlobalAddressSDNode>(N0)) {1897AM.GV = G->getGlobal();1898AM.SymbolFlags = G->getTargetFlags();1899Offset = G->getOffset();1900} else if (auto *CP = dyn_cast<ConstantPoolSDNode>(N0)) {1901AM.CP = CP->getConstVal();1902AM.Alignment = CP->getAlign();1903AM.SymbolFlags = CP->getTargetFlags();1904Offset = CP->getOffset();1905} else if (auto *S = dyn_cast<ExternalSymbolSDNode>(N0)) {1906AM.ES = S->getSymbol();1907AM.SymbolFlags = S->getTargetFlags();1908} else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {1909AM.MCSym = S->getMCSymbol();1910} else if (auto *J = dyn_cast<JumpTableSDNode>(N0)) {1911AM.JT = J->getIndex();1912AM.SymbolFlags = J->getTargetFlags();1913} else if (auto *BA = dyn_cast<BlockAddressSDNode>(N0)) {1914AM.BlockAddr = BA->getBlockAddress();1915AM.SymbolFlags = BA->getTargetFlags();1916Offset = BA->getOffset();1917} else1918llvm_unreachable("Unhandled symbol reference node.");19191920// Can't use an addressing mode with large globals.1921if (Subtarget->is64Bit() && !IsRIPRel && AM.GV &&1922TM.isLargeGlobalValue(AM.GV)) {1923AM = Backup;1924return true;1925}19261927if (foldOffsetIntoAddress(Offset, AM)) {1928AM = Backup;1929return true;1930}19311932if (IsRIPRel)1933AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));19341935// Commit the changes now that we know this fold is safe.1936return false;1937}19381939/// Add the specified node to the specified addressing mode, returning true if1940/// it cannot be done. This just pattern matches for the addressing mode.1941bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {1942if (matchAddressRecursively(N, AM, 0))1943return true;19441945// Post-processing: Make a second attempt to fold a load, if we now know1946// that there will not be any other register. This is only performed for1947// 64-bit ILP32 mode since 32-bit mode and 64-bit LP64 mode will have folded1948// any foldable load the first time.1949if (Subtarget->isTarget64BitILP32() &&1950AM.BaseType == X86ISelAddressMode::RegBase &&1951AM.Base_Reg.getNode() != nullptr && AM.IndexReg.getNode() == nullptr) {1952SDValue Save_Base_Reg = AM.Base_Reg;1953if (auto *LoadN = dyn_cast<LoadSDNode>(Save_Base_Reg)) {1954AM.Base_Reg = SDValue();1955if (matchLoadInAddress(LoadN, AM, /*AllowSegmentRegForX32=*/true))1956AM.Base_Reg = Save_Base_Reg;1957}1958}19591960// Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has1961// a smaller encoding and avoids a scaled-index.1962if (AM.Scale == 2 &&1963AM.BaseType == X86ISelAddressMode::RegBase &&1964AM.Base_Reg.getNode() == nullptr) {1965AM.Base_Reg = AM.IndexReg;1966AM.Scale = 1;1967}19681969// Post-processing: Convert foo to foo(%rip), even in non-PIC mode,1970// because it has a smaller encoding.1971if (TM.getCodeModel() != CodeModel::Large &&1972(!AM.GV || !TM.isLargeGlobalValue(AM.GV)) && Subtarget->is64Bit() &&1973AM.Scale == 1 && AM.BaseType == X86ISelAddressMode::RegBase &&1974AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr &&1975AM.SymbolFlags == X86II::MO_NO_FLAG && AM.hasSymbolicDisplacement()) {1976AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);1977}19781979return false;1980}19811982bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,1983unsigned Depth) {1984// Add an artificial use to this node so that we can keep track of1985// it if it gets CSE'd with a different node.1986HandleSDNode Handle(N);19871988X86ISelAddressMode Backup = AM;1989if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&1990!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))1991return false;1992AM = Backup;19931994// Try again after commutating the operands.1995if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM,1996Depth + 1) &&1997!matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1))1998return false;1999AM = Backup;20002001// If we couldn't fold both operands into the address at the same time,2002// see if we can just put each operand into a register and fold at least2003// the add.2004if (AM.BaseType == X86ISelAddressMode::RegBase &&2005!AM.Base_Reg.getNode() &&2006!AM.IndexReg.getNode()) {2007N = Handle.getValue();2008AM.Base_Reg = N.getOperand(0);2009AM.IndexReg = N.getOperand(1);2010AM.Scale = 1;2011return false;2012}2013N = Handle.getValue();2014return true;2015}20162017// Insert a node into the DAG at least before the Pos node's position. This2018// will reposition the node as needed, and will assign it a node ID that is <=2019// the Pos node's ID. Note that this does *not* preserve the uniqueness of node2020// IDs! The selection DAG must no longer depend on their uniqueness when this2021// is used.2022static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {2023if (N->getNodeId() == -1 ||2024(SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >2025SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {2026DAG.RepositionNode(Pos->getIterator(), N.getNode());2027// Mark Node as invalid for pruning as after this it may be a successor to a2028// selected node but otherwise be in the same position of Pos.2029// Conservatively mark it with the same -abs(Id) to assure node id2030// invariant is preserved.2031N->setNodeId(Pos->getNodeId());2032SelectionDAGISel::InvalidateNodeId(N.getNode());2033}2034}20352036// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if2037// safe. This allows us to convert the shift and and into an h-register2038// extract and a scaled index. Returns false if the simplification is2039// performed.2040static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,2041uint64_t Mask,2042SDValue Shift, SDValue X,2043X86ISelAddressMode &AM) {2044if (Shift.getOpcode() != ISD::SRL ||2045!isa<ConstantSDNode>(Shift.getOperand(1)) ||2046!Shift.hasOneUse())2047return true;20482049int ScaleLog = 8 - Shift.getConstantOperandVal(1);2050if (ScaleLog <= 0 || ScaleLog >= 4 ||2051Mask != (0xffu << ScaleLog))2052return true;20532054MVT XVT = X.getSimpleValueType();2055MVT VT = N.getSimpleValueType();2056SDLoc DL(N);2057SDValue Eight = DAG.getConstant(8, DL, MVT::i8);2058SDValue NewMask = DAG.getConstant(0xff, DL, XVT);2059SDValue Srl = DAG.getNode(ISD::SRL, DL, XVT, X, Eight);2060SDValue And = DAG.getNode(ISD::AND, DL, XVT, Srl, NewMask);2061SDValue Ext = DAG.getZExtOrTrunc(And, DL, VT);2062SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);2063SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Ext, ShlCount);20642065// Insert the new nodes into the topological ordering. We must do this in2066// a valid topological ordering as nothing is going to go back and re-sort2067// these nodes. We continually insert before 'N' in sequence as this is2068// essentially a pre-flattened and pre-sorted sequence of nodes. There is no2069// hierarchy left to express.2070insertDAGNode(DAG, N, Eight);2071insertDAGNode(DAG, N, NewMask);2072insertDAGNode(DAG, N, Srl);2073insertDAGNode(DAG, N, And);2074insertDAGNode(DAG, N, Ext);2075insertDAGNode(DAG, N, ShlCount);2076insertDAGNode(DAG, N, Shl);2077DAG.ReplaceAllUsesWith(N, Shl);2078DAG.RemoveDeadNode(N.getNode());2079AM.IndexReg = Ext;2080AM.Scale = (1 << ScaleLog);2081return false;2082}20832084// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this2085// allows us to fold the shift into this addressing mode. Returns false if the2086// transform succeeded.2087static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,2088X86ISelAddressMode &AM) {2089SDValue Shift = N.getOperand(0);20902091// Use a signed mask so that shifting right will insert sign bits. These2092// bits will be removed when we shift the result left so it doesn't matter2093// what we use. This might allow a smaller immediate encoding.2094int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();20952096// If we have an any_extend feeding the AND, look through it to see if there2097// is a shift behind it. But only if the AND doesn't use the extended bits.2098// FIXME: Generalize this to other ANY_EXTEND than i32 to i64?2099bool FoundAnyExtend = false;2100if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&2101Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&2102isUInt<32>(Mask)) {2103FoundAnyExtend = true;2104Shift = Shift.getOperand(0);2105}21062107if (Shift.getOpcode() != ISD::SHL ||2108!isa<ConstantSDNode>(Shift.getOperand(1)))2109return true;21102111SDValue X = Shift.getOperand(0);21122113// Not likely to be profitable if either the AND or SHIFT node has more2114// than one use (unless all uses are for address computation). Besides,2115// isel mechanism requires their node ids to be reused.2116if (!N.hasOneUse() || !Shift.hasOneUse())2117return true;21182119// Verify that the shift amount is something we can fold.2120unsigned ShiftAmt = Shift.getConstantOperandVal(1);2121if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)2122return true;21232124MVT VT = N.getSimpleValueType();2125SDLoc DL(N);2126if (FoundAnyExtend) {2127SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);2128insertDAGNode(DAG, N, NewX);2129X = NewX;2130}21312132SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);2133SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);2134SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));21352136// Insert the new nodes into the topological ordering. We must do this in2137// a valid topological ordering as nothing is going to go back and re-sort2138// these nodes. We continually insert before 'N' in sequence as this is2139// essentially a pre-flattened and pre-sorted sequence of nodes. There is no2140// hierarchy left to express.2141insertDAGNode(DAG, N, NewMask);2142insertDAGNode(DAG, N, NewAnd);2143insertDAGNode(DAG, N, NewShift);2144DAG.ReplaceAllUsesWith(N, NewShift);2145DAG.RemoveDeadNode(N.getNode());21462147AM.Scale = 1 << ShiftAmt;2148AM.IndexReg = NewAnd;2149return false;2150}21512152// Implement some heroics to detect shifts of masked values where the mask can2153// be replaced by extending the shift and undoing that in the addressing mode2154// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and2155// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in2156// the addressing mode. This results in code such as:2157//2158// int f(short *y, int *lookup_table) {2159// ...2160// return *y + lookup_table[*y >> 11];2161// }2162//2163// Turning into:2164// movzwl (%rdi), %eax2165// movl %eax, %ecx2166// shrl $11, %ecx2167// addl (%rsi,%rcx,4), %eax2168//2169// Instead of:2170// movzwl (%rdi), %eax2171// movl %eax, %ecx2172// shrl $9, %ecx2173// andl $124, %rcx2174// addl (%rsi,%rcx), %eax2175//2176// Note that this function assumes the mask is provided as a mask *after* the2177// value is shifted. The input chain may or may not match that, but computing2178// such a mask is trivial.2179static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,2180uint64_t Mask,2181SDValue Shift, SDValue X,2182X86ISelAddressMode &AM) {2183if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||2184!isa<ConstantSDNode>(Shift.getOperand(1)))2185return true;21862187// We need to ensure that mask is a continuous run of bits.2188unsigned MaskIdx, MaskLen;2189if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))2190return true;2191unsigned MaskLZ = 64 - (MaskIdx + MaskLen);21922193unsigned ShiftAmt = Shift.getConstantOperandVal(1);21942195// The amount of shift we're trying to fit into the addressing mode is taken2196// from the shifted mask index (number of trailing zeros of the mask).2197unsigned AMShiftAmt = MaskIdx;21982199// There is nothing we can do here unless the mask is removing some bits.2200// Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.2201if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;22022203// Scale the leading zero count down based on the actual size of the value.2204// Also scale it down based on the size of the shift.2205unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;2206if (MaskLZ < ScaleDown)2207return true;2208MaskLZ -= ScaleDown;22092210// The final check is to ensure that any masked out high bits of X are2211// already known to be zero. Otherwise, the mask has a semantic impact2212// other than masking out a couple of low bits. Unfortunately, because of2213// the mask, zero extensions will be removed from operands in some cases.2214// This code works extra hard to look through extensions because we can2215// replace them with zero extensions cheaply if necessary.2216bool ReplacingAnyExtend = false;2217if (X.getOpcode() == ISD::ANY_EXTEND) {2218unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -2219X.getOperand(0).getSimpleValueType().getSizeInBits();2220// Assume that we'll replace the any-extend with a zero-extend, and2221// narrow the search to the extended value.2222X = X.getOperand(0);2223MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;2224ReplacingAnyExtend = true;2225}2226APInt MaskedHighBits =2227APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);2228if (!DAG.MaskedValueIsZero(X, MaskedHighBits))2229return true;22302231// We've identified a pattern that can be transformed into a single shift2232// and an addressing mode. Make it so.2233MVT VT = N.getSimpleValueType();2234if (ReplacingAnyExtend) {2235assert(X.getValueType() != VT);2236// We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.2237SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);2238insertDAGNode(DAG, N, NewX);2239X = NewX;2240}22412242MVT XVT = X.getSimpleValueType();2243SDLoc DL(N);2244SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);2245SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);2246SDValue NewExt = DAG.getZExtOrTrunc(NewSRL, DL, VT);2247SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);2248SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);22492250// Insert the new nodes into the topological ordering. We must do this in2251// a valid topological ordering as nothing is going to go back and re-sort2252// these nodes. We continually insert before 'N' in sequence as this is2253// essentially a pre-flattened and pre-sorted sequence of nodes. There is no2254// hierarchy left to express.2255insertDAGNode(DAG, N, NewSRLAmt);2256insertDAGNode(DAG, N, NewSRL);2257insertDAGNode(DAG, N, NewExt);2258insertDAGNode(DAG, N, NewSHLAmt);2259insertDAGNode(DAG, N, NewSHL);2260DAG.ReplaceAllUsesWith(N, NewSHL);2261DAG.RemoveDeadNode(N.getNode());22622263AM.Scale = 1 << AMShiftAmt;2264AM.IndexReg = NewExt;2265return false;2266}22672268// Transform "(X >> SHIFT) & (MASK << C1)" to2269// "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be2270// matched to a BEXTR later. Returns false if the simplification is performed.2271static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,2272uint64_t Mask,2273SDValue Shift, SDValue X,2274X86ISelAddressMode &AM,2275const X86Subtarget &Subtarget) {2276if (Shift.getOpcode() != ISD::SRL ||2277!isa<ConstantSDNode>(Shift.getOperand(1)) ||2278!Shift.hasOneUse() || !N.hasOneUse())2279return true;22802281// Only do this if BEXTR will be matched by matchBEXTRFromAndImm.2282if (!Subtarget.hasTBM() &&2283!(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))2284return true;22852286// We need to ensure that mask is a continuous run of bits.2287unsigned MaskIdx, MaskLen;2288if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))2289return true;22902291unsigned ShiftAmt = Shift.getConstantOperandVal(1);22922293// The amount of shift we're trying to fit into the addressing mode is taken2294// from the shifted mask index (number of trailing zeros of the mask).2295unsigned AMShiftAmt = MaskIdx;22962297// There is nothing we can do here unless the mask is removing some bits.2298// Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.2299if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;23002301MVT XVT = X.getSimpleValueType();2302MVT VT = N.getSimpleValueType();2303SDLoc DL(N);2304SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);2305SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);2306SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, XVT);2307SDValue NewAnd = DAG.getNode(ISD::AND, DL, XVT, NewSRL, NewMask);2308SDValue NewExt = DAG.getZExtOrTrunc(NewAnd, DL, VT);2309SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);2310SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);23112312// Insert the new nodes into the topological ordering. We must do this in2313// a valid topological ordering as nothing is going to go back and re-sort2314// these nodes. We continually insert before 'N' in sequence as this is2315// essentially a pre-flattened and pre-sorted sequence of nodes. There is no2316// hierarchy left to express.2317insertDAGNode(DAG, N, NewSRLAmt);2318insertDAGNode(DAG, N, NewSRL);2319insertDAGNode(DAG, N, NewMask);2320insertDAGNode(DAG, N, NewAnd);2321insertDAGNode(DAG, N, NewExt);2322insertDAGNode(DAG, N, NewSHLAmt);2323insertDAGNode(DAG, N, NewSHL);2324DAG.ReplaceAllUsesWith(N, NewSHL);2325DAG.RemoveDeadNode(N.getNode());23262327AM.Scale = 1 << AMShiftAmt;2328AM.IndexReg = NewExt;2329return false;2330}23312332// Attempt to peek further into a scaled index register, collecting additional2333// extensions / offsets / etc. Returns /p N if we can't peek any further.2334SDValue X86DAGToDAGISel::matchIndexRecursively(SDValue N,2335X86ISelAddressMode &AM,2336unsigned Depth) {2337assert(AM.IndexReg.getNode() == nullptr && "IndexReg already matched");2338assert((AM.Scale == 1 || AM.Scale == 2 || AM.Scale == 4 || AM.Scale == 8) &&2339"Illegal index scale");23402341// Limit recursion.2342if (Depth >= SelectionDAG::MaxRecursionDepth)2343return N;23442345EVT VT = N.getValueType();2346unsigned Opc = N.getOpcode();23472348// index: add(x,c) -> index: x, disp + c2349if (CurDAG->isBaseWithConstantOffset(N)) {2350auto *AddVal = cast<ConstantSDNode>(N.getOperand(1));2351uint64_t Offset = (uint64_t)AddVal->getSExtValue() * AM.Scale;2352if (!foldOffsetIntoAddress(Offset, AM))2353return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);2354}23552356// index: add(x,x) -> index: x, scale * 22357if (Opc == ISD::ADD && N.getOperand(0) == N.getOperand(1)) {2358if (AM.Scale <= 4) {2359AM.Scale *= 2;2360return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);2361}2362}23632364// index: shl(x,i) -> index: x, scale * (1 << i)2365if (Opc == X86ISD::VSHLI) {2366uint64_t ShiftAmt = N.getConstantOperandVal(1);2367uint64_t ScaleAmt = 1ULL << ShiftAmt;2368if ((AM.Scale * ScaleAmt) <= 8) {2369AM.Scale *= ScaleAmt;2370return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);2371}2372}23732374// index: sext(add_nsw(x,c)) -> index: sext(x), disp + sext(c)2375// TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?2376if (Opc == ISD::SIGN_EXTEND && !VT.isVector() && N.hasOneUse()) {2377SDValue Src = N.getOperand(0);2378if (Src.getOpcode() == ISD::ADD && Src->getFlags().hasNoSignedWrap() &&2379Src.hasOneUse()) {2380if (CurDAG->isBaseWithConstantOffset(Src)) {2381SDValue AddSrc = Src.getOperand(0);2382auto *AddVal = cast<ConstantSDNode>(Src.getOperand(1));2383uint64_t Offset = (uint64_t)AddVal->getSExtValue();2384if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) {2385SDLoc DL(N);2386SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);2387SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT);2388SDValue ExtAdd = CurDAG->getNode(ISD::ADD, DL, VT, ExtSrc, ExtVal);2389insertDAGNode(*CurDAG, N, ExtSrc);2390insertDAGNode(*CurDAG, N, ExtVal);2391insertDAGNode(*CurDAG, N, ExtAdd);2392CurDAG->ReplaceAllUsesWith(N, ExtAdd);2393CurDAG->RemoveDeadNode(N.getNode());2394return ExtSrc;2395}2396}2397}2398}23992400// index: zext(add_nuw(x,c)) -> index: zext(x), disp + zext(c)2401// index: zext(addlike(x,c)) -> index: zext(x), disp + zext(c)2402// TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?2403if (Opc == ISD::ZERO_EXTEND && !VT.isVector() && N.hasOneUse()) {2404SDValue Src = N.getOperand(0);2405unsigned SrcOpc = Src.getOpcode();2406if (((SrcOpc == ISD::ADD && Src->getFlags().hasNoUnsignedWrap()) ||2407CurDAG->isADDLike(Src, /*NoWrap=*/true)) &&2408Src.hasOneUse()) {2409if (CurDAG->isBaseWithConstantOffset(Src)) {2410SDValue AddSrc = Src.getOperand(0);2411uint64_t Offset = Src.getConstantOperandVal(1);2412if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) {2413SDLoc DL(N);2414SDValue Res;2415// If we're also scaling, see if we can use that as well.2416if (AddSrc.getOpcode() == ISD::SHL &&2417isa<ConstantSDNode>(AddSrc.getOperand(1))) {2418SDValue ShVal = AddSrc.getOperand(0);2419uint64_t ShAmt = AddSrc.getConstantOperandVal(1);2420APInt HiBits =2421APInt::getHighBitsSet(AddSrc.getScalarValueSizeInBits(), ShAmt);2422uint64_t ScaleAmt = 1ULL << ShAmt;2423if ((AM.Scale * ScaleAmt) <= 8 &&2424(AddSrc->getFlags().hasNoUnsignedWrap() ||2425CurDAG->MaskedValueIsZero(ShVal, HiBits))) {2426AM.Scale *= ScaleAmt;2427SDValue ExtShVal = CurDAG->getNode(Opc, DL, VT, ShVal);2428SDValue ExtShift = CurDAG->getNode(ISD::SHL, DL, VT, ExtShVal,2429AddSrc.getOperand(1));2430insertDAGNode(*CurDAG, N, ExtShVal);2431insertDAGNode(*CurDAG, N, ExtShift);2432AddSrc = ExtShift;2433Res = ExtShVal;2434}2435}2436SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);2437SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT);2438SDValue ExtAdd = CurDAG->getNode(SrcOpc, DL, VT, ExtSrc, ExtVal);2439insertDAGNode(*CurDAG, N, ExtSrc);2440insertDAGNode(*CurDAG, N, ExtVal);2441insertDAGNode(*CurDAG, N, ExtAdd);2442CurDAG->ReplaceAllUsesWith(N, ExtAdd);2443CurDAG->RemoveDeadNode(N.getNode());2444return Res ? Res : ExtSrc;2445}2446}2447}2448}24492450// TODO: Handle extensions, shifted masks etc.2451return N;2452}24532454bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,2455unsigned Depth) {2456SDLoc dl(N);2457LLVM_DEBUG({2458dbgs() << "MatchAddress: ";2459AM.dump(CurDAG);2460});2461// Limit recursion.2462if (Depth >= SelectionDAG::MaxRecursionDepth)2463return matchAddressBase(N, AM);24642465// If this is already a %rip relative address, we can only merge immediates2466// into it. Instead of handling this in every case, we handle it here.2467// RIP relative addressing: %rip + 32-bit displacement!2468if (AM.isRIPRelative()) {2469// FIXME: JumpTable and ExternalSymbol address currently don't like2470// displacements. It isn't very important, but this should be fixed for2471// consistency.2472if (!(AM.ES || AM.MCSym) && AM.JT != -1)2473return true;24742475if (auto *Cst = dyn_cast<ConstantSDNode>(N))2476if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))2477return false;2478return true;2479}24802481switch (N.getOpcode()) {2482default: break;2483case ISD::LOCAL_RECOVER: {2484if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)2485if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {2486// Use the symbol and don't prefix it.2487AM.MCSym = ESNode->getMCSymbol();2488return false;2489}2490break;2491}2492case ISD::Constant: {2493uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();2494if (!foldOffsetIntoAddress(Val, AM))2495return false;2496break;2497}24982499case X86ISD::Wrapper:2500case X86ISD::WrapperRIP:2501if (!matchWrapper(N, AM))2502return false;2503break;25042505case ISD::LOAD:2506if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))2507return false;2508break;25092510case ISD::FrameIndex:2511if (AM.BaseType == X86ISelAddressMode::RegBase &&2512AM.Base_Reg.getNode() == nullptr &&2513(!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {2514AM.BaseType = X86ISelAddressMode::FrameIndexBase;2515AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();2516return false;2517}2518break;25192520case ISD::SHL:2521if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)2522break;25232524if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {2525unsigned Val = CN->getZExtValue();2526// Note that we handle x<<1 as (,x,2) rather than (x,x) here so2527// that the base operand remains free for further matching. If2528// the base doesn't end up getting used, a post-processing step2529// in MatchAddress turns (,x,2) into (x,x), which is cheaper.2530if (Val == 1 || Val == 2 || Val == 3) {2531SDValue ShVal = N.getOperand(0);2532AM.Scale = 1 << Val;2533AM.IndexReg = matchIndexRecursively(ShVal, AM, Depth + 1);2534return false;2535}2536}2537break;25382539case ISD::SRL: {2540// Scale must not be used already.2541if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;25422543// We only handle up to 64-bit values here as those are what matter for2544// addressing mode optimizations.2545assert(N.getSimpleValueType().getSizeInBits() <= 64 &&2546"Unexpected value size!");25472548SDValue And = N.getOperand(0);2549if (And.getOpcode() != ISD::AND) break;2550SDValue X = And.getOperand(0);25512552// The mask used for the transform is expected to be post-shift, but we2553// found the shift first so just apply the shift to the mask before passing2554// it down.2555if (!isa<ConstantSDNode>(N.getOperand(1)) ||2556!isa<ConstantSDNode>(And.getOperand(1)))2557break;2558uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);25592560// Try to fold the mask and shift into the scale, and return false if we2561// succeed.2562if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))2563return false;2564break;2565}25662567case ISD::SMUL_LOHI:2568case ISD::UMUL_LOHI:2569// A mul_lohi where we need the low part can be folded as a plain multiply.2570if (N.getResNo() != 0) break;2571[[fallthrough]];2572case ISD::MUL:2573case X86ISD::MUL_IMM:2574// X*[3,5,9] -> X+X*[2,4,8]2575if (AM.BaseType == X86ISelAddressMode::RegBase &&2576AM.Base_Reg.getNode() == nullptr &&2577AM.IndexReg.getNode() == nullptr) {2578if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))2579if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||2580CN->getZExtValue() == 9) {2581AM.Scale = unsigned(CN->getZExtValue())-1;25822583SDValue MulVal = N.getOperand(0);2584SDValue Reg;25852586// Okay, we know that we have a scale by now. However, if the scaled2587// value is an add of something and a constant, we can fold the2588// constant into the disp field here.2589if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&2590isa<ConstantSDNode>(MulVal.getOperand(1))) {2591Reg = MulVal.getOperand(0);2592auto *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1));2593uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();2594if (foldOffsetIntoAddress(Disp, AM))2595Reg = N.getOperand(0);2596} else {2597Reg = N.getOperand(0);2598}25992600AM.IndexReg = AM.Base_Reg = Reg;2601return false;2602}2603}2604break;26052606case ISD::SUB: {2607// Given A-B, if A can be completely folded into the address and2608// the index field with the index field unused, use -B as the index.2609// This is a win if a has multiple parts that can be folded into2610// the address. Also, this saves a mov if the base register has2611// other uses, since it avoids a two-address sub instruction, however2612// it costs an additional mov if the index register has other uses.26132614// Add an artificial use to this node so that we can keep track of2615// it if it gets CSE'd with a different node.2616HandleSDNode Handle(N);26172618// Test if the LHS of the sub can be folded.2619X86ISelAddressMode Backup = AM;2620if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {2621N = Handle.getValue();2622AM = Backup;2623break;2624}2625N = Handle.getValue();2626// Test if the index field is free for use.2627if (AM.IndexReg.getNode() || AM.isRIPRelative()) {2628AM = Backup;2629break;2630}26312632int Cost = 0;2633SDValue RHS = N.getOperand(1);2634// If the RHS involves a register with multiple uses, this2635// transformation incurs an extra mov, due to the neg instruction2636// clobbering its operand.2637if (!RHS.getNode()->hasOneUse() ||2638RHS.getNode()->getOpcode() == ISD::CopyFromReg ||2639RHS.getNode()->getOpcode() == ISD::TRUNCATE ||2640RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||2641(RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&2642RHS.getOperand(0).getValueType() == MVT::i32))2643++Cost;2644// If the base is a register with multiple uses, this2645// transformation may save a mov.2646if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&2647!AM.Base_Reg.getNode()->hasOneUse()) ||2648AM.BaseType == X86ISelAddressMode::FrameIndexBase)2649--Cost;2650// If the folded LHS was interesting, this transformation saves2651// address arithmetic.2652if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +2653((AM.Disp != 0) && (Backup.Disp == 0)) +2654(AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)2655--Cost;2656// If it doesn't look like it may be an overall win, don't do it.2657if (Cost >= 0) {2658AM = Backup;2659break;2660}26612662// Ok, the transformation is legal and appears profitable. Go for it.2663// Negation will be emitted later to avoid creating dangling nodes if this2664// was an unprofitable LEA.2665AM.IndexReg = RHS;2666AM.NegateIndex = true;2667AM.Scale = 1;2668return false;2669}26702671case ISD::OR:2672case ISD::XOR:2673// See if we can treat the OR/XOR node as an ADD node.2674if (!CurDAG->isADDLike(N))2675break;2676[[fallthrough]];2677case ISD::ADD:2678if (!matchAdd(N, AM, Depth))2679return false;2680break;26812682case ISD::AND: {2683// Perform some heroic transforms on an and of a constant-count shift2684// with a constant to enable use of the scaled offset field.26852686// Scale must not be used already.2687if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;26882689// We only handle up to 64-bit values here as those are what matter for2690// addressing mode optimizations.2691assert(N.getSimpleValueType().getSizeInBits() <= 64 &&2692"Unexpected value size!");26932694if (!isa<ConstantSDNode>(N.getOperand(1)))2695break;26962697if (N.getOperand(0).getOpcode() == ISD::SRL) {2698SDValue Shift = N.getOperand(0);2699SDValue X = Shift.getOperand(0);27002701uint64_t Mask = N.getConstantOperandVal(1);27022703// Try to fold the mask and shift into an extract and scale.2704if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))2705return false;27062707// Try to fold the mask and shift directly into the scale.2708if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))2709return false;27102711// Try to fold the mask and shift into BEXTR and scale.2712if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))2713return false;2714}27152716// Try to swap the mask and shift to place shifts which can be done as2717// a scale on the outside of the mask.2718if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))2719return false;27202721break;2722}2723case ISD::ZERO_EXTEND: {2724// Try to widen a zexted shift left to the same size as its use, so we can2725// match the shift as a scale factor.2726if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)2727break;27282729SDValue Src = N.getOperand(0);27302731// See if we can match a zext(addlike(x,c)).2732// TODO: Move more ZERO_EXTEND patterns into matchIndexRecursively.2733if (Src.getOpcode() == ISD::ADD || Src.getOpcode() == ISD::OR)2734if (SDValue Index = matchIndexRecursively(N, AM, Depth + 1))2735if (Index != N) {2736AM.IndexReg = Index;2737return false;2738}27392740// Peek through mask: zext(and(shl(x,c1),c2))2741APInt Mask = APInt::getAllOnes(Src.getScalarValueSizeInBits());2742if (Src.getOpcode() == ISD::AND && Src.hasOneUse())2743if (auto *MaskC = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {2744Mask = MaskC->getAPIntValue();2745Src = Src.getOperand(0);2746}27472748if (Src.getOpcode() == ISD::SHL && Src.hasOneUse() && N->hasOneUse()) {2749// Give up if the shift is not a valid scale factor [1,2,3].2750SDValue ShlSrc = Src.getOperand(0);2751SDValue ShlAmt = Src.getOperand(1);2752auto *ShAmtC = dyn_cast<ConstantSDNode>(ShlAmt);2753if (!ShAmtC)2754break;2755unsigned ShAmtV = ShAmtC->getZExtValue();2756if (ShAmtV > 3)2757break;27582759// The narrow shift must only shift out zero bits (it must be 'nuw').2760// That makes it safe to widen to the destination type.2761APInt HighZeros =2762APInt::getHighBitsSet(ShlSrc.getValueSizeInBits(), ShAmtV);2763if (!Src->getFlags().hasNoUnsignedWrap() &&2764!CurDAG->MaskedValueIsZero(ShlSrc, HighZeros & Mask))2765break;27662767// zext (shl nuw i8 %x, C1) to i322768// --> shl (zext i8 %x to i32), (zext C1)2769// zext (and (shl nuw i8 %x, C1), C2) to i322770// --> shl (zext i8 (and %x, C2 >> C1) to i32), (zext C1)2771MVT SrcVT = ShlSrc.getSimpleValueType();2772MVT VT = N.getSimpleValueType();2773SDLoc DL(N);27742775SDValue Res = ShlSrc;2776if (!Mask.isAllOnes()) {2777Res = CurDAG->getConstant(Mask.lshr(ShAmtV), DL, SrcVT);2778insertDAGNode(*CurDAG, N, Res);2779Res = CurDAG->getNode(ISD::AND, DL, SrcVT, ShlSrc, Res);2780insertDAGNode(*CurDAG, N, Res);2781}2782SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Res);2783insertDAGNode(*CurDAG, N, Zext);2784SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, ShlAmt);2785insertDAGNode(*CurDAG, N, NewShl);2786CurDAG->ReplaceAllUsesWith(N, NewShl);2787CurDAG->RemoveDeadNode(N.getNode());27882789// Convert the shift to scale factor.2790AM.Scale = 1 << ShAmtV;2791// If matchIndexRecursively is not called here,2792// Zext may be replaced by other nodes but later used to call a builder2793// method2794AM.IndexReg = matchIndexRecursively(Zext, AM, Depth + 1);2795return false;2796}27972798if (Src.getOpcode() == ISD::SRL && !Mask.isAllOnes()) {2799// Try to fold the mask and shift into an extract and scale.2800if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask.getZExtValue(), Src,2801Src.getOperand(0), AM))2802return false;28032804// Try to fold the mask and shift directly into the scale.2805if (!foldMaskAndShiftToScale(*CurDAG, N, Mask.getZExtValue(), Src,2806Src.getOperand(0), AM))2807return false;28082809// Try to fold the mask and shift into BEXTR and scale.2810if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask.getZExtValue(), Src,2811Src.getOperand(0), AM, *Subtarget))2812return false;2813}28142815break;2816}2817}28182819return matchAddressBase(N, AM);2820}28212822/// Helper for MatchAddress. Add the specified node to the2823/// specified addressing mode without any further recursion.2824bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {2825// Is the base register already occupied?2826if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {2827// If so, check to see if the scale index register is set.2828if (!AM.IndexReg.getNode()) {2829AM.IndexReg = N;2830AM.Scale = 1;2831return false;2832}28332834// Otherwise, we cannot select it.2835return true;2836}28372838// Default, generate it as a register.2839AM.BaseType = X86ISelAddressMode::RegBase;2840AM.Base_Reg = N;2841return false;2842}28432844bool X86DAGToDAGISel::matchVectorAddressRecursively(SDValue N,2845X86ISelAddressMode &AM,2846unsigned Depth) {2847SDLoc dl(N);2848LLVM_DEBUG({2849dbgs() << "MatchVectorAddress: ";2850AM.dump(CurDAG);2851});2852// Limit recursion.2853if (Depth >= SelectionDAG::MaxRecursionDepth)2854return matchAddressBase(N, AM);28552856// TODO: Support other operations.2857switch (N.getOpcode()) {2858case ISD::Constant: {2859uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();2860if (!foldOffsetIntoAddress(Val, AM))2861return false;2862break;2863}2864case X86ISD::Wrapper:2865if (!matchWrapper(N, AM))2866return false;2867break;2868case ISD::ADD: {2869// Add an artificial use to this node so that we can keep track of2870// it if it gets CSE'd with a different node.2871HandleSDNode Handle(N);28722873X86ISelAddressMode Backup = AM;2874if (!matchVectorAddressRecursively(N.getOperand(0), AM, Depth + 1) &&2875!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,2876Depth + 1))2877return false;2878AM = Backup;28792880// Try again after commuting the operands.2881if (!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,2882Depth + 1) &&2883!matchVectorAddressRecursively(Handle.getValue().getOperand(0), AM,2884Depth + 1))2885return false;2886AM = Backup;28872888N = Handle.getValue();2889break;2890}2891}28922893return matchAddressBase(N, AM);2894}28952896/// Helper for selectVectorAddr. Handles things that can be folded into a2897/// gather/scatter address. The index register and scale should have already2898/// been handled.2899bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {2900return matchVectorAddressRecursively(N, AM, 0);2901}29022903bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,2904SDValue IndexOp, SDValue ScaleOp,2905SDValue &Base, SDValue &Scale,2906SDValue &Index, SDValue &Disp,2907SDValue &Segment) {2908X86ISelAddressMode AM;2909AM.Scale = ScaleOp->getAsZExtVal();29102911// Attempt to match index patterns, as long as we're not relying on implicit2912// sign-extension, which is performed BEFORE scale.2913if (IndexOp.getScalarValueSizeInBits() == BasePtr.getScalarValueSizeInBits())2914AM.IndexReg = matchIndexRecursively(IndexOp, AM, 0);2915else2916AM.IndexReg = IndexOp;29172918unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();2919if (AddrSpace == X86AS::GS)2920AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);2921if (AddrSpace == X86AS::FS)2922AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);2923if (AddrSpace == X86AS::SS)2924AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);29252926SDLoc DL(BasePtr);2927MVT VT = BasePtr.getSimpleValueType();29282929// Try to match into the base and displacement fields.2930if (matchVectorAddress(BasePtr, AM))2931return false;29322933getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);2934return true;2935}29362937/// Returns true if it is able to pattern match an addressing mode.2938/// It returns the operands which make up the maximal addressing mode it can2939/// match by reference.2940///2941/// Parent is the parent node of the addr operand that is being matched. It2942/// is always a load, store, atomic node, or null. It is only null when2943/// checking memory operands for inline asm nodes.2944bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,2945SDValue &Scale, SDValue &Index,2946SDValue &Disp, SDValue &Segment) {2947X86ISelAddressMode AM;29482949if (Parent &&2950// This list of opcodes are all the nodes that have an "addr:$ptr" operand2951// that are not a MemSDNode, and thus don't have proper addrspace info.2952Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme2953Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores2954Parent->getOpcode() != X86ISD::TLSCALL && // Fixme2955Parent->getOpcode() != X86ISD::ENQCMD && // Fixme2956Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme2957Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp2958Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp2959unsigned AddrSpace =2960cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();2961if (AddrSpace == X86AS::GS)2962AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);2963if (AddrSpace == X86AS::FS)2964AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);2965if (AddrSpace == X86AS::SS)2966AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);2967}29682969// Save the DL and VT before calling matchAddress, it can invalidate N.2970SDLoc DL(N);2971MVT VT = N.getSimpleValueType();29722973if (matchAddress(N, AM))2974return false;29752976getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);2977return true;2978}29792980bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {2981// Cannot use 32 bit constants to reference objects in kernel/large code2982// model.2983if (TM.getCodeModel() == CodeModel::Kernel ||2984TM.getCodeModel() == CodeModel::Large)2985return false;29862987// In static codegen with small code model, we can get the address of a label2988// into a register with 'movl'2989if (N->getOpcode() != X86ISD::Wrapper)2990return false;29912992N = N.getOperand(0);29932994// At least GNU as does not accept 'movl' for TPOFF relocations.2995// FIXME: We could use 'movl' when we know we are targeting MC.2996if (N->getOpcode() == ISD::TargetGlobalTLSAddress)2997return false;29982999Imm = N;3000// Small/medium code model can reference non-TargetGlobalAddress objects with3001// 32 bit constants.3002if (N->getOpcode() != ISD::TargetGlobalAddress) {3003return TM.getCodeModel() == CodeModel::Small ||3004TM.getCodeModel() == CodeModel::Medium;3005}30063007const GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();3008if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())3009return CR->getUnsignedMax().ult(1ull << 32);30103011return !TM.isLargeGlobalValue(GV);3012}30133014bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,3015SDValue &Scale, SDValue &Index,3016SDValue &Disp, SDValue &Segment) {3017// Save the debug loc before calling selectLEAAddr, in case it invalidates N.3018SDLoc DL(N);30193020if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))3021return false;30223023auto *RN = dyn_cast<RegisterSDNode>(Base);3024if (RN && RN->getReg() == 0)3025Base = CurDAG->getRegister(0, MVT::i64);3026else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {3027// Base could already be %rip, particularly in the x32 ABI.3028SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,3029MVT::i64), 0);3030Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,3031Base);3032}30333034RN = dyn_cast<RegisterSDNode>(Index);3035if (RN && RN->getReg() == 0)3036Index = CurDAG->getRegister(0, MVT::i64);3037else {3038assert(Index.getValueType() == MVT::i32 &&3039"Expect to be extending 32-bit registers for use in LEA");3040SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,3041MVT::i64), 0);3042Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,3043Index);3044}30453046return true;3047}30483049/// Calls SelectAddr and determines if the maximal addressing3050/// mode it matches can be cost effectively emitted as an LEA instruction.3051bool X86DAGToDAGISel::selectLEAAddr(SDValue N,3052SDValue &Base, SDValue &Scale,3053SDValue &Index, SDValue &Disp,3054SDValue &Segment) {3055X86ISelAddressMode AM;30563057// Save the DL and VT before calling matchAddress, it can invalidate N.3058SDLoc DL(N);3059MVT VT = N.getSimpleValueType();30603061// Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support3062// segments.3063SDValue Copy = AM.Segment;3064SDValue T = CurDAG->getRegister(0, MVT::i32);3065AM.Segment = T;3066if (matchAddress(N, AM))3067return false;3068assert (T == AM.Segment);3069AM.Segment = Copy;30703071unsigned Complexity = 0;3072if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())3073Complexity = 1;3074else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)3075Complexity = 4;30763077if (AM.IndexReg.getNode())3078Complexity++;30793080// Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with3081// a simple shift.3082if (AM.Scale > 1)3083Complexity++;30843085// FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA3086// to a LEA. This is determined with some experimentation but is by no means3087// optimal (especially for code size consideration). LEA is nice because of3088// its three-address nature. Tweak the cost function again when we can run3089// convertToThreeAddress() at register allocation time.3090if (AM.hasSymbolicDisplacement()) {3091// For X86-64, always use LEA to materialize RIP-relative addresses.3092if (Subtarget->is64Bit())3093Complexity = 4;3094else3095Complexity += 2;3096}30973098// Heuristic: try harder to form an LEA from ADD if the operands set flags.3099// Unlike ADD, LEA does not affect flags, so we will be less likely to require3100// duplicating flag-producing instructions later in the pipeline.3101if (N.getOpcode() == ISD::ADD) {3102auto isMathWithFlags = [](SDValue V) {3103switch (V.getOpcode()) {3104case X86ISD::ADD:3105case X86ISD::SUB:3106case X86ISD::ADC:3107case X86ISD::SBB:3108case X86ISD::SMUL:3109case X86ISD::UMUL:3110/* TODO: These opcodes can be added safely, but we may want to justify3111their inclusion for different reasons (better for reg-alloc).3112case X86ISD::OR:3113case X86ISD::XOR:3114case X86ISD::AND:3115*/3116// Value 1 is the flag output of the node - verify it's not dead.3117return !SDValue(V.getNode(), 1).use_empty();3118default:3119return false;3120}3121};3122// TODO: We might want to factor in whether there's a load folding3123// opportunity for the math op that disappears with LEA.3124if (isMathWithFlags(N.getOperand(0)) || isMathWithFlags(N.getOperand(1)))3125Complexity++;3126}31273128if (AM.Disp)3129Complexity++;31303131// If it isn't worth using an LEA, reject it.3132if (Complexity <= 2)3133return false;31343135getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);3136return true;3137}31383139/// This is only run on TargetGlobalTLSAddress nodes.3140bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,3141SDValue &Scale, SDValue &Index,3142SDValue &Disp, SDValue &Segment) {3143assert(N.getOpcode() == ISD::TargetGlobalTLSAddress ||3144N.getOpcode() == ISD::TargetExternalSymbol);31453146X86ISelAddressMode AM;3147if (auto *GA = dyn_cast<GlobalAddressSDNode>(N)) {3148AM.GV = GA->getGlobal();3149AM.Disp += GA->getOffset();3150AM.SymbolFlags = GA->getTargetFlags();3151} else {3152auto *SA = cast<ExternalSymbolSDNode>(N);3153AM.ES = SA->getSymbol();3154AM.SymbolFlags = SA->getTargetFlags();3155}31563157if (Subtarget->is32Bit()) {3158AM.Scale = 1;3159AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);3160}31613162MVT VT = N.getSimpleValueType();3163getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);3164return true;3165}31663167bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {3168// Keep track of the original value type and whether this value was3169// truncated. If we see a truncation from pointer type to VT that truncates3170// bits that are known to be zero, we can use a narrow reference.3171EVT VT = N.getValueType();3172bool WasTruncated = false;3173if (N.getOpcode() == ISD::TRUNCATE) {3174WasTruncated = true;3175N = N.getOperand(0);3176}31773178if (N.getOpcode() != X86ISD::Wrapper)3179return false;31803181// We can only use non-GlobalValues as immediates if they were not truncated,3182// as we do not have any range information. If we have a GlobalValue and the3183// address was not truncated, we can select it as an operand directly.3184unsigned Opc = N.getOperand(0)->getOpcode();3185if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {3186Op = N.getOperand(0);3187// We can only select the operand directly if we didn't have to look past a3188// truncate.3189return !WasTruncated;3190}31913192// Check that the global's range fits into VT.3193auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));3194std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();3195if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))3196return false;31973198// Okay, we can use a narrow reference.3199Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,3200GA->getOffset(), GA->getTargetFlags());3201return true;3202}32033204bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,3205SDValue &Base, SDValue &Scale,3206SDValue &Index, SDValue &Disp,3207SDValue &Segment) {3208assert(Root && P && "Unknown root/parent nodes");3209if (!ISD::isNON_EXTLoad(N.getNode()) ||3210!IsProfitableToFold(N, P, Root) ||3211!IsLegalToFold(N, P, Root, OptLevel))3212return false;32133214return selectAddr(N.getNode(),3215N.getOperand(1), Base, Scale, Index, Disp, Segment);3216}32173218bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,3219SDValue &Base, SDValue &Scale,3220SDValue &Index, SDValue &Disp,3221SDValue &Segment) {3222assert(Root && P && "Unknown root/parent nodes");3223if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||3224!IsProfitableToFold(N, P, Root) ||3225!IsLegalToFold(N, P, Root, OptLevel))3226return false;32273228return selectAddr(N.getNode(),3229N.getOperand(1), Base, Scale, Index, Disp, Segment);3230}32313232/// Return an SDNode that returns the value of the global base register.3233/// Output instructions required to initialize the global base register,3234/// if necessary.3235SDNode *X86DAGToDAGISel::getGlobalBaseReg() {3236unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);3237auto &DL = MF->getDataLayout();3238return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();3239}32403241bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {3242if (N->getOpcode() == ISD::TRUNCATE)3243N = N->getOperand(0).getNode();3244if (N->getOpcode() != X86ISD::Wrapper)3245return false;32463247auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));3248if (!GA)3249return false;32503251auto *GV = GA->getGlobal();3252std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange();3253if (CR)3254return CR->getSignedMin().sge(-1ull << Width) &&3255CR->getSignedMax().slt(1ull << Width);3256// In the kernel code model, globals are in the negative 2GB of the address3257// space, so globals can be a sign extended 32-bit immediate.3258// In other code models, small globals are in the low 2GB of the address3259// space, so sign extending them is equivalent to zero extending them.3260return Width == 32 && !TM.isLargeGlobalValue(GV);3261}32623263X86::CondCode X86DAGToDAGISel::getCondFromNode(SDNode *N) const {3264assert(N->isMachineOpcode() && "Unexpected node");3265unsigned Opc = N->getMachineOpcode();3266const MCInstrDesc &MCID = getInstrInfo()->get(Opc);3267int CondNo = X86::getCondSrcNoFromDesc(MCID);3268if (CondNo < 0)3269return X86::COND_INVALID;32703271return static_cast<X86::CondCode>(N->getConstantOperandVal(CondNo));3272}32733274/// Test whether the given X86ISD::CMP node has any users that use a flag3275/// other than ZF.3276bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {3277// Examine each user of the node.3278for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();3279UI != UE; ++UI) {3280// Only check things that use the flags.3281if (UI.getUse().getResNo() != Flags.getResNo())3282continue;3283// Only examine CopyToReg uses that copy to EFLAGS.3284if (UI->getOpcode() != ISD::CopyToReg ||3285cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)3286return false;3287// Examine each user of the CopyToReg use.3288for (SDNode::use_iterator FlagUI = UI->use_begin(),3289FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {3290// Only examine the Flag result.3291if (FlagUI.getUse().getResNo() != 1) continue;3292// Anything unusual: assume conservatively.3293if (!FlagUI->isMachineOpcode()) return false;3294// Examine the condition code of the user.3295X86::CondCode CC = getCondFromNode(*FlagUI);32963297switch (CC) {3298// Comparisons which only use the zero flag.3299case X86::COND_E: case X86::COND_NE:3300continue;3301// Anything else: assume conservatively.3302default:3303return false;3304}3305}3306}3307return true;3308}33093310/// Test whether the given X86ISD::CMP node has any uses which require the SF3311/// flag to be accurate.3312bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {3313// Examine each user of the node.3314for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();3315UI != UE; ++UI) {3316// Only check things that use the flags.3317if (UI.getUse().getResNo() != Flags.getResNo())3318continue;3319// Only examine CopyToReg uses that copy to EFLAGS.3320if (UI->getOpcode() != ISD::CopyToReg ||3321cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)3322return false;3323// Examine each user of the CopyToReg use.3324for (SDNode::use_iterator FlagUI = UI->use_begin(),3325FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {3326// Only examine the Flag result.3327if (FlagUI.getUse().getResNo() != 1) continue;3328// Anything unusual: assume conservatively.3329if (!FlagUI->isMachineOpcode()) return false;3330// Examine the condition code of the user.3331X86::CondCode CC = getCondFromNode(*FlagUI);33323333switch (CC) {3334// Comparisons which don't examine the SF flag.3335case X86::COND_A: case X86::COND_AE:3336case X86::COND_B: case X86::COND_BE:3337case X86::COND_E: case X86::COND_NE:3338case X86::COND_O: case X86::COND_NO:3339case X86::COND_P: case X86::COND_NP:3340continue;3341// Anything else: assume conservatively.3342default:3343return false;3344}3345}3346}3347return true;3348}33493350static bool mayUseCarryFlag(X86::CondCode CC) {3351switch (CC) {3352// Comparisons which don't examine the CF flag.3353case X86::COND_O: case X86::COND_NO:3354case X86::COND_E: case X86::COND_NE:3355case X86::COND_S: case X86::COND_NS:3356case X86::COND_P: case X86::COND_NP:3357case X86::COND_L: case X86::COND_GE:3358case X86::COND_G: case X86::COND_LE:3359return false;3360// Anything else: assume conservatively.3361default:3362return true;3363}3364}33653366/// Test whether the given node which sets flags has any uses which require the3367/// CF flag to be accurate.3368bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {3369// Examine each user of the node.3370for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();3371UI != UE; ++UI) {3372// Only check things that use the flags.3373if (UI.getUse().getResNo() != Flags.getResNo())3374continue;33753376unsigned UIOpc = UI->getOpcode();33773378if (UIOpc == ISD::CopyToReg) {3379// Only examine CopyToReg uses that copy to EFLAGS.3380if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)3381return false;3382// Examine each user of the CopyToReg use.3383for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();3384FlagUI != FlagUE; ++FlagUI) {3385// Only examine the Flag result.3386if (FlagUI.getUse().getResNo() != 1)3387continue;3388// Anything unusual: assume conservatively.3389if (!FlagUI->isMachineOpcode())3390return false;3391// Examine the condition code of the user.3392X86::CondCode CC = getCondFromNode(*FlagUI);33933394if (mayUseCarryFlag(CC))3395return false;3396}33973398// This CopyToReg is ok. Move on to the next user.3399continue;3400}34013402// This might be an unselected node. So look for the pre-isel opcodes that3403// use flags.3404unsigned CCOpNo;3405switch (UIOpc) {3406default:3407// Something unusual. Be conservative.3408return false;3409case X86ISD::SETCC: CCOpNo = 0; break;3410case X86ISD::SETCC_CARRY: CCOpNo = 0; break;3411case X86ISD::CMOV: CCOpNo = 2; break;3412case X86ISD::BRCOND: CCOpNo = 2; break;3413}34143415X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);3416if (mayUseCarryFlag(CC))3417return false;3418}3419return true;3420}34213422/// Check whether or not the chain ending in StoreNode is suitable for doing3423/// the {load; op; store} to modify transformation.3424static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,3425SDValue StoredVal, SelectionDAG *CurDAG,3426unsigned LoadOpNo,3427LoadSDNode *&LoadNode,3428SDValue &InputChain) {3429// Is the stored value result 0 of the operation?3430if (StoredVal.getResNo() != 0) return false;34313432// Are there other uses of the operation other than the store?3433if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;34343435// Is the store non-extending and non-indexed?3436if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())3437return false;34383439SDValue Load = StoredVal->getOperand(LoadOpNo);3440// Is the stored value a non-extending and non-indexed load?3441if (!ISD::isNormalLoad(Load.getNode())) return false;34423443// Return LoadNode by reference.3444LoadNode = cast<LoadSDNode>(Load);34453446// Is store the only read of the loaded value?3447if (!Load.hasOneUse())3448return false;34493450// Is the address of the store the same as the load?3451if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||3452LoadNode->getOffset() != StoreNode->getOffset())3453return false;34543455bool FoundLoad = false;3456SmallVector<SDValue, 4> ChainOps;3457SmallVector<const SDNode *, 4> LoopWorklist;3458SmallPtrSet<const SDNode *, 16> Visited;3459const unsigned int Max = 1024;34603461// Visualization of Load-Op-Store fusion:3462// -------------------------3463// Legend:3464// *-lines = Chain operand dependencies.3465// |-lines = Normal operand dependencies.3466// Dependencies flow down and right. n-suffix references multiple nodes.3467//3468// C Xn C3469// * * *3470// * * *3471// Xn A-LD Yn TF Yn3472// * * \ | * |3473// * * \ | * |3474// * * \ | => A--LD_OP_ST3475// * * \| \3476// TF OP \3477// * | \ Zn3478// * | \3479// A-ST Zn3480//34813482// This merge induced dependences from: #1: Xn -> LD, OP, Zn3483// #2: Yn -> LD3484// #3: ST -> Zn34853486// Ensure the transform is safe by checking for the dual3487// dependencies to make sure we do not induce a loop.34883489// As LD is a predecessor to both OP and ST we can do this by checking:3490// a). if LD is a predecessor to a member of Xn or Yn.3491// b). if a Zn is a predecessor to ST.34923493// However, (b) can only occur through being a chain predecessor to3494// ST, which is the same as Zn being a member or predecessor of Xn,3495// which is a subset of LD being a predecessor of Xn. So it's3496// subsumed by check (a).34973498SDValue Chain = StoreNode->getChain();34993500// Gather X elements in ChainOps.3501if (Chain == Load.getValue(1)) {3502FoundLoad = true;3503ChainOps.push_back(Load.getOperand(0));3504} else if (Chain.getOpcode() == ISD::TokenFactor) {3505for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {3506SDValue Op = Chain.getOperand(i);3507if (Op == Load.getValue(1)) {3508FoundLoad = true;3509// Drop Load, but keep its chain. No cycle check necessary.3510ChainOps.push_back(Load.getOperand(0));3511continue;3512}3513LoopWorklist.push_back(Op.getNode());3514ChainOps.push_back(Op);3515}3516}35173518if (!FoundLoad)3519return false;35203521// Worklist is currently Xn. Add Yn to worklist.3522for (SDValue Op : StoredVal->ops())3523if (Op.getNode() != LoadNode)3524LoopWorklist.push_back(Op.getNode());35253526// Check (a) if Load is a predecessor to Xn + Yn3527if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,3528true))3529return false;35303531InputChain =3532CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);3533return true;3534}35353536// Change a chain of {load; op; store} of the same value into a simple op3537// through memory of that value, if the uses of the modified value and its3538// address are suitable.3539//3540// The tablegen pattern memory operand pattern is currently not able to match3541// the case where the EFLAGS on the original operation are used.3542//3543// To move this to tablegen, we'll need to improve tablegen to allow flags to3544// be transferred from a node in the pattern to the result node, probably with3545// a new keyword. For example, we have this3546// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",3547// [(store (add (loadi64 addr:$dst), -1), addr:$dst),3548// (implicit EFLAGS)]>;3549// but maybe need something like this3550// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",3551// [(store (add (loadi64 addr:$dst), -1), addr:$dst),3552// (transferrable EFLAGS)]>;3553//3554// Until then, we manually fold these and instruction select the operation3555// here.3556bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {3557auto *StoreNode = cast<StoreSDNode>(Node);3558SDValue StoredVal = StoreNode->getOperand(1);3559unsigned Opc = StoredVal->getOpcode();35603561// Before we try to select anything, make sure this is memory operand size3562// and opcode we can handle. Note that this must match the code below that3563// actually lowers the opcodes.3564EVT MemVT = StoreNode->getMemoryVT();3565if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&3566MemVT != MVT::i8)3567return false;35683569bool IsCommutable = false;3570bool IsNegate = false;3571switch (Opc) {3572default:3573return false;3574case X86ISD::SUB:3575IsNegate = isNullConstant(StoredVal.getOperand(0));3576break;3577case X86ISD::SBB:3578break;3579case X86ISD::ADD:3580case X86ISD::ADC:3581case X86ISD::AND:3582case X86ISD::OR:3583case X86ISD::XOR:3584IsCommutable = true;3585break;3586}35873588unsigned LoadOpNo = IsNegate ? 1 : 0;3589LoadSDNode *LoadNode = nullptr;3590SDValue InputChain;3591if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,3592LoadNode, InputChain)) {3593if (!IsCommutable)3594return false;35953596// This operation is commutable, try the other operand.3597LoadOpNo = 1;3598if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,3599LoadNode, InputChain))3600return false;3601}36023603SDValue Base, Scale, Index, Disp, Segment;3604if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,3605Segment))3606return false;36073608auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,3609unsigned Opc8) {3610switch (MemVT.getSimpleVT().SimpleTy) {3611case MVT::i64:3612return Opc64;3613case MVT::i32:3614return Opc32;3615case MVT::i16:3616return Opc16;3617case MVT::i8:3618return Opc8;3619default:3620llvm_unreachable("Invalid size!");3621}3622};36233624MachineSDNode *Result;3625switch (Opc) {3626case X86ISD::SUB:3627// Handle negate.3628if (IsNegate) {3629unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,3630X86::NEG8m);3631const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};3632Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,3633MVT::Other, Ops);3634break;3635}3636[[fallthrough]];3637case X86ISD::ADD:3638// Try to match inc/dec.3639if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {3640bool IsOne = isOneConstant(StoredVal.getOperand(1));3641bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));3642// ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.3643if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {3644unsigned NewOpc =3645((Opc == X86ISD::ADD) == IsOne)3646? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)3647: SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);3648const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};3649Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,3650MVT::Other, Ops);3651break;3652}3653}3654[[fallthrough]];3655case X86ISD::ADC:3656case X86ISD::SBB:3657case X86ISD::AND:3658case X86ISD::OR:3659case X86ISD::XOR: {3660auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {3661switch (Opc) {3662case X86ISD::ADD:3663return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,3664X86::ADD8mr);3665case X86ISD::ADC:3666return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,3667X86::ADC8mr);3668case X86ISD::SUB:3669return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,3670X86::SUB8mr);3671case X86ISD::SBB:3672return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,3673X86::SBB8mr);3674case X86ISD::AND:3675return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,3676X86::AND8mr);3677case X86ISD::OR:3678return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);3679case X86ISD::XOR:3680return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,3681X86::XOR8mr);3682default:3683llvm_unreachable("Invalid opcode!");3684}3685};3686auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {3687switch (Opc) {3688case X86ISD::ADD:3689return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,3690X86::ADD8mi);3691case X86ISD::ADC:3692return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,3693X86::ADC8mi);3694case X86ISD::SUB:3695return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,3696X86::SUB8mi);3697case X86ISD::SBB:3698return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,3699X86::SBB8mi);3700case X86ISD::AND:3701return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,3702X86::AND8mi);3703case X86ISD::OR:3704return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,3705X86::OR8mi);3706case X86ISD::XOR:3707return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,3708X86::XOR8mi);3709default:3710llvm_unreachable("Invalid opcode!");3711}3712};37133714unsigned NewOpc = SelectRegOpcode(Opc);3715SDValue Operand = StoredVal->getOperand(1-LoadOpNo);37163717// See if the operand is a constant that we can fold into an immediate3718// operand.3719if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {3720int64_t OperandV = OperandC->getSExtValue();37213722// Check if we can shrink the operand enough to fit in an immediate (or3723// fit into a smaller immediate) by negating it and switching the3724// operation.3725if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&3726((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||3727(MemVT == MVT::i64 && !isInt<32>(OperandV) &&3728isInt<32>(-OperandV))) &&3729hasNoCarryFlagUses(StoredVal.getValue(1))) {3730OperandV = -OperandV;3731Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;3732}37333734if (MemVT != MVT::i64 || isInt<32>(OperandV)) {3735Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);3736NewOpc = SelectImmOpcode(Opc);3737}3738}37393740if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {3741SDValue CopyTo =3742CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,3743StoredVal.getOperand(2), SDValue());37443745const SDValue Ops[] = {Base, Scale, Index, Disp,3746Segment, Operand, CopyTo, CopyTo.getValue(1)};3747Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,3748Ops);3749} else {3750const SDValue Ops[] = {Base, Scale, Index, Disp,3751Segment, Operand, InputChain};3752Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,3753Ops);3754}3755break;3756}3757default:3758llvm_unreachable("Invalid opcode!");3759}37603761MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),3762LoadNode->getMemOperand()};3763CurDAG->setNodeMemRefs(Result, MemOps);37643765// Update Load Chain uses as well.3766ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));3767ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));3768ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));3769CurDAG->RemoveDeadNode(Node);3770return true;3771}37723773// See if this is an X & Mask that we can match to BEXTR/BZHI.3774// Where Mask is one of the following patterns:3775// a) x & (1 << nbits) - 13776// b) x & ~(-1 << nbits)3777// c) x & (-1 >> (32 - y))3778// d) x << (32 - y) >> (32 - y)3779// e) (1 << nbits) - 13780bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {3781assert(3782(Node->getOpcode() == ISD::ADD || Node->getOpcode() == ISD::AND ||3783Node->getOpcode() == ISD::SRL) &&3784"Should be either an and-mask, or right-shift after clearing high bits.");37853786// BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.3787if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())3788return false;37893790MVT NVT = Node->getSimpleValueType(0);37913792// Only supported for 32 and 64 bits.3793if (NVT != MVT::i32 && NVT != MVT::i64)3794return false;37953796SDValue NBits;3797bool NegateNBits;37983799// If we have BMI2's BZHI, we are ok with muti-use patterns.3800// Else, if we only have BMI1's BEXTR, we require one-use.3801const bool AllowExtraUsesByDefault = Subtarget->hasBMI2();3802auto checkUses = [AllowExtraUsesByDefault](3803SDValue Op, unsigned NUses,3804std::optional<bool> AllowExtraUses) {3805return AllowExtraUses.value_or(AllowExtraUsesByDefault) ||3806Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());3807};3808auto checkOneUse = [checkUses](SDValue Op,3809std::optional<bool> AllowExtraUses =3810std::nullopt) {3811return checkUses(Op, 1, AllowExtraUses);3812};3813auto checkTwoUse = [checkUses](SDValue Op,3814std::optional<bool> AllowExtraUses =3815std::nullopt) {3816return checkUses(Op, 2, AllowExtraUses);3817};38183819auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {3820if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {3821assert(V.getSimpleValueType() == MVT::i32 &&3822V.getOperand(0).getSimpleValueType() == MVT::i64 &&3823"Expected i64 -> i32 truncation");3824V = V.getOperand(0);3825}3826return V;3827};38283829// a) x & ((1 << nbits) + (-1))3830auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits,3831&NegateNBits](SDValue Mask) -> bool {3832// Match `add`. Must only have one use!3833if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))3834return false;3835// We should be adding all-ones constant (i.e. subtracting one.)3836if (!isAllOnesConstant(Mask->getOperand(1)))3837return false;3838// Match `1 << nbits`. Might be truncated. Must only have one use!3839SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));3840if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))3841return false;3842if (!isOneConstant(M0->getOperand(0)))3843return false;3844NBits = M0->getOperand(1);3845NegateNBits = false;3846return true;3847};38483849auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {3850V = peekThroughOneUseTruncation(V);3851return CurDAG->MaskedValueIsAllOnes(3852V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),3853NVT.getSizeInBits()));3854};38553856// b) x & ~(-1 << nbits)3857auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,3858&NBits, &NegateNBits](SDValue Mask) -> bool {3859// Match `~()`. Must only have one use!3860if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))3861return false;3862// The -1 only has to be all-ones for the final Node's NVT.3863if (!isAllOnes(Mask->getOperand(1)))3864return false;3865// Match `-1 << nbits`. Might be truncated. Must only have one use!3866SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));3867if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))3868return false;3869// The -1 only has to be all-ones for the final Node's NVT.3870if (!isAllOnes(M0->getOperand(0)))3871return false;3872NBits = M0->getOperand(1);3873NegateNBits = false;3874return true;3875};38763877// Try to match potentially-truncated shift amount as `(bitwidth - y)`,3878// or leave the shift amount as-is, but then we'll have to negate it.3879auto canonicalizeShiftAmt = [&NBits, &NegateNBits](SDValue ShiftAmt,3880unsigned Bitwidth) {3881NBits = ShiftAmt;3882NegateNBits = true;3883// Skip over a truncate of the shift amount, if any.3884if (NBits.getOpcode() == ISD::TRUNCATE)3885NBits = NBits.getOperand(0);3886// Try to match the shift amount as (bitwidth - y). It should go away, too.3887// If it doesn't match, that's fine, we'll just negate it ourselves.3888if (NBits.getOpcode() != ISD::SUB)3889return;3890auto *V0 = dyn_cast<ConstantSDNode>(NBits.getOperand(0));3891if (!V0 || V0->getZExtValue() != Bitwidth)3892return;3893NBits = NBits.getOperand(1);3894NegateNBits = false;3895};38963897// c) x & (-1 >> z) but then we'll have to subtract z from bitwidth3898// or3899// c) x & (-1 >> (32 - y))3900auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, &NegateNBits,3901canonicalizeShiftAmt](SDValue Mask) -> bool {3902// The mask itself may be truncated.3903Mask = peekThroughOneUseTruncation(Mask);3904unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();3905// Match `l>>`. Must only have one use!3906if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))3907return false;3908// We should be shifting truly all-ones constant.3909if (!isAllOnesConstant(Mask.getOperand(0)))3910return false;3911SDValue M1 = Mask.getOperand(1);3912// The shift amount should not be used externally.3913if (!checkOneUse(M1))3914return false;3915canonicalizeShiftAmt(M1, Bitwidth);3916// Pattern c. is non-canonical, and is expanded into pattern d. iff there3917// is no extra use of the mask. Clearly, there was one since we are here.3918// But at the same time, if we need to negate the shift amount,3919// then we don't want the mask to stick around, else it's unprofitable.3920return !NegateNBits;3921};39223923SDValue X;39243925// d) x << z >> z but then we'll have to subtract z from bitwidth3926// or3927// d) x << (32 - y) >> (32 - y)3928auto matchPatternD = [checkOneUse, checkTwoUse, canonicalizeShiftAmt,3929AllowExtraUsesByDefault, &NegateNBits,3930&X](SDNode *Node) -> bool {3931if (Node->getOpcode() != ISD::SRL)3932return false;3933SDValue N0 = Node->getOperand(0);3934if (N0->getOpcode() != ISD::SHL)3935return false;3936unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();3937SDValue N1 = Node->getOperand(1);3938SDValue N01 = N0->getOperand(1);3939// Both of the shifts must be by the exact same value.3940if (N1 != N01)3941return false;3942canonicalizeShiftAmt(N1, Bitwidth);3943// There should not be any external uses of the inner shift / shift amount.3944// Note that while we are generally okay with external uses given BMI2,3945// iff we need to negate the shift amount, we are not okay with extra uses.3946const bool AllowExtraUses = AllowExtraUsesByDefault && !NegateNBits;3947if (!checkOneUse(N0, AllowExtraUses) || !checkTwoUse(N1, AllowExtraUses))3948return false;3949X = N0->getOperand(0);3950return true;3951};39523953auto matchLowBitMask = [matchPatternA, matchPatternB,3954matchPatternC](SDValue Mask) -> bool {3955return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);3956};39573958if (Node->getOpcode() == ISD::AND) {3959X = Node->getOperand(0);3960SDValue Mask = Node->getOperand(1);39613962if (matchLowBitMask(Mask)) {3963// Great.3964} else {3965std::swap(X, Mask);3966if (!matchLowBitMask(Mask))3967return false;3968}3969} else if (matchLowBitMask(SDValue(Node, 0))) {3970X = CurDAG->getAllOnesConstant(SDLoc(Node), NVT);3971} else if (!matchPatternD(Node))3972return false;39733974// If we need to negate the shift amount, require BMI2 BZHI support.3975// It's just too unprofitable for BMI1 BEXTR.3976if (NegateNBits && !Subtarget->hasBMI2())3977return false;39783979SDLoc DL(Node);39803981// Truncate the shift amount.3982NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);3983insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);39843985// Insert 8-bit NBits into lowest 8 bits of 32-bit register.3986// All the other bits are undefined, we do not care about them.3987SDValue ImplDef = SDValue(3988CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);3989insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);39903991SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);3992insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);3993NBits = SDValue(CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL,3994MVT::i32, ImplDef, NBits, SRIdxVal),39950);3996insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);39973998// We might have matched the amount of high bits to be cleared,3999// but we want the amount of low bits to be kept, so negate it then.4000if (NegateNBits) {4001SDValue BitWidthC = CurDAG->getConstant(NVT.getSizeInBits(), DL, MVT::i32);4002insertDAGNode(*CurDAG, SDValue(Node, 0), BitWidthC);40034004NBits = CurDAG->getNode(ISD::SUB, DL, MVT::i32, BitWidthC, NBits);4005insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);4006}40074008if (Subtarget->hasBMI2()) {4009// Great, just emit the BZHI..4010if (NVT != MVT::i32) {4011// But have to place the bit count into the wide-enough register first.4012NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);4013insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);4014}40154016SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);4017ReplaceNode(Node, Extract.getNode());4018SelectCode(Extract.getNode());4019return true;4020}40214022// Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is4023// *logically* shifted (potentially with one-use trunc inbetween),4024// and the truncation was the only use of the shift,4025// and if so look past one-use truncation.4026{4027SDValue RealX = peekThroughOneUseTruncation(X);4028// FIXME: only if the shift is one-use?4029if (RealX != X && RealX.getOpcode() == ISD::SRL)4030X = RealX;4031}40324033MVT XVT = X.getSimpleValueType();40344035// Else, emitting BEXTR requires one more step.4036// The 'control' of BEXTR has the pattern of:4037// [15...8 bit][ 7...0 bit] location4038// [ bit count][ shift] name4039// I.e. 0b000000011'00000001 means (x >> 0b1) & 0b1140404041// Shift NBits left by 8 bits, thus producing 'control'.4042// This makes the low 8 bits to be zero.4043SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);4044insertDAGNode(*CurDAG, SDValue(Node, 0), C8);4045SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);4046insertDAGNode(*CurDAG, SDValue(Node, 0), Control);40474048// If the 'X' is *logically* shifted, we can fold that shift into 'control'.4049// FIXME: only if the shift is one-use?4050if (X.getOpcode() == ISD::SRL) {4051SDValue ShiftAmt = X.getOperand(1);4052X = X.getOperand(0);40534054assert(ShiftAmt.getValueType() == MVT::i8 &&4055"Expected shift amount to be i8");40564057// Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!4058// We could zext to i16 in some form, but we intentionally don't do that.4059SDValue OrigShiftAmt = ShiftAmt;4060ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);4061insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);40624063// And now 'or' these low 8 bits of shift amount into the 'control'.4064Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);4065insertDAGNode(*CurDAG, SDValue(Node, 0), Control);4066}40674068// But have to place the 'control' into the wide-enough register first.4069if (XVT != MVT::i32) {4070Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);4071insertDAGNode(*CurDAG, SDValue(Node, 0), Control);4072}40734074// And finally, form the BEXTR itself.4075SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);40764077// The 'X' was originally truncated. Do that now.4078if (XVT != NVT) {4079insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);4080Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);4081}40824083ReplaceNode(Node, Extract.getNode());4084SelectCode(Extract.getNode());40854086return true;4087}40884089// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.4090MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {4091MVT NVT = Node->getSimpleValueType(0);4092SDLoc dl(Node);40934094SDValue N0 = Node->getOperand(0);4095SDValue N1 = Node->getOperand(1);40964097// If we have TBM we can use an immediate for the control. If we have BMI4098// we should only do this if the BEXTR instruction is implemented well.4099// Otherwise moving the control into a register makes this more costly.4100// TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM4101// hoisting the move immediate would make it worthwhile with a less optimal4102// BEXTR?4103bool PreferBEXTR =4104Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());4105if (!PreferBEXTR && !Subtarget->hasBMI2())4106return nullptr;41074108// Must have a shift right.4109if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)4110return nullptr;41114112// Shift can't have additional users.4113if (!N0->hasOneUse())4114return nullptr;41154116// Only supported for 32 and 64 bits.4117if (NVT != MVT::i32 && NVT != MVT::i64)4118return nullptr;41194120// Shift amount and RHS of and must be constant.4121auto *MaskCst = dyn_cast<ConstantSDNode>(N1);4122auto *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));4123if (!MaskCst || !ShiftCst)4124return nullptr;41254126// And RHS must be a mask.4127uint64_t Mask = MaskCst->getZExtValue();4128if (!isMask_64(Mask))4129return nullptr;41304131uint64_t Shift = ShiftCst->getZExtValue();4132uint64_t MaskSize = llvm::popcount(Mask);41334134// Don't interfere with something that can be handled by extracting AH.4135// TODO: If we are able to fold a load, BEXTR might still be better than AH.4136if (Shift == 8 && MaskSize == 8)4137return nullptr;41384139// Make sure we are only using bits that were in the original value, not4140// shifted in.4141if (Shift + MaskSize > NVT.getSizeInBits())4142return nullptr;41434144// BZHI, if available, is always fast, unlike BEXTR. But even if we decide4145// that we can't use BEXTR, it is only worthwhile using BZHI if the mask4146// does not fit into 32 bits. Load folding is not a sufficient reason.4147if (!PreferBEXTR && MaskSize <= 32)4148return nullptr;41494150SDValue Control;4151unsigned ROpc, MOpc;41524153#define GET_EGPR_IF_ENABLED(OPC) (Subtarget->hasEGPR() ? OPC##_EVEX : OPC)4154if (!PreferBEXTR) {4155assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");4156// If we can't make use of BEXTR then we can't fuse shift+mask stages.4157// Let's perform the mask first, and apply shift later. Note that we need to4158// widen the mask to account for the fact that we'll apply shift afterwards!4159Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);4160ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rr)4161: GET_EGPR_IF_ENABLED(X86::BZHI32rr);4162MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rm)4163: GET_EGPR_IF_ENABLED(X86::BZHI32rm);4164unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;4165Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);4166} else {4167// The 'control' of BEXTR has the pattern of:4168// [15...8 bit][ 7...0 bit] location4169// [ bit count][ shift] name4170// I.e. 0b000000011'00000001 means (x >> 0b1) & 0b114171Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);4172if (Subtarget->hasTBM()) {4173ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;4174MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;4175} else {4176assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");4177// BMI requires the immediate to placed in a register.4178ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rr)4179: GET_EGPR_IF_ENABLED(X86::BEXTR32rr);4180MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rm)4181: GET_EGPR_IF_ENABLED(X86::BEXTR32rm);4182unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;4183Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);4184}4185}41864187MachineSDNode *NewNode;4188SDValue Input = N0->getOperand(0);4189SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;4190if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {4191SDValue Ops[] = {4192Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};4193SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);4194NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);4195// Update the chain.4196ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));4197// Record the mem-refs4198CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});4199} else {4200NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);4201}42024203if (!PreferBEXTR) {4204// We still need to apply the shift.4205SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);4206unsigned NewOpc = NVT == MVT::i64 ? GET_ND_IF_ENABLED(X86::SHR64ri)4207: GET_ND_IF_ENABLED(X86::SHR32ri);4208NewNode =4209CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);4210}42114212return NewNode;4213}42144215// Emit a PCMISTR(I/M) instruction.4216MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,4217bool MayFoldLoad, const SDLoc &dl,4218MVT VT, SDNode *Node) {4219SDValue N0 = Node->getOperand(0);4220SDValue N1 = Node->getOperand(1);4221SDValue Imm = Node->getOperand(2);4222auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();4223Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());42244225// Try to fold a load. No need to check alignment.4226SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;4227if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {4228SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,4229N1.getOperand(0) };4230SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);4231MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);4232// Update the chain.4233ReplaceUses(N1.getValue(1), SDValue(CNode, 2));4234// Record the mem-refs4235CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});4236return CNode;4237}42384239SDValue Ops[] = { N0, N1, Imm };4240SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);4241MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);4242return CNode;4243}42444245// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need4246// to emit a second instruction after this one. This is needed since we have two4247// copyToReg nodes glued before this and we need to continue that glue through.4248MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,4249bool MayFoldLoad, const SDLoc &dl,4250MVT VT, SDNode *Node,4251SDValue &InGlue) {4252SDValue N0 = Node->getOperand(0);4253SDValue N2 = Node->getOperand(2);4254SDValue Imm = Node->getOperand(4);4255auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();4256Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());42574258// Try to fold a load. No need to check alignment.4259SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;4260if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {4261SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,4262N2.getOperand(0), InGlue };4263SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);4264MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);4265InGlue = SDValue(CNode, 3);4266// Update the chain.4267ReplaceUses(N2.getValue(1), SDValue(CNode, 2));4268// Record the mem-refs4269CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});4270return CNode;4271}42724273SDValue Ops[] = { N0, N2, Imm, InGlue };4274SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);4275MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);4276InGlue = SDValue(CNode, 2);4277return CNode;4278}42794280bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {4281EVT VT = N->getValueType(0);42824283// Only handle scalar shifts.4284if (VT.isVector())4285return false;42864287// Narrower shifts only mask to 5 bits in hardware.4288unsigned Size = VT == MVT::i64 ? 64 : 32;42894290SDValue OrigShiftAmt = N->getOperand(1);4291SDValue ShiftAmt = OrigShiftAmt;4292SDLoc DL(N);42934294// Skip over a truncate of the shift amount.4295if (ShiftAmt->getOpcode() == ISD::TRUNCATE)4296ShiftAmt = ShiftAmt->getOperand(0);42974298// This function is called after X86DAGToDAGISel::matchBitExtract(),4299// so we are not afraid that we might mess up BZHI/BEXTR pattern.43004301SDValue NewShiftAmt;4302if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB ||4303ShiftAmt->getOpcode() == ISD::XOR) {4304SDValue Add0 = ShiftAmt->getOperand(0);4305SDValue Add1 = ShiftAmt->getOperand(1);4306auto *Add0C = dyn_cast<ConstantSDNode>(Add0);4307auto *Add1C = dyn_cast<ConstantSDNode>(Add1);4308// If we are shifting by X+/-/^N where N == 0 mod Size, then just shift by X4309// to avoid the ADD/SUB/XOR.4310if (Add1C && Add1C->getAPIntValue().urem(Size) == 0) {4311NewShiftAmt = Add0;43124313} else if (ShiftAmt->getOpcode() != ISD::ADD && ShiftAmt.hasOneUse() &&4314((Add0C && Add0C->getAPIntValue().urem(Size) == Size - 1) ||4315(Add1C && Add1C->getAPIntValue().urem(Size) == Size - 1))) {4316// If we are doing a NOT on just the lower bits with (Size*N-1) -/^ X4317// we can replace it with a NOT. In the XOR case it may save some code4318// size, in the SUB case it also may save a move.4319assert(Add0C == nullptr || Add1C == nullptr);43204321// We can only do N-X, not X-N4322if (ShiftAmt->getOpcode() == ISD::SUB && Add0C == nullptr)4323return false;43244325EVT OpVT = ShiftAmt.getValueType();43264327SDValue AllOnes = CurDAG->getAllOnesConstant(DL, OpVT);4328NewShiftAmt = CurDAG->getNode(ISD::XOR, DL, OpVT,4329Add0C == nullptr ? Add0 : Add1, AllOnes);4330insertDAGNode(*CurDAG, OrigShiftAmt, AllOnes);4331insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);4332// If we are shifting by N-X where N == 0 mod Size, then just shift by4333// -X to generate a NEG instead of a SUB of a constant.4334} else if (ShiftAmt->getOpcode() == ISD::SUB && Add0C &&4335Add0C->getZExtValue() != 0) {4336EVT SubVT = ShiftAmt.getValueType();4337SDValue X;4338if (Add0C->getZExtValue() % Size == 0)4339X = Add1;4340else if (ShiftAmt.hasOneUse() && Size == 64 &&4341Add0C->getZExtValue() % 32 == 0) {4342// We have a 64-bit shift by (n*32-x), turn it into -(x+n*32).4343// This is mainly beneficial if we already compute (x+n*32).4344if (Add1.getOpcode() == ISD::TRUNCATE) {4345Add1 = Add1.getOperand(0);4346SubVT = Add1.getValueType();4347}4348if (Add0.getValueType() != SubVT) {4349Add0 = CurDAG->getZExtOrTrunc(Add0, DL, SubVT);4350insertDAGNode(*CurDAG, OrigShiftAmt, Add0);4351}43524353X = CurDAG->getNode(ISD::ADD, DL, SubVT, Add1, Add0);4354insertDAGNode(*CurDAG, OrigShiftAmt, X);4355} else4356return false;4357// Insert a negate op.4358// TODO: This isn't guaranteed to replace the sub if there is a logic cone4359// that uses it that's not a shift.4360SDValue Zero = CurDAG->getConstant(0, DL, SubVT);4361SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, X);4362NewShiftAmt = Neg;43634364// Insert these operands into a valid topological order so they can4365// get selected independently.4366insertDAGNode(*CurDAG, OrigShiftAmt, Zero);4367insertDAGNode(*CurDAG, OrigShiftAmt, Neg);4368} else4369return false;4370} else4371return false;43724373if (NewShiftAmt.getValueType() != MVT::i8) {4374// Need to truncate the shift amount.4375NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);4376// Add to a correct topological ordering.4377insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);4378}43794380// Insert a new mask to keep the shift amount legal. This should be removed4381// by isel patterns.4382NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,4383CurDAG->getConstant(Size - 1, DL, MVT::i8));4384// Place in a correct topological ordering.4385insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);43864387SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),4388NewShiftAmt);4389if (UpdatedNode != N) {4390// If we found an existing node, we should replace ourselves with that node4391// and wait for it to be selected after its other users.4392ReplaceNode(N, UpdatedNode);4393return true;4394}43954396// If the original shift amount is now dead, delete it so that we don't run4397// it through isel.4398if (OrigShiftAmt.getNode()->use_empty())4399CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());44004401// Now that we've optimized the shift amount, defer to normal isel to get4402// load folding and legacy vs BMI2 selection without repeating it here.4403SelectCode(N);4404return true;4405}44064407bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {4408MVT NVT = N->getSimpleValueType(0);4409unsigned Opcode = N->getOpcode();4410SDLoc dl(N);44114412// For operations of the form (x << C1) op C2, check if we can use a smaller4413// encoding for C2 by transforming it into (x op (C2>>C1)) << C1.4414SDValue Shift = N->getOperand(0);4415SDValue N1 = N->getOperand(1);44164417auto *Cst = dyn_cast<ConstantSDNode>(N1);4418if (!Cst)4419return false;44204421int64_t Val = Cst->getSExtValue();44224423// If we have an any_extend feeding the AND, look through it to see if there4424// is a shift behind it. But only if the AND doesn't use the extended bits.4425// FIXME: Generalize this to other ANY_EXTEND than i32 to i64?4426bool FoundAnyExtend = false;4427if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&4428Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&4429isUInt<32>(Val)) {4430FoundAnyExtend = true;4431Shift = Shift.getOperand(0);4432}44334434if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())4435return false;44364437// i8 is unshrinkable, i16 should be promoted to i32.4438if (NVT != MVT::i32 && NVT != MVT::i64)4439return false;44404441auto *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));4442if (!ShlCst)4443return false;44444445uint64_t ShAmt = ShlCst->getZExtValue();44464447// Make sure that we don't change the operation by removing bits.4448// This only matters for OR and XOR, AND is unaffected.4449uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;4450if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)4451return false;44524453// Check the minimum bitwidth for the new constant.4454// TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.4455auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {4456if (Opcode == ISD::AND) {4457// AND32ri is the same as AND64ri32 with zext imm.4458// Try this before sign extended immediates below.4459ShiftedVal = (uint64_t)Val >> ShAmt;4460if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))4461return true;4462// Also swap order when the AND can become MOVZX.4463if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)4464return true;4465}4466ShiftedVal = Val >> ShAmt;4467if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||4468(!isInt<32>(Val) && isInt<32>(ShiftedVal)))4469return true;4470if (Opcode != ISD::AND) {4471// MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr4472ShiftedVal = (uint64_t)Val >> ShAmt;4473if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))4474return true;4475}4476return false;4477};44784479int64_t ShiftedVal;4480if (!CanShrinkImmediate(ShiftedVal))4481return false;44824483// Ok, we can reorder to get a smaller immediate.44844485// But, its possible the original immediate allowed an AND to become MOVZX.4486// Doing this late due to avoid the MakedValueIsZero call as late as4487// possible.4488if (Opcode == ISD::AND) {4489// Find the smallest zext this could possibly be.4490unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();4491ZExtWidth = llvm::bit_ceil(std::max(ZExtWidth, 8U));44924493// Figure out which bits need to be zero to achieve that mask.4494APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),4495ZExtWidth);4496NeededMask &= ~Cst->getAPIntValue();44974498if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))4499return false;4500}45014502SDValue X = Shift.getOperand(0);4503if (FoundAnyExtend) {4504SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);4505insertDAGNode(*CurDAG, SDValue(N, 0), NewX);4506X = NewX;4507}45084509SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);4510insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);4511SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);4512insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);4513SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,4514Shift.getOperand(1));4515ReplaceNode(N, NewSHL.getNode());4516SelectCode(NewSHL.getNode());4517return true;4518}45194520bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA,4521SDNode *ParentB, SDNode *ParentC,4522SDValue A, SDValue B, SDValue C,4523uint8_t Imm) {4524assert(A.isOperandOf(ParentA) && B.isOperandOf(ParentB) &&4525C.isOperandOf(ParentC) && "Incorrect parent node");45264527auto tryFoldLoadOrBCast =4528[this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale,4529SDValue &Index, SDValue &Disp, SDValue &Segment) {4530if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))4531return true;45324533// Not a load, check for broadcast which may be behind a bitcast.4534if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {4535P = L.getNode();4536L = L.getOperand(0);4537}45384539if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)4540return false;45414542// Only 32 and 64 bit broadcasts are supported.4543auto *MemIntr = cast<MemIntrinsicSDNode>(L);4544unsigned Size = MemIntr->getMemoryVT().getSizeInBits();4545if (Size != 32 && Size != 64)4546return false;45474548return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);4549};45504551bool FoldedLoad = false;4552SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;4553if (tryFoldLoadOrBCast(Root, ParentC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {4554FoldedLoad = true;4555} else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3,4556Tmp4)) {4557FoldedLoad = true;4558std::swap(A, C);4559// Swap bits 1/4 and 3/6.4560uint8_t OldImm = Imm;4561Imm = OldImm & 0xa5;4562if (OldImm & 0x02) Imm |= 0x10;4563if (OldImm & 0x10) Imm |= 0x02;4564if (OldImm & 0x08) Imm |= 0x40;4565if (OldImm & 0x40) Imm |= 0x08;4566} else if (tryFoldLoadOrBCast(Root, ParentB, B, Tmp0, Tmp1, Tmp2, Tmp3,4567Tmp4)) {4568FoldedLoad = true;4569std::swap(B, C);4570// Swap bits 1/2 and 5/6.4571uint8_t OldImm = Imm;4572Imm = OldImm & 0x99;4573if (OldImm & 0x02) Imm |= 0x04;4574if (OldImm & 0x04) Imm |= 0x02;4575if (OldImm & 0x20) Imm |= 0x40;4576if (OldImm & 0x40) Imm |= 0x20;4577}45784579SDLoc DL(Root);45804581SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8);45824583MVT NVT = Root->getSimpleValueType(0);45844585MachineSDNode *MNode;4586if (FoldedLoad) {4587SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);45884589unsigned Opc;4590if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) {4591auto *MemIntr = cast<MemIntrinsicSDNode>(C);4592unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits();4593assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!");45944595bool UseD = EltSize == 32;4596if (NVT.is128BitVector())4597Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi;4598else if (NVT.is256BitVector())4599Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi;4600else if (NVT.is512BitVector())4601Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi;4602else4603llvm_unreachable("Unexpected vector size!");4604} else {4605bool UseD = NVT.getVectorElementType() == MVT::i32;4606if (NVT.is128BitVector())4607Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi;4608else if (NVT.is256BitVector())4609Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi;4610else if (NVT.is512BitVector())4611Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi;4612else4613llvm_unreachable("Unexpected vector size!");4614}46154616SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)};4617MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);46184619// Update the chain.4620ReplaceUses(C.getValue(1), SDValue(MNode, 1));4621// Record the mem-refs4622CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()});4623} else {4624bool UseD = NVT.getVectorElementType() == MVT::i32;4625unsigned Opc;4626if (NVT.is128BitVector())4627Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri;4628else if (NVT.is256BitVector())4629Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri;4630else if (NVT.is512BitVector())4631Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri;4632else4633llvm_unreachable("Unexpected vector size!");46344635MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm});4636}46374638ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0));4639CurDAG->RemoveDeadNode(Root);4640return true;4641}46424643// Try to match two logic ops to a VPTERNLOG.4644// FIXME: Handle more complex patterns that use an operand more than once?4645bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) {4646MVT NVT = N->getSimpleValueType(0);46474648// Make sure we support VPTERNLOG.4649if (!NVT.isVector() || !Subtarget->hasAVX512() ||4650NVT.getVectorElementType() == MVT::i1)4651return false;46524653// We need VLX for 128/256-bit.4654if (!(Subtarget->hasVLX() || NVT.is512BitVector()))4655return false;46564657SDValue N0 = N->getOperand(0);4658SDValue N1 = N->getOperand(1);46594660auto getFoldableLogicOp = [](SDValue Op) {4661// Peek through single use bitcast.4662if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse())4663Op = Op.getOperand(0);46644665if (!Op.hasOneUse())4666return SDValue();46674668unsigned Opc = Op.getOpcode();4669if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR ||4670Opc == X86ISD::ANDNP)4671return Op;46724673return SDValue();4674};46754676SDValue A, FoldableOp;4677if ((FoldableOp = getFoldableLogicOp(N1))) {4678A = N0;4679} else if ((FoldableOp = getFoldableLogicOp(N0))) {4680A = N1;4681} else4682return false;46834684SDValue B = FoldableOp.getOperand(0);4685SDValue C = FoldableOp.getOperand(1);4686SDNode *ParentA = N;4687SDNode *ParentB = FoldableOp.getNode();4688SDNode *ParentC = FoldableOp.getNode();46894690// We can build the appropriate control immediate by performing the logic4691// operation we're matching using these constants for A, B, and C.4692uint8_t TernlogMagicA = 0xf0;4693uint8_t TernlogMagicB = 0xcc;4694uint8_t TernlogMagicC = 0xaa;46954696// Some of the inputs may be inverted, peek through them and invert the4697// magic values accordingly.4698// TODO: There may be a bitcast before the xor that we should peek through.4699auto PeekThroughNot = [](SDValue &Op, SDNode *&Parent, uint8_t &Magic) {4700if (Op.getOpcode() == ISD::XOR && Op.hasOneUse() &&4701ISD::isBuildVectorAllOnes(Op.getOperand(1).getNode())) {4702Magic = ~Magic;4703Parent = Op.getNode();4704Op = Op.getOperand(0);4705}4706};47074708PeekThroughNot(A, ParentA, TernlogMagicA);4709PeekThroughNot(B, ParentB, TernlogMagicB);4710PeekThroughNot(C, ParentC, TernlogMagicC);47114712uint8_t Imm;4713switch (FoldableOp.getOpcode()) {4714default: llvm_unreachable("Unexpected opcode!");4715case ISD::AND: Imm = TernlogMagicB & TernlogMagicC; break;4716case ISD::OR: Imm = TernlogMagicB | TernlogMagicC; break;4717case ISD::XOR: Imm = TernlogMagicB ^ TernlogMagicC; break;4718case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break;4719}47204721switch (N->getOpcode()) {4722default: llvm_unreachable("Unexpected opcode!");4723case X86ISD::ANDNP:4724if (A == N0)4725Imm &= ~TernlogMagicA;4726else4727Imm = ~(Imm) & TernlogMagicA;4728break;4729case ISD::AND: Imm &= TernlogMagicA; break;4730case ISD::OR: Imm |= TernlogMagicA; break;4731case ISD::XOR: Imm ^= TernlogMagicA; break;4732}47334734return matchVPTERNLOG(N, ParentA, ParentB, ParentC, A, B, C, Imm);4735}47364737/// If the high bits of an 'and' operand are known zero, try setting the4738/// high bits of an 'and' constant operand to produce a smaller encoding by4739/// creating a small, sign-extended negative immediate rather than a large4740/// positive one. This reverses a transform in SimplifyDemandedBits that4741/// shrinks mask constants by clearing bits. There is also a possibility that4742/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that4743/// case, just replace the 'and'. Return 'true' if the node is replaced.4744bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {4745// i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't4746// have immediate operands.4747MVT VT = And->getSimpleValueType(0);4748if (VT != MVT::i32 && VT != MVT::i64)4749return false;47504751auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));4752if (!And1C)4753return false;47544755// Bail out if the mask constant is already negative. It's can't shrink more.4756// If the upper 32 bits of a 64 bit mask are all zeros, we have special isel4757// patterns to use a 32-bit and instead of a 64-bit and by relying on the4758// implicit zeroing of 32 bit ops. So we should check if the lower 32 bits4759// are negative too.4760APInt MaskVal = And1C->getAPIntValue();4761unsigned MaskLZ = MaskVal.countl_zero();4762if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))4763return false;47644765// Don't extend into the upper 32 bits of a 64 bit mask.4766if (VT == MVT::i64 && MaskLZ >= 32) {4767MaskLZ -= 32;4768MaskVal = MaskVal.trunc(32);4769}47704771SDValue And0 = And->getOperand(0);4772APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);4773APInt NegMaskVal = MaskVal | HighZeros;47744775// If a negative constant would not allow a smaller encoding, there's no need4776// to continue. Only change the constant when we know it's a win.4777unsigned MinWidth = NegMaskVal.getSignificantBits();4778if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getSignificantBits() <= 32))4779return false;47804781// Extend masks if we truncated above.4782if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {4783NegMaskVal = NegMaskVal.zext(64);4784HighZeros = HighZeros.zext(64);4785}47864787// The variable operand must be all zeros in the top bits to allow using the4788// new, negative constant as the mask.4789if (!CurDAG->MaskedValueIsZero(And0, HighZeros))4790return false;47914792// Check if the mask is -1. In that case, this is an unnecessary instruction4793// that escaped earlier analysis.4794if (NegMaskVal.isAllOnes()) {4795ReplaceNode(And, And0.getNode());4796return true;4797}47984799// A negative mask allows a smaller encoding. Create a new 'and' node.4800SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);4801insertDAGNode(*CurDAG, SDValue(And, 0), NewMask);4802SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);4803ReplaceNode(And, NewAnd.getNode());4804SelectCode(NewAnd.getNode());4805return true;4806}48074808static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,4809bool FoldedBCast, bool Masked) {4810#define VPTESTM_CASE(VT, SUFFIX) \4811case MVT::VT: \4812if (Masked) \4813return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \4814return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX;481548164817#define VPTESTM_BROADCAST_CASES(SUFFIX) \4818default: llvm_unreachable("Unexpected VT!"); \4819VPTESTM_CASE(v4i32, DZ128##SUFFIX) \4820VPTESTM_CASE(v2i64, QZ128##SUFFIX) \4821VPTESTM_CASE(v8i32, DZ256##SUFFIX) \4822VPTESTM_CASE(v4i64, QZ256##SUFFIX) \4823VPTESTM_CASE(v16i32, DZ##SUFFIX) \4824VPTESTM_CASE(v8i64, QZ##SUFFIX)48254826#define VPTESTM_FULL_CASES(SUFFIX) \4827VPTESTM_BROADCAST_CASES(SUFFIX) \4828VPTESTM_CASE(v16i8, BZ128##SUFFIX) \4829VPTESTM_CASE(v8i16, WZ128##SUFFIX) \4830VPTESTM_CASE(v32i8, BZ256##SUFFIX) \4831VPTESTM_CASE(v16i16, WZ256##SUFFIX) \4832VPTESTM_CASE(v64i8, BZ##SUFFIX) \4833VPTESTM_CASE(v32i16, WZ##SUFFIX)48344835if (FoldedBCast) {4836switch (TestVT.SimpleTy) {4837VPTESTM_BROADCAST_CASES(rmb)4838}4839}48404841if (FoldedLoad) {4842switch (TestVT.SimpleTy) {4843VPTESTM_FULL_CASES(rm)4844}4845}48464847switch (TestVT.SimpleTy) {4848VPTESTM_FULL_CASES(rr)4849}48504851#undef VPTESTM_FULL_CASES4852#undef VPTESTM_BROADCAST_CASES4853#undef VPTESTM_CASE4854}48554856// Try to create VPTESTM instruction. If InMask is not null, it will be used4857// to form a masked operation.4858bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,4859SDValue InMask) {4860assert(Subtarget->hasAVX512() && "Expected AVX512!");4861assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&4862"Unexpected VT!");48634864// Look for equal and not equal compares.4865ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();4866if (CC != ISD::SETEQ && CC != ISD::SETNE)4867return false;48684869SDValue SetccOp0 = Setcc.getOperand(0);4870SDValue SetccOp1 = Setcc.getOperand(1);48714872// Canonicalize the all zero vector to the RHS.4873if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))4874std::swap(SetccOp0, SetccOp1);48754876// See if we're comparing against zero.4877if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))4878return false;48794880SDValue N0 = SetccOp0;48814882MVT CmpVT = N0.getSimpleValueType();4883MVT CmpSVT = CmpVT.getVectorElementType();48844885// Start with both operands the same. We'll try to refine this.4886SDValue Src0 = N0;4887SDValue Src1 = N0;48884889{4890// Look through single use bitcasts.4891SDValue N0Temp = N0;4892if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())4893N0Temp = N0.getOperand(0);48944895// Look for single use AND.4896if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {4897Src0 = N0Temp.getOperand(0);4898Src1 = N0Temp.getOperand(1);4899}4900}49014902// Without VLX we need to widen the operation.4903bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();49044905auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L,4906SDValue &Base, SDValue &Scale, SDValue &Index,4907SDValue &Disp, SDValue &Segment) {4908// If we need to widen, we can't fold the load.4909if (!Widen)4910if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))4911return true;49124913// If we didn't fold a load, try to match broadcast. No widening limitation4914// for this. But only 32 and 64 bit types are supported.4915if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64)4916return false;49174918// Look through single use bitcasts.4919if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {4920P = L.getNode();4921L = L.getOperand(0);4922}49234924if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)4925return false;49264927auto *MemIntr = cast<MemIntrinsicSDNode>(L);4928if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits())4929return false;49304931return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);4932};49334934// We can only fold loads if the sources are unique.4935bool CanFoldLoads = Src0 != Src1;49364937bool FoldedLoad = false;4938SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;4939if (CanFoldLoads) {4940FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2,4941Tmp3, Tmp4);4942if (!FoldedLoad) {4943// And is commutative.4944FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1,4945Tmp2, Tmp3, Tmp4);4946if (FoldedLoad)4947std::swap(Src0, Src1);4948}4949}49504951bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD;49524953bool IsMasked = InMask.getNode() != nullptr;49544955SDLoc dl(Root);49564957MVT ResVT = Setcc.getSimpleValueType();4958MVT MaskVT = ResVT;4959if (Widen) {4960// Widen the inputs using insert_subreg or copy_to_regclass.4961unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;4962unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;4963unsigned NumElts = CmpVT.getVectorNumElements() * Scale;4964CmpVT = MVT::getVectorVT(CmpSVT, NumElts);4965MaskVT = MVT::getVectorVT(MVT::i1, NumElts);4966SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,4967CmpVT), 0);4968Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);49694970if (!FoldedBCast)4971Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);49724973if (IsMasked) {4974// Widen the mask.4975unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID();4976SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);4977InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,4978dl, MaskVT, InMask, RC), 0);4979}4980}49814982bool IsTestN = CC == ISD::SETEQ;4983unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,4984IsMasked);49854986MachineSDNode *CNode;4987if (FoldedLoad) {4988SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);49894990if (IsMasked) {4991SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,4992Src1.getOperand(0) };4993CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);4994} else {4995SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,4996Src1.getOperand(0) };4997CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);4998}49995000// Update the chain.5001ReplaceUses(Src1.getValue(1), SDValue(CNode, 1));5002// Record the mem-refs5003CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()});5004} else {5005if (IsMasked)5006CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);5007else5008CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);5009}50105011// If we widened, we need to shrink the mask VT.5012if (Widen) {5013unsigned RegClass = TLI->getRegClassFor(ResVT)->getID();5014SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);5015CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,5016dl, ResVT, SDValue(CNode, 0), RC);5017}50185019ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));5020CurDAG->RemoveDeadNode(Root);5021return true;5022}50235024// Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it5025// into vpternlog.5026bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {5027assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");50285029MVT NVT = N->getSimpleValueType(0);50305031// Make sure we support VPTERNLOG.5032if (!NVT.isVector() || !Subtarget->hasAVX512())5033return false;50345035// We need VLX for 128/256-bit.5036if (!(Subtarget->hasVLX() || NVT.is512BitVector()))5037return false;50385039SDValue N0 = N->getOperand(0);5040SDValue N1 = N->getOperand(1);50415042// Canonicalize AND to LHS.5043if (N1.getOpcode() == ISD::AND)5044std::swap(N0, N1);50455046if (N0.getOpcode() != ISD::AND ||5047N1.getOpcode() != X86ISD::ANDNP ||5048!N0.hasOneUse() || !N1.hasOneUse())5049return false;50505051// ANDN is not commutable, use it to pick down A and C.5052SDValue A = N1.getOperand(0);5053SDValue C = N1.getOperand(1);50545055// AND is commutable, if one operand matches A, the other operand is B.5056// Otherwise this isn't a match.5057SDValue B;5058if (N0.getOperand(0) == A)5059B = N0.getOperand(1);5060else if (N0.getOperand(1) == A)5061B = N0.getOperand(0);5062else5063return false;50645065SDLoc dl(N);5066SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);5067SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);5068ReplaceNode(N, Ternlog.getNode());50695070return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(),5071Ternlog.getNode(), A, B, C, 0xCA);5072}50735074void X86DAGToDAGISel::Select(SDNode *Node) {5075MVT NVT = Node->getSimpleValueType(0);5076unsigned Opcode = Node->getOpcode();5077SDLoc dl(Node);50785079if (Node->isMachineOpcode()) {5080LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');5081Node->setNodeId(-1);5082return; // Already selected.5083}50845085switch (Opcode) {5086default: break;5087case ISD::INTRINSIC_W_CHAIN: {5088unsigned IntNo = Node->getConstantOperandVal(1);5089switch (IntNo) {5090default: break;5091case Intrinsic::x86_encodekey128:5092case Intrinsic::x86_encodekey256: {5093if (!Subtarget->hasKL())5094break;50955096unsigned Opcode;5097switch (IntNo) {5098default: llvm_unreachable("Impossible intrinsic");5099case Intrinsic::x86_encodekey128:5100Opcode = X86::ENCODEKEY128;5101break;5102case Intrinsic::x86_encodekey256:5103Opcode = X86::ENCODEKEY256;5104break;5105}51065107SDValue Chain = Node->getOperand(0);5108Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(3),5109SDValue());5110if (Opcode == X86::ENCODEKEY256)5111Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(4),5112Chain.getValue(1));51135114MachineSDNode *Res = CurDAG->getMachineNode(5115Opcode, dl, Node->getVTList(),5116{Node->getOperand(2), Chain, Chain.getValue(1)});5117ReplaceNode(Node, Res);5118return;5119}5120case Intrinsic::x86_tileloadd64_internal:5121case Intrinsic::x86_tileloaddt164_internal: {5122if (!Subtarget->hasAMXTILE())5123break;5124auto *MFI =5125CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();5126MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);5127unsigned Opc = IntNo == Intrinsic::x86_tileloadd64_internal5128? X86::PTILELOADDV5129: X86::PTILELOADDT1V;5130// _tile_loadd_internal(row, col, buf, STRIDE)5131SDValue Base = Node->getOperand(4);5132SDValue Scale = getI8Imm(1, dl);5133SDValue Index = Node->getOperand(5);5134SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);5135SDValue Segment = CurDAG->getRegister(0, MVT::i16);5136SDValue Chain = Node->getOperand(0);5137MachineSDNode *CNode;5138SDValue Ops[] = {Node->getOperand(2),5139Node->getOperand(3),5140Base,5141Scale,5142Index,5143Disp,5144Segment,5145Chain};5146CNode = CurDAG->getMachineNode(Opc, dl, {MVT::x86amx, MVT::Other}, Ops);5147ReplaceNode(Node, CNode);5148return;5149}5150}5151break;5152}5153case ISD::INTRINSIC_VOID: {5154unsigned IntNo = Node->getConstantOperandVal(1);5155switch (IntNo) {5156default: break;5157case Intrinsic::x86_sse3_monitor:5158case Intrinsic::x86_monitorx:5159case Intrinsic::x86_clzero: {5160bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;51615162unsigned Opc = 0;5163switch (IntNo) {5164default: llvm_unreachable("Unexpected intrinsic!");5165case Intrinsic::x86_sse3_monitor:5166if (!Subtarget->hasSSE3())5167break;5168Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;5169break;5170case Intrinsic::x86_monitorx:5171if (!Subtarget->hasMWAITX())5172break;5173Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;5174break;5175case Intrinsic::x86_clzero:5176if (!Subtarget->hasCLZERO())5177break;5178Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;5179break;5180}51815182if (Opc) {5183unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;5184SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,5185Node->getOperand(2), SDValue());5186SDValue InGlue = Chain.getValue(1);51875188if (IntNo == Intrinsic::x86_sse3_monitor ||5189IntNo == Intrinsic::x86_monitorx) {5190// Copy the other two operands to ECX and EDX.5191Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),5192InGlue);5193InGlue = Chain.getValue(1);5194Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),5195InGlue);5196InGlue = Chain.getValue(1);5197}51985199MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,5200{ Chain, InGlue});5201ReplaceNode(Node, CNode);5202return;5203}52045205break;5206}5207case Intrinsic::x86_tilestored64_internal: {5208auto *MFI =5209CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();5210MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);5211unsigned Opc = X86::PTILESTOREDV;5212// _tile_stored_internal(row, col, buf, STRIDE, c)5213SDValue Base = Node->getOperand(4);5214SDValue Scale = getI8Imm(1, dl);5215SDValue Index = Node->getOperand(5);5216SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);5217SDValue Segment = CurDAG->getRegister(0, MVT::i16);5218SDValue Chain = Node->getOperand(0);5219MachineSDNode *CNode;5220SDValue Ops[] = {Node->getOperand(2),5221Node->getOperand(3),5222Base,5223Scale,5224Index,5225Disp,5226Segment,5227Node->getOperand(6),5228Chain};5229CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);5230ReplaceNode(Node, CNode);5231return;5232}5233case Intrinsic::x86_tileloadd64:5234case Intrinsic::x86_tileloaddt164:5235case Intrinsic::x86_tilestored64: {5236if (!Subtarget->hasAMXTILE())5237break;5238auto *MFI =5239CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();5240MFI->setAMXProgModel(AMXProgModelEnum::DirectReg);5241unsigned Opc;5242switch (IntNo) {5243default: llvm_unreachable("Unexpected intrinsic!");5244case Intrinsic::x86_tileloadd64: Opc = X86::PTILELOADD; break;5245case Intrinsic::x86_tileloaddt164: Opc = X86::PTILELOADDT1; break;5246case Intrinsic::x86_tilestored64: Opc = X86::PTILESTORED; break;5247}5248// FIXME: Match displacement and scale.5249unsigned TIndex = Node->getConstantOperandVal(2);5250SDValue TReg = getI8Imm(TIndex, dl);5251SDValue Base = Node->getOperand(3);5252SDValue Scale = getI8Imm(1, dl);5253SDValue Index = Node->getOperand(4);5254SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);5255SDValue Segment = CurDAG->getRegister(0, MVT::i16);5256SDValue Chain = Node->getOperand(0);5257MachineSDNode *CNode;5258if (Opc == X86::PTILESTORED) {5259SDValue Ops[] = { Base, Scale, Index, Disp, Segment, TReg, Chain };5260CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);5261} else {5262SDValue Ops[] = { TReg, Base, Scale, Index, Disp, Segment, Chain };5263CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);5264}5265ReplaceNode(Node, CNode);5266return;5267}5268}5269break;5270}5271case ISD::BRIND:5272case X86ISD::NT_BRIND: {5273if (Subtarget->isTargetNaCl())5274// NaCl has its own pass where jmp %r32 are converted to jmp %r64. We5275// leave the instruction alone.5276break;5277if (Subtarget->isTarget64BitILP32()) {5278// Converts a 32-bit register to a 64-bit, zero-extended version of5279// it. This is needed because x86-64 can do many things, but jmp %r325280// ain't one of them.5281SDValue Target = Node->getOperand(1);5282assert(Target.getValueType() == MVT::i32 && "Unexpected VT!");5283SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64);5284SDValue Brind = CurDAG->getNode(Opcode, dl, MVT::Other,5285Node->getOperand(0), ZextTarget);5286ReplaceNode(Node, Brind.getNode());5287SelectCode(ZextTarget.getNode());5288SelectCode(Brind.getNode());5289return;5290}5291break;5292}5293case X86ISD::GlobalBaseReg:5294ReplaceNode(Node, getGlobalBaseReg());5295return;52965297case ISD::BITCAST:5298// Just drop all 128/256/512-bit bitcasts.5299if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||5300NVT == MVT::f128) {5301ReplaceUses(SDValue(Node, 0), Node->getOperand(0));5302CurDAG->RemoveDeadNode(Node);5303return;5304}5305break;53065307case ISD::SRL:5308if (matchBitExtract(Node))5309return;5310[[fallthrough]];5311case ISD::SRA:5312case ISD::SHL:5313if (tryShiftAmountMod(Node))5314return;5315break;53165317case X86ISD::VPTERNLOG: {5318uint8_t Imm = Node->getConstantOperandVal(3);5319if (matchVPTERNLOG(Node, Node, Node, Node, Node->getOperand(0),5320Node->getOperand(1), Node->getOperand(2), Imm))5321return;5322break;5323}53245325case X86ISD::ANDNP:5326if (tryVPTERNLOG(Node))5327return;5328break;53295330case ISD::AND:5331if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) {5332// Try to form a masked VPTESTM. Operands can be in either order.5333SDValue N0 = Node->getOperand(0);5334SDValue N1 = Node->getOperand(1);5335if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&5336tryVPTESTM(Node, N0, N1))5337return;5338if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&5339tryVPTESTM(Node, N1, N0))5340return;5341}53425343if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {5344ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));5345CurDAG->RemoveDeadNode(Node);5346return;5347}5348if (matchBitExtract(Node))5349return;5350if (AndImmShrink && shrinkAndImmediate(Node))5351return;53525353[[fallthrough]];5354case ISD::OR:5355case ISD::XOR:5356if (tryShrinkShlLogicImm(Node))5357return;5358if (Opcode == ISD::OR && tryMatchBitSelect(Node))5359return;5360if (tryVPTERNLOG(Node))5361return;53625363[[fallthrough]];5364case ISD::ADD:5365if (Opcode == ISD::ADD && matchBitExtract(Node))5366return;5367[[fallthrough]];5368case ISD::SUB: {5369// Try to avoid folding immediates with multiple uses for optsize.5370// This code tries to select to register form directly to avoid going5371// through the isel table which might fold the immediate. We can't change5372// the patterns on the add/sub/and/or/xor with immediate paterns in the5373// tablegen files to check immediate use count without making the patterns5374// unavailable to the fast-isel table.5375if (!CurDAG->shouldOptForSize())5376break;53775378// Only handle i8/i16/i32/i64.5379if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64)5380break;53815382SDValue N0 = Node->getOperand(0);5383SDValue N1 = Node->getOperand(1);53845385auto *Cst = dyn_cast<ConstantSDNode>(N1);5386if (!Cst)5387break;53885389int64_t Val = Cst->getSExtValue();53905391// Make sure its an immediate that is considered foldable.5392// FIXME: Handle unsigned 32 bit immediates for 64-bit AND.5393if (!isInt<8>(Val) && !isInt<32>(Val))5394break;53955396// If this can match to INC/DEC, let it go.5397if (Opcode == ISD::ADD && (Val == 1 || Val == -1))5398break;53995400// Check if we should avoid folding this immediate.5401if (!shouldAvoidImmediateInstFormsForSize(N1.getNode()))5402break;54035404// We should not fold the immediate. So we need a register form instead.5405unsigned ROpc, MOpc;5406switch (NVT.SimpleTy) {5407default: llvm_unreachable("Unexpected VT!");5408case MVT::i8:5409switch (Opcode) {5410default: llvm_unreachable("Unexpected opcode!");5411case ISD::ADD:5412ROpc = GET_ND_IF_ENABLED(X86::ADD8rr);5413MOpc = GET_ND_IF_ENABLED(X86::ADD8rm);5414break;5415case ISD::SUB:5416ROpc = GET_ND_IF_ENABLED(X86::SUB8rr);5417MOpc = GET_ND_IF_ENABLED(X86::SUB8rm);5418break;5419case ISD::AND:5420ROpc = GET_ND_IF_ENABLED(X86::AND8rr);5421MOpc = GET_ND_IF_ENABLED(X86::AND8rm);5422break;5423case ISD::OR:5424ROpc = GET_ND_IF_ENABLED(X86::OR8rr);5425MOpc = GET_ND_IF_ENABLED(X86::OR8rm);5426break;5427case ISD::XOR:5428ROpc = GET_ND_IF_ENABLED(X86::XOR8rr);5429MOpc = GET_ND_IF_ENABLED(X86::XOR8rm);5430break;5431}5432break;5433case MVT::i16:5434switch (Opcode) {5435default: llvm_unreachable("Unexpected opcode!");5436case ISD::ADD:5437ROpc = GET_ND_IF_ENABLED(X86::ADD16rr);5438MOpc = GET_ND_IF_ENABLED(X86::ADD16rm);5439break;5440case ISD::SUB:5441ROpc = GET_ND_IF_ENABLED(X86::SUB16rr);5442MOpc = GET_ND_IF_ENABLED(X86::SUB16rm);5443break;5444case ISD::AND:5445ROpc = GET_ND_IF_ENABLED(X86::AND16rr);5446MOpc = GET_ND_IF_ENABLED(X86::AND16rm);5447break;5448case ISD::OR:5449ROpc = GET_ND_IF_ENABLED(X86::OR16rr);5450MOpc = GET_ND_IF_ENABLED(X86::OR16rm);5451break;5452case ISD::XOR:5453ROpc = GET_ND_IF_ENABLED(X86::XOR16rr);5454MOpc = GET_ND_IF_ENABLED(X86::XOR16rm);5455break;5456}5457break;5458case MVT::i32:5459switch (Opcode) {5460default: llvm_unreachable("Unexpected opcode!");5461case ISD::ADD:5462ROpc = GET_ND_IF_ENABLED(X86::ADD32rr);5463MOpc = GET_ND_IF_ENABLED(X86::ADD32rm);5464break;5465case ISD::SUB:5466ROpc = GET_ND_IF_ENABLED(X86::SUB32rr);5467MOpc = GET_ND_IF_ENABLED(X86::SUB32rm);5468break;5469case ISD::AND:5470ROpc = GET_ND_IF_ENABLED(X86::AND32rr);5471MOpc = GET_ND_IF_ENABLED(X86::AND32rm);5472break;5473case ISD::OR:5474ROpc = GET_ND_IF_ENABLED(X86::OR32rr);5475MOpc = GET_ND_IF_ENABLED(X86::OR32rm);5476break;5477case ISD::XOR:5478ROpc = GET_ND_IF_ENABLED(X86::XOR32rr);5479MOpc = GET_ND_IF_ENABLED(X86::XOR32rm);5480break;5481}5482break;5483case MVT::i64:5484switch (Opcode) {5485default: llvm_unreachable("Unexpected opcode!");5486case ISD::ADD:5487ROpc = GET_ND_IF_ENABLED(X86::ADD64rr);5488MOpc = GET_ND_IF_ENABLED(X86::ADD64rm);5489break;5490case ISD::SUB:5491ROpc = GET_ND_IF_ENABLED(X86::SUB64rr);5492MOpc = GET_ND_IF_ENABLED(X86::SUB64rm);5493break;5494case ISD::AND:5495ROpc = GET_ND_IF_ENABLED(X86::AND64rr);5496MOpc = GET_ND_IF_ENABLED(X86::AND64rm);5497break;5498case ISD::OR:5499ROpc = GET_ND_IF_ENABLED(X86::OR64rr);5500MOpc = GET_ND_IF_ENABLED(X86::OR64rm);5501break;5502case ISD::XOR:5503ROpc = GET_ND_IF_ENABLED(X86::XOR64rr);5504MOpc = GET_ND_IF_ENABLED(X86::XOR64rm);5505break;5506}5507break;5508}55095510// Ok this is a AND/OR/XOR/ADD/SUB with constant.55115512// If this is a not a subtract, we can still try to fold a load.5513if (Opcode != ISD::SUB) {5514SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;5515if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {5516SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };5517SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);5518MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);5519// Update the chain.5520ReplaceUses(N0.getValue(1), SDValue(CNode, 2));5521// Record the mem-refs5522CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()});5523ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));5524CurDAG->RemoveDeadNode(Node);5525return;5526}5527}55285529CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1);5530return;5531}55325533case X86ISD::SMUL:5534// i16/i32/i64 are handled with isel patterns.5535if (NVT != MVT::i8)5536break;5537[[fallthrough]];5538case X86ISD::UMUL: {5539SDValue N0 = Node->getOperand(0);5540SDValue N1 = Node->getOperand(1);55415542unsigned LoReg, ROpc, MOpc;5543switch (NVT.SimpleTy) {5544default: llvm_unreachable("Unsupported VT!");5545case MVT::i8:5546LoReg = X86::AL;5547ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;5548MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;5549break;5550case MVT::i16:5551LoReg = X86::AX;5552ROpc = X86::MUL16r;5553MOpc = X86::MUL16m;5554break;5555case MVT::i32:5556LoReg = X86::EAX;5557ROpc = X86::MUL32r;5558MOpc = X86::MUL32m;5559break;5560case MVT::i64:5561LoReg = X86::RAX;5562ROpc = X86::MUL64r;5563MOpc = X86::MUL64m;5564break;5565}55665567SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;5568bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);5569// Multiply is commutative.5570if (!FoldedLoad) {5571FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);5572if (FoldedLoad)5573std::swap(N0, N1);5574}55755576SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,5577N0, SDValue()).getValue(1);55785579MachineSDNode *CNode;5580if (FoldedLoad) {5581// i16/i32/i64 use an instruction that produces a low and high result even5582// though only the low result is used.5583SDVTList VTs;5584if (NVT == MVT::i8)5585VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);5586else5587VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);55885589SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),5590InGlue };5591CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);55925593// Update the chain.5594ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));5595// Record the mem-refs5596CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});5597} else {5598// i16/i32/i64 use an instruction that produces a low and high result even5599// though only the low result is used.5600SDVTList VTs;5601if (NVT == MVT::i8)5602VTs = CurDAG->getVTList(NVT, MVT::i32);5603else5604VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);56055606CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InGlue});5607}56085609ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));5610ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));5611CurDAG->RemoveDeadNode(Node);5612return;5613}56145615case ISD::SMUL_LOHI:5616case ISD::UMUL_LOHI: {5617SDValue N0 = Node->getOperand(0);5618SDValue N1 = Node->getOperand(1);56195620unsigned Opc, MOpc;5621unsigned LoReg, HiReg;5622bool IsSigned = Opcode == ISD::SMUL_LOHI;5623bool UseMULX = !IsSigned && Subtarget->hasBMI2();5624bool UseMULXHi = UseMULX && SDValue(Node, 0).use_empty();5625switch (NVT.SimpleTy) {5626default: llvm_unreachable("Unsupported VT!");5627case MVT::i32:5628Opc = UseMULXHi ? X86::MULX32Hrr5629: UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX32rr)5630: IsSigned ? X86::IMUL32r5631: X86::MUL32r;5632MOpc = UseMULXHi ? X86::MULX32Hrm5633: UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX32rm)5634: IsSigned ? X86::IMUL32m5635: X86::MUL32m;5636LoReg = UseMULX ? X86::EDX : X86::EAX;5637HiReg = X86::EDX;5638break;5639case MVT::i64:5640Opc = UseMULXHi ? X86::MULX64Hrr5641: UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX64rr)5642: IsSigned ? X86::IMUL64r5643: X86::MUL64r;5644MOpc = UseMULXHi ? X86::MULX64Hrm5645: UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX64rm)5646: IsSigned ? X86::IMUL64m5647: X86::MUL64m;5648LoReg = UseMULX ? X86::RDX : X86::RAX;5649HiReg = X86::RDX;5650break;5651}56525653SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;5654bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);5655// Multiply is commutative.5656if (!foldedLoad) {5657foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);5658if (foldedLoad)5659std::swap(N0, N1);5660}56615662SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,5663N0, SDValue()).getValue(1);5664SDValue ResHi, ResLo;5665if (foldedLoad) {5666SDValue Chain;5667MachineSDNode *CNode = nullptr;5668SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),5669InGlue };5670if (UseMULXHi) {5671SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);5672CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);5673ResHi = SDValue(CNode, 0);5674Chain = SDValue(CNode, 1);5675} else if (UseMULX) {5676SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other);5677CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);5678ResHi = SDValue(CNode, 0);5679ResLo = SDValue(CNode, 1);5680Chain = SDValue(CNode, 2);5681} else {5682SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);5683CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);5684Chain = SDValue(CNode, 0);5685InGlue = SDValue(CNode, 1);5686}56875688// Update the chain.5689ReplaceUses(N1.getValue(1), Chain);5690// Record the mem-refs5691CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});5692} else {5693SDValue Ops[] = { N1, InGlue };5694if (UseMULXHi) {5695SDVTList VTs = CurDAG->getVTList(NVT);5696SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);5697ResHi = SDValue(CNode, 0);5698} else if (UseMULX) {5699SDVTList VTs = CurDAG->getVTList(NVT, NVT);5700SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);5701ResHi = SDValue(CNode, 0);5702ResLo = SDValue(CNode, 1);5703} else {5704SDVTList VTs = CurDAG->getVTList(MVT::Glue);5705SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);5706InGlue = SDValue(CNode, 0);5707}5708}57095710// Copy the low half of the result, if it is needed.5711if (!SDValue(Node, 0).use_empty()) {5712if (!ResLo) {5713assert(LoReg && "Register for low half is not defined!");5714ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,5715NVT, InGlue);5716InGlue = ResLo.getValue(2);5717}5718ReplaceUses(SDValue(Node, 0), ResLo);5719LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);5720dbgs() << '\n');5721}5722// Copy the high half of the result, if it is needed.5723if (!SDValue(Node, 1).use_empty()) {5724if (!ResHi) {5725assert(HiReg && "Register for high half is not defined!");5726ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,5727NVT, InGlue);5728InGlue = ResHi.getValue(2);5729}5730ReplaceUses(SDValue(Node, 1), ResHi);5731LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);5732dbgs() << '\n');5733}57345735CurDAG->RemoveDeadNode(Node);5736return;5737}57385739case ISD::SDIVREM:5740case ISD::UDIVREM: {5741SDValue N0 = Node->getOperand(0);5742SDValue N1 = Node->getOperand(1);57435744unsigned ROpc, MOpc;5745bool isSigned = Opcode == ISD::SDIVREM;5746if (!isSigned) {5747switch (NVT.SimpleTy) {5748default: llvm_unreachable("Unsupported VT!");5749case MVT::i8: ROpc = X86::DIV8r; MOpc = X86::DIV8m; break;5750case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break;5751case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break;5752case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break;5753}5754} else {5755switch (NVT.SimpleTy) {5756default: llvm_unreachable("Unsupported VT!");5757case MVT::i8: ROpc = X86::IDIV8r; MOpc = X86::IDIV8m; break;5758case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break;5759case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break;5760case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break;5761}5762}57635764unsigned LoReg, HiReg, ClrReg;5765unsigned SExtOpcode;5766switch (NVT.SimpleTy) {5767default: llvm_unreachable("Unsupported VT!");5768case MVT::i8:5769LoReg = X86::AL; ClrReg = HiReg = X86::AH;5770SExtOpcode = 0; // Not used.5771break;5772case MVT::i16:5773LoReg = X86::AX; HiReg = X86::DX;5774ClrReg = X86::DX;5775SExtOpcode = X86::CWD;5776break;5777case MVT::i32:5778LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;5779SExtOpcode = X86::CDQ;5780break;5781case MVT::i64:5782LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;5783SExtOpcode = X86::CQO;5784break;5785}57865787SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;5788bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);5789bool signBitIsZero = CurDAG->SignBitIsZero(N0);57905791SDValue InGlue;5792if (NVT == MVT::i8) {5793// Special case for div8, just use a move with zero extension to AX to5794// clear the upper 8 bits (AH).5795SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;5796MachineSDNode *Move;5797if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {5798SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };5799unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm85800: X86::MOVZX16rm8;5801Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops);5802Chain = SDValue(Move, 1);5803ReplaceUses(N0.getValue(1), Chain);5804// Record the mem-refs5805CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});5806} else {5807unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr85808: X86::MOVZX16rr8;5809Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0);5810Chain = CurDAG->getEntryNode();5811}5812Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0),5813SDValue());5814InGlue = Chain.getValue(1);5815} else {5816InGlue =5817CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,5818LoReg, N0, SDValue()).getValue(1);5819if (isSigned && !signBitIsZero) {5820// Sign extend the low part into the high part.5821InGlue =5822SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InGlue),0);5823} else {5824// Zero out the high part, effectively zero extending the input.5825SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);5826SDValue ClrNode = SDValue(5827CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0);5828switch (NVT.SimpleTy) {5829case MVT::i16:5830ClrNode =5831SDValue(CurDAG->getMachineNode(5832TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,5833CurDAG->getTargetConstant(X86::sub_16bit, dl,5834MVT::i32)),58350);5836break;5837case MVT::i32:5838break;5839case MVT::i64:5840ClrNode =5841SDValue(CurDAG->getMachineNode(5842TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,5843CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,5844CurDAG->getTargetConstant(X86::sub_32bit, dl,5845MVT::i32)),58460);5847break;5848default:5849llvm_unreachable("Unexpected division source");5850}58515852InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,5853ClrNode, InGlue).getValue(1);5854}5855}58565857if (foldedLoad) {5858SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),5859InGlue };5860MachineSDNode *CNode =5861CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);5862InGlue = SDValue(CNode, 1);5863// Update the chain.5864ReplaceUses(N1.getValue(1), SDValue(CNode, 0));5865// Record the mem-refs5866CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});5867} else {5868InGlue =5869SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InGlue), 0);5870}58715872// Prevent use of AH in a REX instruction by explicitly copying it to5873// an ABCD_L register.5874//5875// The current assumption of the register allocator is that isel5876// won't generate explicit references to the GR8_ABCD_H registers. If5877// the allocator and/or the backend get enhanced to be more robust in5878// that regard, this can be, and should be, removed.5879if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {5880SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);5881unsigned AHExtOpcode =5882isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;58835884SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,5885MVT::Glue, AHCopy, InGlue);5886SDValue Result(RNode, 0);5887InGlue = SDValue(RNode, 1);58885889Result =5890CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);58915892ReplaceUses(SDValue(Node, 1), Result);5893LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);5894dbgs() << '\n');5895}5896// Copy the division (low) result, if it is needed.5897if (!SDValue(Node, 0).use_empty()) {5898SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,5899LoReg, NVT, InGlue);5900InGlue = Result.getValue(2);5901ReplaceUses(SDValue(Node, 0), Result);5902LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);5903dbgs() << '\n');5904}5905// Copy the remainder (high) result, if it is needed.5906if (!SDValue(Node, 1).use_empty()) {5907SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,5908HiReg, NVT, InGlue);5909InGlue = Result.getValue(2);5910ReplaceUses(SDValue(Node, 1), Result);5911LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);5912dbgs() << '\n');5913}5914CurDAG->RemoveDeadNode(Node);5915return;5916}59175918case X86ISD::FCMP:5919case X86ISD::STRICT_FCMP:5920case X86ISD::STRICT_FCMPS: {5921bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP ||5922Node->getOpcode() == X86ISD::STRICT_FCMPS;5923SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0);5924SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1);59255926// Save the original VT of the compare.5927MVT CmpVT = N0.getSimpleValueType();59285929// Floating point needs special handling if we don't have FCOMI.5930if (Subtarget->canUseCMOV())5931break;59325933bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS;59345935unsigned Opc;5936switch (CmpVT.SimpleTy) {5937default: llvm_unreachable("Unexpected type!");5938case MVT::f32:5939Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32;5940break;5941case MVT::f64:5942Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64;5943break;5944case MVT::f80:5945Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80;5946break;5947}59485949SDValue Chain =5950IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode();5951SDValue Glue;5952if (IsStrictCmp) {5953SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);5954Chain = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0);5955Glue = Chain.getValue(1);5956} else {5957Glue = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N0, N1), 0);5958}59595960// Move FPSW to AX.5961SDValue FNSTSW =5962SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, Glue), 0);59635964// Extract upper 8-bits of AX.5965SDValue Extract =5966CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW);59675968// Move AH into flags.5969// Some 64-bit targets lack SAHF support, but they do support FCOMI.5970assert(Subtarget->canUseLAHFSAHF() &&5971"Target doesn't support SAHF or FCOMI?");5972SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue());5973Chain = AH;5974SDValue SAHF = SDValue(5975CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0);59765977if (IsStrictCmp)5978ReplaceUses(SDValue(Node, 1), Chain);59795980ReplaceUses(SDValue(Node, 0), SAHF);5981CurDAG->RemoveDeadNode(Node);5982return;5983}59845985case X86ISD::CMP: {5986SDValue N0 = Node->getOperand(0);5987SDValue N1 = Node->getOperand(1);59885989// Optimizations for TEST compares.5990if (!isNullConstant(N1))5991break;59925993// Save the original VT of the compare.5994MVT CmpVT = N0.getSimpleValueType();59955996// If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed5997// by a test instruction. The test should be removed later by5998// analyzeCompare if we are using only the zero flag.5999// TODO: Should we check the users and use the BEXTR flags directly?6000if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {6001if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {6002unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr6003: X86::TEST32rr;6004SDValue BEXTR = SDValue(NewNode, 0);6005NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);6006ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));6007CurDAG->RemoveDeadNode(Node);6008return;6009}6010}60116012// We can peek through truncates, but we need to be careful below.6013if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())6014N0 = N0.getOperand(0);60156016// Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to6017// use a smaller encoding.6018// Look past the truncate if CMP is the only use of it.6019if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&6020N0.getValueType() != MVT::i8) {6021auto *MaskC = dyn_cast<ConstantSDNode>(N0.getOperand(1));6022if (!MaskC)6023break;60246025// We may have looked through a truncate so mask off any bits that6026// shouldn't be part of the compare.6027uint64_t Mask = MaskC->getZExtValue();6028Mask &= maskTrailingOnes<uint64_t>(CmpVT.getScalarSizeInBits());60296030// Check if we can replace AND+IMM{32,64} with a shift. This is possible6031// for masks like 0xFF000000 or 0x00FFFFFF and if we care only about the6032// zero flag.6033if (CmpVT == MVT::i64 && !isInt<8>(Mask) && isShiftedMask_64(Mask) &&6034onlyUsesZeroFlag(SDValue(Node, 0))) {6035unsigned ShiftOpcode = ISD::DELETED_NODE;6036unsigned ShiftAmt;6037unsigned SubRegIdx;6038MVT SubRegVT;6039unsigned TestOpcode;6040unsigned LeadingZeros = llvm::countl_zero(Mask);6041unsigned TrailingZeros = llvm::countr_zero(Mask);60426043// With leading/trailing zeros, the transform is profitable if we can6044// eliminate a movabsq or shrink a 32-bit immediate to 8-bit without6045// incurring any extra register moves.6046bool SavesBytes = !isInt<32>(Mask) || N0.getOperand(0).hasOneUse();6047if (LeadingZeros == 0 && SavesBytes) {6048// If the mask covers the most significant bit, then we can replace6049// TEST+AND with a SHR and check eflags.6050// This emits a redundant TEST which is subsequently eliminated.6051ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);6052ShiftAmt = TrailingZeros;6053SubRegIdx = 0;6054TestOpcode = X86::TEST64rr;6055} else if (TrailingZeros == 0 && SavesBytes) {6056// If the mask covers the least significant bit, then we can replace6057// TEST+AND with a SHL and check eflags.6058// This emits a redundant TEST which is subsequently eliminated.6059ShiftOpcode = GET_ND_IF_ENABLED(X86::SHL64ri);6060ShiftAmt = LeadingZeros;6061SubRegIdx = 0;6062TestOpcode = X86::TEST64rr;6063} else if (MaskC->hasOneUse() && !isInt<32>(Mask)) {6064// If the shifted mask extends into the high half and is 8/16/32 bits6065// wide, then replace it with a SHR and a TEST8rr/TEST16rr/TEST32rr.6066unsigned PopCount = 64 - LeadingZeros - TrailingZeros;6067if (PopCount == 8) {6068ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);6069ShiftAmt = TrailingZeros;6070SubRegIdx = X86::sub_8bit;6071SubRegVT = MVT::i8;6072TestOpcode = X86::TEST8rr;6073} else if (PopCount == 16) {6074ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);6075ShiftAmt = TrailingZeros;6076SubRegIdx = X86::sub_16bit;6077SubRegVT = MVT::i16;6078TestOpcode = X86::TEST16rr;6079} else if (PopCount == 32) {6080ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);6081ShiftAmt = TrailingZeros;6082SubRegIdx = X86::sub_32bit;6083SubRegVT = MVT::i32;6084TestOpcode = X86::TEST32rr;6085}6086}6087if (ShiftOpcode != ISD::DELETED_NODE) {6088SDValue ShiftC = CurDAG->getTargetConstant(ShiftAmt, dl, MVT::i64);6089SDValue Shift = SDValue(6090CurDAG->getMachineNode(ShiftOpcode, dl, MVT::i64, MVT::i32,6091N0.getOperand(0), ShiftC),60920);6093if (SubRegIdx != 0) {6094Shift =6095CurDAG->getTargetExtractSubreg(SubRegIdx, dl, SubRegVT, Shift);6096}6097MachineSDNode *Test =6098CurDAG->getMachineNode(TestOpcode, dl, MVT::i32, Shift, Shift);6099ReplaceNode(Node, Test);6100return;6101}6102}61036104MVT VT;6105int SubRegOp;6106unsigned ROpc, MOpc;61076108// For each of these checks we need to be careful if the sign flag is6109// being used. It is only safe to use the sign flag in two conditions,6110// either the sign bit in the shrunken mask is zero or the final test6111// size is equal to the original compare size.61126113if (isUInt<8>(Mask) &&6114(!(Mask & 0x80) || CmpVT == MVT::i8 ||6115hasNoSignFlagUses(SDValue(Node, 0)))) {6116// For example, convert "testl %eax, $8" to "testb %al, $8"6117VT = MVT::i8;6118SubRegOp = X86::sub_8bit;6119ROpc = X86::TEST8ri;6120MOpc = X86::TEST8mi;6121} else if (OptForMinSize && isUInt<16>(Mask) &&6122(!(Mask & 0x8000) || CmpVT == MVT::i16 ||6123hasNoSignFlagUses(SDValue(Node, 0)))) {6124// For example, "testl %eax, $32776" to "testw %ax, $32776".6125// NOTE: We only want to form TESTW instructions if optimizing for6126// min size. Otherwise we only save one byte and possibly get a length6127// changing prefix penalty in the decoders.6128VT = MVT::i16;6129SubRegOp = X86::sub_16bit;6130ROpc = X86::TEST16ri;6131MOpc = X86::TEST16mi;6132} else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&6133((!(Mask & 0x80000000) &&6134// Without minsize 16-bit Cmps can get here so we need to6135// be sure we calculate the correct sign flag if needed.6136(CmpVT != MVT::i16 || !(Mask & 0x8000))) ||6137CmpVT == MVT::i32 ||6138hasNoSignFlagUses(SDValue(Node, 0)))) {6139// For example, "testq %rax, $268468232" to "testl %eax, $268468232".6140// NOTE: We only want to run that transform if N0 is 32 or 64 bits.6141// Otherwize, we find ourselves in a position where we have to do6142// promotion. If previous passes did not promote the and, we assume6143// they had a good reason not to and do not promote here.6144VT = MVT::i32;6145SubRegOp = X86::sub_32bit;6146ROpc = X86::TEST32ri;6147MOpc = X86::TEST32mi;6148} else {6149// No eligible transformation was found.6150break;6151}61526153SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);6154SDValue Reg = N0.getOperand(0);61556156// Emit a testl or testw.6157MachineSDNode *NewNode;6158SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;6159if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {6160if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) {6161if (!LoadN->isSimple()) {6162unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits();6163if ((MOpc == X86::TEST8mi && NumVolBits != 8) ||6164(MOpc == X86::TEST16mi && NumVolBits != 16) ||6165(MOpc == X86::TEST32mi && NumVolBits != 32))6166break;6167}6168}6169SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,6170Reg.getOperand(0) };6171NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);6172// Update the chain.6173ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));6174// Record the mem-refs6175CurDAG->setNodeMemRefs(NewNode,6176{cast<LoadSDNode>(Reg)->getMemOperand()});6177} else {6178// Extract the subregister if necessary.6179if (N0.getValueType() != VT)6180Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);61816182NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);6183}6184// Replace CMP with TEST.6185ReplaceNode(Node, NewNode);6186return;6187}6188break;6189}6190case X86ISD::PCMPISTR: {6191if (!Subtarget->hasSSE42())6192break;61936194bool NeedIndex = !SDValue(Node, 0).use_empty();6195bool NeedMask = !SDValue(Node, 1).use_empty();6196// We can't fold a load if we are going to make two instructions.6197bool MayFoldLoad = !NeedIndex || !NeedMask;61986199MachineSDNode *CNode;6200if (NeedMask) {6201unsigned ROpc =6202Subtarget->hasAVX() ? X86::VPCMPISTRMrri : X86::PCMPISTRMrri;6203unsigned MOpc =6204Subtarget->hasAVX() ? X86::VPCMPISTRMrmi : X86::PCMPISTRMrmi;6205CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);6206ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));6207}6208if (NeedIndex || !NeedMask) {6209unsigned ROpc =6210Subtarget->hasAVX() ? X86::VPCMPISTRIrri : X86::PCMPISTRIrri;6211unsigned MOpc =6212Subtarget->hasAVX() ? X86::VPCMPISTRIrmi : X86::PCMPISTRIrmi;6213CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);6214ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));6215}62166217// Connect the flag usage to the last instruction created.6218ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));6219CurDAG->RemoveDeadNode(Node);6220return;6221}6222case X86ISD::PCMPESTR: {6223if (!Subtarget->hasSSE42())6224break;62256226// Copy the two implicit register inputs.6227SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,6228Node->getOperand(1),6229SDValue()).getValue(1);6230InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,6231Node->getOperand(3), InGlue).getValue(1);62326233bool NeedIndex = !SDValue(Node, 0).use_empty();6234bool NeedMask = !SDValue(Node, 1).use_empty();6235// We can't fold a load if we are going to make two instructions.6236bool MayFoldLoad = !NeedIndex || !NeedMask;62376238MachineSDNode *CNode;6239if (NeedMask) {6240unsigned ROpc =6241Subtarget->hasAVX() ? X86::VPCMPESTRMrri : X86::PCMPESTRMrri;6242unsigned MOpc =6243Subtarget->hasAVX() ? X86::VPCMPESTRMrmi : X86::PCMPESTRMrmi;6244CNode =6245emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node, InGlue);6246ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));6247}6248if (NeedIndex || !NeedMask) {6249unsigned ROpc =6250Subtarget->hasAVX() ? X86::VPCMPESTRIrri : X86::PCMPESTRIrri;6251unsigned MOpc =6252Subtarget->hasAVX() ? X86::VPCMPESTRIrmi : X86::PCMPESTRIrmi;6253CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InGlue);6254ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));6255}6256// Connect the flag usage to the last instruction created.6257ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));6258CurDAG->RemoveDeadNode(Node);6259return;6260}62616262case ISD::SETCC: {6263if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))6264return;62656266break;6267}62686269case ISD::STORE:6270if (foldLoadStoreIntoMemOperand(Node))6271return;6272break;62736274case X86ISD::SETCC_CARRY: {6275MVT VT = Node->getSimpleValueType(0);6276SDValue Result;6277if (Subtarget->hasSBBDepBreaking()) {6278// We have to do this manually because tblgen will put the eflags copy in6279// the wrong place if we use an extract_subreg in the pattern.6280// Copy flags to the EFLAGS register and glue it to next node.6281SDValue EFLAGS =6282CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,6283Node->getOperand(1), SDValue());62846285// Create a 64-bit instruction if the result is 64-bits otherwise use the6286// 32-bit version.6287unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r;6288MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;6289Result = SDValue(6290CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)),62910);6292} else {6293// The target does not recognize sbb with the same reg operand as a6294// no-source idiom, so we explicitly zero the input values.6295Result = getSBBZero(Node);6296}62976298// For less than 32-bits we need to extract from the 32-bit node.6299if (VT == MVT::i8 || VT == MVT::i16) {6300int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;6301Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);6302}63036304ReplaceUses(SDValue(Node, 0), Result);6305CurDAG->RemoveDeadNode(Node);6306return;6307}6308case X86ISD::SBB: {6309if (isNullConstant(Node->getOperand(0)) &&6310isNullConstant(Node->getOperand(1))) {6311SDValue Result = getSBBZero(Node);63126313// Replace the flag use.6314ReplaceUses(SDValue(Node, 1), Result.getValue(1));63156316// Replace the result use.6317if (!SDValue(Node, 0).use_empty()) {6318// For less than 32-bits we need to extract from the 32-bit node.6319MVT VT = Node->getSimpleValueType(0);6320if (VT == MVT::i8 || VT == MVT::i16) {6321int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;6322Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);6323}6324ReplaceUses(SDValue(Node, 0), Result);6325}63266327CurDAG->RemoveDeadNode(Node);6328return;6329}6330break;6331}6332case X86ISD::MGATHER: {6333auto *Mgt = cast<X86MaskedGatherSDNode>(Node);6334SDValue IndexOp = Mgt->getIndex();6335SDValue Mask = Mgt->getMask();6336MVT IndexVT = IndexOp.getSimpleValueType();6337MVT ValueVT = Node->getSimpleValueType(0);6338MVT MaskVT = Mask.getSimpleValueType();63396340// This is just to prevent crashes if the nodes are malformed somehow. We're6341// otherwise only doing loose type checking in here based on type what6342// a type constraint would say just like table based isel.6343if (!ValueVT.isVector() || !MaskVT.isVector())6344break;63456346unsigned NumElts = ValueVT.getVectorNumElements();6347MVT ValueSVT = ValueVT.getVectorElementType();63486349bool IsFP = ValueSVT.isFloatingPoint();6350unsigned EltSize = ValueSVT.getSizeInBits();63516352unsigned Opc = 0;6353bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1;6354if (AVX512Gather) {6355if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)6356Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm;6357else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)6358Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm;6359else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)6360Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm;6361else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)6362Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm;6363else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)6364Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm;6365else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)6366Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm;6367else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)6368Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm;6369else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)6370Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm;6371else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)6372Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm;6373else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)6374Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm;6375else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)6376Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm;6377else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)6378Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm;6379} else {6380assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() &&6381"Unexpected mask VT!");6382if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)6383Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm;6384else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)6385Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm;6386else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)6387Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm;6388else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)6389Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm;6390else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)6391Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm;6392else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)6393Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm;6394else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)6395Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm;6396else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)6397Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm;6398}63996400if (!Opc)6401break;64026403SDValue Base, Scale, Index, Disp, Segment;6404if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(),6405Base, Scale, Index, Disp, Segment))6406break;64076408SDValue PassThru = Mgt->getPassThru();6409SDValue Chain = Mgt->getChain();6410// Gather instructions have a mask output not in the ISD node.6411SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other);64126413MachineSDNode *NewNode;6414if (AVX512Gather) {6415SDValue Ops[] = {PassThru, Mask, Base, Scale,6416Index, Disp, Segment, Chain};6417NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);6418} else {6419SDValue Ops[] = {PassThru, Base, Scale, Index,6420Disp, Segment, Mask, Chain};6421NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);6422}6423CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()});6424ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));6425ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2));6426CurDAG->RemoveDeadNode(Node);6427return;6428}6429case X86ISD::MSCATTER: {6430auto *Sc = cast<X86MaskedScatterSDNode>(Node);6431SDValue Value = Sc->getValue();6432SDValue IndexOp = Sc->getIndex();6433MVT IndexVT = IndexOp.getSimpleValueType();6434MVT ValueVT = Value.getSimpleValueType();64356436// This is just to prevent crashes if the nodes are malformed somehow. We're6437// otherwise only doing loose type checking in here based on type what6438// a type constraint would say just like table based isel.6439if (!ValueVT.isVector())6440break;64416442unsigned NumElts = ValueVT.getVectorNumElements();6443MVT ValueSVT = ValueVT.getVectorElementType();64446445bool IsFP = ValueSVT.isFloatingPoint();6446unsigned EltSize = ValueSVT.getSizeInBits();64476448unsigned Opc;6449if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)6450Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr;6451else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)6452Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr;6453else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)6454Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr;6455else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)6456Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr;6457else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)6458Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr;6459else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)6460Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr;6461else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)6462Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr;6463else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)6464Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr;6465else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)6466Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr;6467else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)6468Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr;6469else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)6470Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr;6471else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)6472Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr;6473else6474break;64756476SDValue Base, Scale, Index, Disp, Segment;6477if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(),6478Base, Scale, Index, Disp, Segment))6479break;64806481SDValue Mask = Sc->getMask();6482SDValue Chain = Sc->getChain();6483// Scatter instructions have a mask output not in the ISD node.6484SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other);6485SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain};64866487MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);6488CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()});6489ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1));6490CurDAG->RemoveDeadNode(Node);6491return;6492}6493case ISD::PREALLOCATED_SETUP: {6494auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();6495auto CallId = MFI->getPreallocatedIdForCallSite(6496cast<SrcValueSDNode>(Node->getOperand(1))->getValue());6497SDValue Chain = Node->getOperand(0);6498SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);6499MachineSDNode *New = CurDAG->getMachineNode(6500TargetOpcode::PREALLOCATED_SETUP, dl, MVT::Other, CallIdValue, Chain);6501ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Chain6502CurDAG->RemoveDeadNode(Node);6503return;6504}6505case ISD::PREALLOCATED_ARG: {6506auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();6507auto CallId = MFI->getPreallocatedIdForCallSite(6508cast<SrcValueSDNode>(Node->getOperand(1))->getValue());6509SDValue Chain = Node->getOperand(0);6510SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);6511SDValue ArgIndex = Node->getOperand(2);6512SDValue Ops[3];6513Ops[0] = CallIdValue;6514Ops[1] = ArgIndex;6515Ops[2] = Chain;6516MachineSDNode *New = CurDAG->getMachineNode(6517TargetOpcode::PREALLOCATED_ARG, dl,6518CurDAG->getVTList(TLI->getPointerTy(CurDAG->getDataLayout()),6519MVT::Other),6520Ops);6521ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Arg pointer6522ReplaceUses(SDValue(Node, 1), SDValue(New, 1)); // Chain6523CurDAG->RemoveDeadNode(Node);6524return;6525}6526case X86ISD::AESENCWIDE128KL:6527case X86ISD::AESDECWIDE128KL:6528case X86ISD::AESENCWIDE256KL:6529case X86ISD::AESDECWIDE256KL: {6530if (!Subtarget->hasWIDEKL())6531break;65326533unsigned Opcode;6534switch (Node->getOpcode()) {6535default:6536llvm_unreachable("Unexpected opcode!");6537case X86ISD::AESENCWIDE128KL:6538Opcode = X86::AESENCWIDE128KL;6539break;6540case X86ISD::AESDECWIDE128KL:6541Opcode = X86::AESDECWIDE128KL;6542break;6543case X86ISD::AESENCWIDE256KL:6544Opcode = X86::AESENCWIDE256KL;6545break;6546case X86ISD::AESDECWIDE256KL:6547Opcode = X86::AESDECWIDE256KL;6548break;6549}65506551SDValue Chain = Node->getOperand(0);6552SDValue Addr = Node->getOperand(1);65536554SDValue Base, Scale, Index, Disp, Segment;6555if (!selectAddr(Node, Addr, Base, Scale, Index, Disp, Segment))6556break;65576558Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(2),6559SDValue());6560Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(3),6561Chain.getValue(1));6562Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM2, Node->getOperand(4),6563Chain.getValue(1));6564Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM3, Node->getOperand(5),6565Chain.getValue(1));6566Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM4, Node->getOperand(6),6567Chain.getValue(1));6568Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM5, Node->getOperand(7),6569Chain.getValue(1));6570Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM6, Node->getOperand(8),6571Chain.getValue(1));6572Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM7, Node->getOperand(9),6573Chain.getValue(1));65746575MachineSDNode *Res = CurDAG->getMachineNode(6576Opcode, dl, Node->getVTList(),6577{Base, Scale, Index, Disp, Segment, Chain, Chain.getValue(1)});6578CurDAG->setNodeMemRefs(Res, cast<MemSDNode>(Node)->getMemOperand());6579ReplaceNode(Node, Res);6580return;6581}6582}65836584SelectCode(Node);6585}65866587bool X86DAGToDAGISel::SelectInlineAsmMemoryOperand(6588const SDValue &Op, InlineAsm::ConstraintCode ConstraintID,6589std::vector<SDValue> &OutOps) {6590SDValue Op0, Op1, Op2, Op3, Op4;6591switch (ConstraintID) {6592default:6593llvm_unreachable("Unexpected asm memory constraint");6594case InlineAsm::ConstraintCode::o: // offsetable ??6595case InlineAsm::ConstraintCode::v: // not offsetable ??6596case InlineAsm::ConstraintCode::m: // memory6597case InlineAsm::ConstraintCode::X:6598case InlineAsm::ConstraintCode::p: // address6599if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))6600return true;6601break;6602}66036604OutOps.push_back(Op0);6605OutOps.push_back(Op1);6606OutOps.push_back(Op2);6607OutOps.push_back(Op3);6608OutOps.push_back(Op4);6609return false;6610}66116612X86ISelDAGToDAGPass::X86ISelDAGToDAGPass(X86TargetMachine &TM)6613: SelectionDAGISelPass(6614std::make_unique<X86DAGToDAGISel>(TM, TM.getOptLevel())) {}66156616/// This pass converts a legalized DAG into a X86-specific DAG,6617/// ready for instruction scheduling.6618FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,6619CodeGenOptLevel OptLevel) {6620return new X86DAGToDAGISelLegacy(TM, OptLevel);6621}662266236624