1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
42 #define DEBUG_TYPE "x86-isel"
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
51 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52 /// numbers for the leaves of the matched tree.
53 struct X86ISelAddressMode {
59 // This is really a union, discriminated by BaseType!
67 const GlobalValue *GV;
69 const BlockAddress *BlockAddr;
73 unsigned Align; // CP alignment.
74 unsigned char SymbolFlags; // X86II::MO_*
77 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
81 bool hasSymbolicDisplacement() const {
82 return GV != nullptr || CP != nullptr || ES != nullptr ||
83 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
86 bool hasBaseOrIndexReg() const {
87 return BaseType == FrameIndexBase ||
88 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
91 /// Return true if this addressing mode is already RIP-relative.
92 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
95 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
96 return RegNode->getReg() == X86::RIP;
100 void setBaseReg(SDValue Reg) {
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
107 dbgs() << "X86ISelAddressMode " << this << '\n';
108 dbgs() << "Base_Reg ";
109 if (Base_Reg.getNode())
110 Base_Reg.getNode()->dump();
113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114 << " Scale" << Scale << '\n'
116 if (IndexReg.getNode())
117 IndexReg.getNode()->dump();
120 dbgs() << " Disp " << Disp << '\n'
142 dbgs() << " JT" << JT << " Align" << Align << '\n';
149 //===--------------------------------------------------------------------===//
150 /// ISel - X86-specific code to select X86 machine instructions for
151 /// SelectionDAG operations.
153 class X86DAGToDAGISel final : public SelectionDAGISel {
154 /// Keep a pointer to the X86Subtarget around so that we can
155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
158 /// If true, selector should try to optimize for code size instead of
162 /// If true, selector should try to optimize for minimum code size.
166 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
167 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
168 OptForMinSize(false) {}
170 StringRef getPassName() const override {
171 return "X86 DAG->DAG Instruction Selection";
174 bool runOnMachineFunction(MachineFunction &MF) override {
175 // Reset the subtarget each time through.
176 Subtarget = &MF.getSubtarget<X86Subtarget>();
177 SelectionDAGISel::runOnMachineFunction(MF);
181 void EmitFunctionEntryCode() override;
183 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
185 void PreprocessISelDAG() override;
187 // Include the pieces autogenerated from the target description.
188 #include "X86GenDAGISel.inc"
191 void Select(SDNode *N) override;
193 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
197 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
198 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
200 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
202 SDValue &Scale, SDValue &Index, SDValue &Disp,
204 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
205 SDValue &Scale, SDValue &Index, SDValue &Disp,
207 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
208 bool selectLEAAddr(SDValue N, SDValue &Base,
209 SDValue &Scale, SDValue &Index, SDValue &Disp,
211 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
212 SDValue &Scale, SDValue &Index, SDValue &Disp,
214 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
215 SDValue &Scale, SDValue &Index, SDValue &Disp,
217 bool selectScalarSSELoad(SDNode *Root, SDValue N,
218 SDValue &Base, SDValue &Scale,
219 SDValue &Index, SDValue &Disp,
221 SDValue &NodeWithChain);
222 bool selectRelocImm(SDValue N, SDValue &Op);
224 bool tryFoldLoad(SDNode *P, SDValue N,
225 SDValue &Base, SDValue &Scale,
226 SDValue &Index, SDValue &Disp,
229 /// Implement addressing mode selection for inline asm expressions.
230 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
231 unsigned ConstraintID,
232 std::vector<SDValue> &OutOps) override;
234 void emitSpecialCodeForMain();
236 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
237 SDValue &Base, SDValue &Scale,
238 SDValue &Index, SDValue &Disp,
240 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
241 ? CurDAG->getTargetFrameIndex(
243 TLI->getPointerTy(CurDAG->getDataLayout()))
245 Scale = getI8Imm(AM.Scale, DL);
247 // These are 32-bit even in 64-bit mode since RIP-relative offset
250 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
254 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
255 AM.Align, AM.Disp, AM.SymbolFlags);
257 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
258 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
259 } else if (AM.MCSym) {
260 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
261 assert(AM.SymbolFlags == 0 && "oo");
262 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
263 } else if (AM.JT != -1) {
264 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
265 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
266 } else if (AM.BlockAddr)
267 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
270 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
272 if (AM.Segment.getNode())
273 Segment = AM.Segment;
275 Segment = CurDAG->getRegister(0, MVT::i32);
278 // Utility function to determine whether we should avoid selecting
279 // immediate forms of instructions for better code size or not.
280 // At a high level, we'd like to avoid such instructions when
281 // we have similar constants used within the same basic block
282 // that can be kept in a register.
284 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
285 uint32_t UseCount = 0;
287 // Do not want to hoist if we're not optimizing for size.
288 // TODO: We'd like to remove this restriction.
289 // See the comment in X86InstrInfo.td for more info.
293 // Walk all the users of the immediate.
294 for (SDNode::use_iterator UI = N->use_begin(),
295 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
299 // This user is already selected. Count it as a legitimate use and
301 if (User->isMachineOpcode()) {
306 // We want to count stores of immediates as real uses.
307 if (User->getOpcode() == ISD::STORE &&
308 User->getOperand(1).getNode() == N) {
313 // We don't currently match users that have > 2 operands (except
314 // for stores, which are handled above)
315 // Those instruction won't match in ISEL, for now, and would
316 // be counted incorrectly.
317 // This may change in the future as we add additional instruction
319 if (User->getNumOperands() != 2)
322 // Immediates that are used for offsets as part of stack
323 // manipulation should be left alone. These are typically
324 // used to indicate SP offsets for argument passing and
325 // will get pulled into stores/pushes (implicitly).
326 if (User->getOpcode() == X86ISD::ADD ||
327 User->getOpcode() == ISD::ADD ||
328 User->getOpcode() == X86ISD::SUB ||
329 User->getOpcode() == ISD::SUB) {
331 // Find the other operand of the add/sub.
332 SDValue OtherOp = User->getOperand(0);
333 if (OtherOp.getNode() == N)
334 OtherOp = User->getOperand(1);
336 // Don't count if the other operand is SP.
337 RegisterSDNode *RegNode;
338 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
339 (RegNode = dyn_cast_or_null<RegisterSDNode>(
340 OtherOp->getOperand(1).getNode())))
341 if ((RegNode->getReg() == X86::ESP) ||
342 (RegNode->getReg() == X86::RSP))
346 // ... otherwise, count this and move on.
350 // If we have more than 1 use, then recommend for hoisting.
351 return (UseCount > 1);
354 /// Return a target constant with the specified value of type i8.
355 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
356 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
359 /// Return a target constant with the specified value, of type i32.
360 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
361 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
364 /// Return an SDNode that returns the value of the global base register.
365 /// Output instructions required to initialize the global base register,
367 SDNode *getGlobalBaseReg();
369 /// Return a reference to the TargetMachine, casted to the target-specific
371 const X86TargetMachine &getTargetMachine() const {
372 return static_cast<const X86TargetMachine &>(TM);
375 /// Return a reference to the TargetInstrInfo, casted to the target-specific
377 const X86InstrInfo *getInstrInfo() const {
378 return Subtarget->getInstrInfo();
381 /// \brief Address-mode matching performs shift-of-and to and-of-shift
382 /// reassociation in order to expose more scaled addressing
384 bool ComplexPatternFuncMutatesDAG() const override {
388 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
390 /// Returns whether this is a relocatable immediate in the range
391 /// [-2^Width .. 2^Width-1].
392 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
393 if (auto *CN = dyn_cast<ConstantSDNode>(N))
394 return isInt<Width>(CN->getSExtValue());
395 return isSExtAbsoluteSymbolRef(Width, N);
402 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
403 if (OptLevel == CodeGenOpt::None) return false;
408 if (N.getOpcode() != ISD::LOAD)
411 // If N is a load, do additional profitability checks.
413 switch (U->getOpcode()) {
427 SDValue Op1 = U->getOperand(1);
429 // If the other operand is a 8-bit immediate we should fold the immediate
430 // instead. This reduces code size.
432 // movl 4(%esp), %eax
436 // addl 4(%esp), %eax
437 // The former is 2 bytes shorter. In case where the increment is 1, then
438 // the saving can be 4 bytes (by using incl %eax).
439 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
440 if (Imm->getAPIntValue().isSignedIntN(8))
443 // If the other operand is a TLS address, we should fold it instead.
446 // leal i@NTPOFF(%eax), %eax
448 // movl $i@NTPOFF, %eax
450 // if the block also has an access to a second TLS address this will save
452 // FIXME: This is probably also true for non-TLS addresses.
453 if (Op1.getOpcode() == X86ISD::Wrapper) {
454 SDValue Val = Op1.getOperand(0);
455 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
465 /// Replace the original chain operand of the call with
466 /// load's chain operand and move load below the call's chain operand.
467 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
468 SDValue Call, SDValue OrigChain) {
469 SmallVector<SDValue, 8> Ops;
470 SDValue Chain = OrigChain.getOperand(0);
471 if (Chain.getNode() == Load.getNode())
472 Ops.push_back(Load.getOperand(0));
474 assert(Chain.getOpcode() == ISD::TokenFactor &&
475 "Unexpected chain operand");
476 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
477 if (Chain.getOperand(i).getNode() == Load.getNode())
478 Ops.push_back(Load.getOperand(0));
480 Ops.push_back(Chain.getOperand(i));
482 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
484 Ops.push_back(NewChain);
486 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
487 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
488 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
489 Load.getOperand(1), Load.getOperand(2));
492 Ops.push_back(SDValue(Load.getNode(), 1));
493 Ops.append(Call->op_begin() + 1, Call->op_end());
494 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
497 /// Return true if call address is a load and it can be
498 /// moved below CALLSEQ_START and the chains leading up to the call.
499 /// Return the CALLSEQ_START by reference as a second output.
500 /// In the case of a tail call, there isn't a callseq node between the call
501 /// chain and the load.
502 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
503 // The transformation is somewhat dangerous if the call's chain was glued to
504 // the call. After MoveBelowOrigChain the load is moved between the call and
505 // the chain, this can create a cycle if the load is not folded. So it is
506 // *really* important that we are sure the load will be folded.
507 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
509 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
512 LD->getAddressingMode() != ISD::UNINDEXED ||
513 LD->getExtensionType() != ISD::NON_EXTLOAD)
516 // Now let's find the callseq_start.
517 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
518 if (!Chain.hasOneUse())
520 Chain = Chain.getOperand(0);
523 if (!Chain.getNumOperands())
525 // Since we are not checking for AA here, conservatively abort if the chain
526 // writes to memory. It's not safe to move the callee (a load) across a store.
527 if (isa<MemSDNode>(Chain.getNode()) &&
528 cast<MemSDNode>(Chain.getNode())->writeMem())
530 if (Chain.getOperand(0).getNode() == Callee.getNode())
532 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
533 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
534 Callee.getValue(1).hasOneUse())
539 void X86DAGToDAGISel::PreprocessISelDAG() {
540 // OptFor[Min]Size are used in pattern predicates that isel is matching.
541 OptForSize = MF->getFunction()->optForSize();
542 OptForMinSize = MF->getFunction()->optForMinSize();
543 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
545 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
546 E = CurDAG->allnodes_end(); I != E; ) {
547 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
549 if (OptLevel != CodeGenOpt::None &&
550 // Only does this when target favors doesn't favor register indirect
552 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
553 (N->getOpcode() == X86ISD::TC_RETURN &&
554 // Only does this if load can be folded into TC_RETURN.
555 (Subtarget->is64Bit() ||
556 !getTargetMachine().isPositionIndependent())))) {
557 /// Also try moving call address load from outside callseq_start to just
558 /// before the call to allow it to be folded.
576 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
577 SDValue Chain = N->getOperand(0);
578 SDValue Load = N->getOperand(1);
579 if (!isCalleeLoad(Load, Chain, HasCallSeq))
581 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
586 // Lower fpround and fpextend nodes that target the FP stack to be store and
587 // load to the stack. This is a gross hack. We would like to simply mark
588 // these as being illegal, but when we do that, legalize produces these when
589 // it expands calls, then expands these in the same legalize pass. We would
590 // like dag combine to be able to hack on these between the call expansion
591 // and the node legalization. As such this pass basically does "really
592 // late" legalization of these inline with the X86 isel pass.
593 // FIXME: This should only happen when not compiled with -O0.
594 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
597 MVT SrcVT = N->getOperand(0).getSimpleValueType();
598 MVT DstVT = N->getSimpleValueType(0);
600 // If any of the sources are vectors, no fp stack involved.
601 if (SrcVT.isVector() || DstVT.isVector())
604 // If the source and destination are SSE registers, then this is a legal
605 // conversion that should not be lowered.
606 const X86TargetLowering *X86Lowering =
607 static_cast<const X86TargetLowering *>(TLI);
608 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
609 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
610 if (SrcIsSSE && DstIsSSE)
613 if (!SrcIsSSE && !DstIsSSE) {
614 // If this is an FPStack extension, it is a noop.
615 if (N->getOpcode() == ISD::FP_EXTEND)
617 // If this is a value-preserving FPStack truncation, it is a noop.
618 if (N->getConstantOperandVal(1))
622 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
623 // FPStack has extload and truncstore. SSE can fold direct loads into other
624 // operations. Based on this, decide what we want to do.
626 if (N->getOpcode() == ISD::FP_ROUND)
627 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
629 MemVT = SrcIsSSE ? SrcVT : DstVT;
631 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
634 // FIXME: optimize the case where the src/dest is a load or store?
636 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
637 MemTmp, MachinePointerInfo(), MemVT);
638 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
639 MachinePointerInfo(), MemVT);
641 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
642 // extload we created. This will cause general havok on the dag because
643 // anything below the conversion could be folded into other existing nodes.
644 // To avoid invalidating 'I', back it up to the convert node.
646 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
648 // Now that we did that, the node is dead. Increment the iterator to the
649 // next node to process, then delete N.
651 CurDAG->DeleteNode(N);
656 /// Emit any code that needs to be executed only in the main function.
657 void X86DAGToDAGISel::emitSpecialCodeForMain() {
658 if (Subtarget->isTargetCygMing()) {
659 TargetLowering::ArgListTy Args;
660 auto &DL = CurDAG->getDataLayout();
662 TargetLowering::CallLoweringInfo CLI(*CurDAG);
663 CLI.setChain(CurDAG->getRoot())
664 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
665 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
667 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
668 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
669 CurDAG->setRoot(Result.second);
673 void X86DAGToDAGISel::EmitFunctionEntryCode() {
674 // If this is main, emit special code for main.
675 if (const Function *Fn = MF->getFunction())
676 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
677 emitSpecialCodeForMain();
680 static bool isDispSafeForFrameIndex(int64_t Val) {
681 // On 64-bit platforms, we can run into an issue where a frame index
682 // includes a displacement that, when added to the explicit displacement,
683 // will overflow the displacement field. Assuming that the frame index
684 // displacement fits into a 31-bit integer (which is only slightly more
685 // aggressive than the current fundamental assumption that it fits into
686 // a 32-bit integer), a 31-bit disp should always be safe.
687 return isInt<31>(Val);
690 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
691 X86ISelAddressMode &AM) {
692 // Cannot combine ExternalSymbol displacements with integer offsets.
693 if (Offset != 0 && (AM.ES || AM.MCSym))
695 int64_t Val = AM.Disp + Offset;
696 CodeModel::Model M = TM.getCodeModel();
697 if (Subtarget->is64Bit()) {
698 if (!X86::isOffsetSuitableForCodeModel(Val, M,
699 AM.hasSymbolicDisplacement()))
701 // In addition to the checks required for a register base, check that
702 // we do not try to use an unsafe Disp with a frame index.
703 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
704 !isDispSafeForFrameIndex(Val))
712 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
713 SDValue Address = N->getOperand(1);
715 // load gs:0 -> GS segment register.
716 // load fs:0 -> FS segment register.
718 // This optimization is valid because the GNU TLS model defines that
719 // gs:0 (or fs:0 on X86-64) contains its own address.
720 // For more information see http://people.redhat.com/drepper/tls.pdf
721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
722 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
723 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
724 Subtarget->isTargetFuchsia()))
725 switch (N->getPointerInfo().getAddrSpace()) {
727 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
730 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
732 // Address space 258 is not handled here, because it is not used to
733 // address TLS areas.
739 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
740 /// mode. These wrap things that will resolve down into a symbol reference.
741 /// If no match is possible, this returns true, otherwise it returns false.
742 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
743 // If the addressing mode already has a symbol as the displacement, we can
744 // never match another symbol.
745 if (AM.hasSymbolicDisplacement())
748 SDValue N0 = N.getOperand(0);
749 CodeModel::Model M = TM.getCodeModel();
751 // Handle X86-64 rip-relative addresses. We check this before checking direct
752 // folding because RIP is preferable to non-RIP accesses.
753 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
754 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
755 // they cannot be folded into immediate fields.
756 // FIXME: This can be improved for kernel and other models?
757 (M == CodeModel::Small || M == CodeModel::Kernel)) {
758 // Base and index reg must be 0 in order to use %rip as base.
759 if (AM.hasBaseOrIndexReg())
761 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
762 X86ISelAddressMode Backup = AM;
763 AM.GV = G->getGlobal();
764 AM.SymbolFlags = G->getTargetFlags();
765 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
769 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
770 X86ISelAddressMode Backup = AM;
771 AM.CP = CP->getConstVal();
772 AM.Align = CP->getAlignment();
773 AM.SymbolFlags = CP->getTargetFlags();
774 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
778 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
779 AM.ES = S->getSymbol();
780 AM.SymbolFlags = S->getTargetFlags();
781 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
782 AM.MCSym = S->getMCSymbol();
783 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
784 AM.JT = J->getIndex();
785 AM.SymbolFlags = J->getTargetFlags();
786 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
787 X86ISelAddressMode Backup = AM;
788 AM.BlockAddr = BA->getBlockAddress();
789 AM.SymbolFlags = BA->getTargetFlags();
790 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
795 llvm_unreachable("Unhandled symbol reference node.");
797 if (N.getOpcode() == X86ISD::WrapperRIP)
798 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
802 // Handle the case when globals fit in our immediate field: This is true for
803 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
804 // mode, this only applies to a non-RIP-relative computation.
805 if (!Subtarget->is64Bit() ||
806 M == CodeModel::Small || M == CodeModel::Kernel) {
807 assert(N.getOpcode() != X86ISD::WrapperRIP &&
808 "RIP-relative addressing already handled");
809 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
810 AM.GV = G->getGlobal();
811 AM.Disp += G->getOffset();
812 AM.SymbolFlags = G->getTargetFlags();
813 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
814 AM.CP = CP->getConstVal();
815 AM.Align = CP->getAlignment();
816 AM.Disp += CP->getOffset();
817 AM.SymbolFlags = CP->getTargetFlags();
818 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
819 AM.ES = S->getSymbol();
820 AM.SymbolFlags = S->getTargetFlags();
821 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
822 AM.MCSym = S->getMCSymbol();
823 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
824 AM.JT = J->getIndex();
825 AM.SymbolFlags = J->getTargetFlags();
826 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
827 AM.BlockAddr = BA->getBlockAddress();
828 AM.Disp += BA->getOffset();
829 AM.SymbolFlags = BA->getTargetFlags();
831 llvm_unreachable("Unhandled symbol reference node.");
838 /// Add the specified node to the specified addressing mode, returning true if
839 /// it cannot be done. This just pattern matches for the addressing mode.
840 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
841 if (matchAddressRecursively(N, AM, 0))
844 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
845 // a smaller encoding and avoids a scaled-index.
847 AM.BaseType == X86ISelAddressMode::RegBase &&
848 AM.Base_Reg.getNode() == nullptr) {
849 AM.Base_Reg = AM.IndexReg;
853 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
854 // because it has a smaller encoding.
855 // TODO: Which other code models can use this?
856 if (TM.getCodeModel() == CodeModel::Small &&
857 Subtarget->is64Bit() &&
859 AM.BaseType == X86ISelAddressMode::RegBase &&
860 AM.Base_Reg.getNode() == nullptr &&
861 AM.IndexReg.getNode() == nullptr &&
862 AM.SymbolFlags == X86II::MO_NO_FLAG &&
863 AM.hasSymbolicDisplacement())
864 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
869 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
871 // Add an artificial use to this node so that we can keep track of
872 // it if it gets CSE'd with a different node.
873 HandleSDNode Handle(N);
875 X86ISelAddressMode Backup = AM;
876 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
877 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
881 // Try again after commuting the operands.
882 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
883 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
887 // If we couldn't fold both operands into the address at the same time,
888 // see if we can just put each operand into a register and fold at least
890 if (AM.BaseType == X86ISelAddressMode::RegBase &&
891 !AM.Base_Reg.getNode() &&
892 !AM.IndexReg.getNode()) {
893 N = Handle.getValue();
894 AM.Base_Reg = N.getOperand(0);
895 AM.IndexReg = N.getOperand(1);
899 N = Handle.getValue();
903 // Insert a node into the DAG at least before the Pos node's position. This
904 // will reposition the node as needed, and will assign it a node ID that is <=
905 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
906 // IDs! The selection DAG must no longer depend on their uniqueness when this
908 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
909 if (N.getNode()->getNodeId() == -1 ||
910 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
911 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
912 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
916 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
917 // safe. This allows us to convert the shift and and into an h-register
918 // extract and a scaled index. Returns false if the simplification is
920 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
922 SDValue Shift, SDValue X,
923 X86ISelAddressMode &AM) {
924 if (Shift.getOpcode() != ISD::SRL ||
925 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
929 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
930 if (ScaleLog <= 0 || ScaleLog >= 4 ||
931 Mask != (0xffu << ScaleLog))
934 MVT VT = N.getSimpleValueType();
936 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
937 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
938 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
939 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
940 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
941 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
943 // Insert the new nodes into the topological ordering. We must do this in
944 // a valid topological ordering as nothing is going to go back and re-sort
945 // these nodes. We continually insert before 'N' in sequence as this is
946 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
947 // hierarchy left to express.
948 insertDAGNode(DAG, N, Eight);
949 insertDAGNode(DAG, N, Srl);
950 insertDAGNode(DAG, N, NewMask);
951 insertDAGNode(DAG, N, And);
952 insertDAGNode(DAG, N, ShlCount);
953 insertDAGNode(DAG, N, Shl);
954 DAG.ReplaceAllUsesWith(N, Shl);
956 AM.Scale = (1 << ScaleLog);
960 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
961 // allows us to fold the shift into this addressing mode. Returns false if the
962 // transform succeeded.
963 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
965 SDValue Shift, SDValue X,
966 X86ISelAddressMode &AM) {
967 if (Shift.getOpcode() != ISD::SHL ||
968 !isa<ConstantSDNode>(Shift.getOperand(1)))
971 // Not likely to be profitable if either the AND or SHIFT node has more
972 // than one use (unless all uses are for address computation). Besides,
973 // isel mechanism requires their node ids to be reused.
974 if (!N.hasOneUse() || !Shift.hasOneUse())
977 // Verify that the shift amount is something we can fold.
978 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
979 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
982 MVT VT = N.getSimpleValueType();
984 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
985 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
986 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
988 // Insert the new nodes into the topological ordering. We must do this in
989 // a valid topological ordering as nothing is going to go back and re-sort
990 // these nodes. We continually insert before 'N' in sequence as this is
991 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
992 // hierarchy left to express.
993 insertDAGNode(DAG, N, NewMask);
994 insertDAGNode(DAG, N, NewAnd);
995 insertDAGNode(DAG, N, NewShift);
996 DAG.ReplaceAllUsesWith(N, NewShift);
998 AM.Scale = 1 << ShiftAmt;
999 AM.IndexReg = NewAnd;
1003 // Implement some heroics to detect shifts of masked values where the mask can
1004 // be replaced by extending the shift and undoing that in the addressing mode
1005 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1006 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1007 // the addressing mode. This results in code such as:
1009 // int f(short *y, int *lookup_table) {
1011 // return *y + lookup_table[*y >> 11];
1015 // movzwl (%rdi), %eax
1018 // addl (%rsi,%rcx,4), %eax
1021 // movzwl (%rdi), %eax
1025 // addl (%rsi,%rcx), %eax
1027 // Note that this function assumes the mask is provided as a mask *after* the
1028 // value is shifted. The input chain may or may not match that, but computing
1029 // such a mask is trivial.
1030 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1032 SDValue Shift, SDValue X,
1033 X86ISelAddressMode &AM) {
1034 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1035 !isa<ConstantSDNode>(Shift.getOperand(1)))
1038 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1039 unsigned MaskLZ = countLeadingZeros(Mask);
1040 unsigned MaskTZ = countTrailingZeros(Mask);
1042 // The amount of shift we're trying to fit into the addressing mode is taken
1043 // from the trailing zeros of the mask.
1044 unsigned AMShiftAmt = MaskTZ;
1046 // There is nothing we can do here unless the mask is removing some bits.
1047 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1048 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1050 // We also need to ensure that mask is a continuous run of bits.
1051 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1053 // Scale the leading zero count down based on the actual size of the value.
1054 // Also scale it down based on the size of the shift.
1055 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1057 // The final check is to ensure that any masked out high bits of X are
1058 // already known to be zero. Otherwise, the mask has a semantic impact
1059 // other than masking out a couple of low bits. Unfortunately, because of
1060 // the mask, zero extensions will be removed from operands in some cases.
1061 // This code works extra hard to look through extensions because we can
1062 // replace them with zero extensions cheaply if necessary.
1063 bool ReplacingAnyExtend = false;
1064 if (X.getOpcode() == ISD::ANY_EXTEND) {
1065 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1066 X.getOperand(0).getSimpleValueType().getSizeInBits();
1067 // Assume that we'll replace the any-extend with a zero-extend, and
1068 // narrow the search to the extended value.
1069 X = X.getOperand(0);
1070 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1071 ReplacingAnyExtend = true;
1073 APInt MaskedHighBits =
1074 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1076 DAG.computeKnownBits(X, Known);
1077 if (MaskedHighBits != Known.Zero) return true;
1079 // We've identified a pattern that can be transformed into a single shift
1080 // and an addressing mode. Make it so.
1081 MVT VT = N.getSimpleValueType();
1082 if (ReplacingAnyExtend) {
1083 assert(X.getValueType() != VT);
1084 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1085 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1086 insertDAGNode(DAG, N, NewX);
1090 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1091 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1092 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1093 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1095 // Insert the new nodes into the topological ordering. We must do this in
1096 // a valid topological ordering as nothing is going to go back and re-sort
1097 // these nodes. We continually insert before 'N' in sequence as this is
1098 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1099 // hierarchy left to express.
1100 insertDAGNode(DAG, N, NewSRLAmt);
1101 insertDAGNode(DAG, N, NewSRL);
1102 insertDAGNode(DAG, N, NewSHLAmt);
1103 insertDAGNode(DAG, N, NewSHL);
1104 DAG.ReplaceAllUsesWith(N, NewSHL);
1106 AM.Scale = 1 << AMShiftAmt;
1107 AM.IndexReg = NewSRL;
1111 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1115 dbgs() << "MatchAddress: ";
1120 return matchAddressBase(N, AM);
1122 // If this is already a %rip relative address, we can only merge immediates
1123 // into it. Instead of handling this in every case, we handle it here.
1124 // RIP relative addressing: %rip + 32-bit displacement!
1125 if (AM.isRIPRelative()) {
1126 // FIXME: JumpTable and ExternalSymbol address currently don't like
1127 // displacements. It isn't very important, but this should be fixed for
1129 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1132 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1133 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1138 switch (N.getOpcode()) {
1140 case ISD::LOCAL_RECOVER: {
1141 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1142 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1143 // Use the symbol and don't prefix it.
1144 AM.MCSym = ESNode->getMCSymbol();
1149 case ISD::Constant: {
1150 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1151 if (!foldOffsetIntoAddress(Val, AM))
1156 case X86ISD::Wrapper:
1157 case X86ISD::WrapperRIP:
1158 if (!matchWrapper(N, AM))
1163 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1167 case ISD::FrameIndex:
1168 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1169 AM.Base_Reg.getNode() == nullptr &&
1170 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1171 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1172 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1178 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1182 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1183 unsigned Val = CN->getZExtValue();
1184 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1185 // that the base operand remains free for further matching. If
1186 // the base doesn't end up getting used, a post-processing step
1187 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1188 if (Val == 1 || Val == 2 || Val == 3) {
1189 AM.Scale = 1 << Val;
1190 SDValue ShVal = N.getNode()->getOperand(0);
1192 // Okay, we know that we have a scale by now. However, if the scaled
1193 // value is an add of something and a constant, we can fold the
1194 // constant into the disp field here.
1195 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1196 AM.IndexReg = ShVal.getNode()->getOperand(0);
1197 ConstantSDNode *AddVal =
1198 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1199 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1200 if (!foldOffsetIntoAddress(Disp, AM))
1204 AM.IndexReg = ShVal;
1211 // Scale must not be used already.
1212 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1214 SDValue And = N.getOperand(0);
1215 if (And.getOpcode() != ISD::AND) break;
1216 SDValue X = And.getOperand(0);
1218 // We only handle up to 64-bit values here as those are what matter for
1219 // addressing mode optimizations.
1220 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1222 // The mask used for the transform is expected to be post-shift, but we
1223 // found the shift first so just apply the shift to the mask before passing
1225 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1226 !isa<ConstantSDNode>(And.getOperand(1)))
1228 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1230 // Try to fold the mask and shift into the scale, and return false if we
1232 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1237 case ISD::SMUL_LOHI:
1238 case ISD::UMUL_LOHI:
1239 // A mul_lohi where we need the low part can be folded as a plain multiply.
1240 if (N.getResNo() != 0) break;
1243 case X86ISD::MUL_IMM:
1244 // X*[3,5,9] -> X+X*[2,4,8]
1245 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1246 AM.Base_Reg.getNode() == nullptr &&
1247 AM.IndexReg.getNode() == nullptr) {
1249 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1250 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1251 CN->getZExtValue() == 9) {
1252 AM.Scale = unsigned(CN->getZExtValue())-1;
1254 SDValue MulVal = N.getNode()->getOperand(0);
1257 // Okay, we know that we have a scale by now. However, if the scaled
1258 // value is an add of something and a constant, we can fold the
1259 // constant into the disp field here.
1260 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1261 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1262 Reg = MulVal.getNode()->getOperand(0);
1263 ConstantSDNode *AddVal =
1264 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1265 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1266 if (foldOffsetIntoAddress(Disp, AM))
1267 Reg = N.getNode()->getOperand(0);
1269 Reg = N.getNode()->getOperand(0);
1272 AM.IndexReg = AM.Base_Reg = Reg;
1279 // Given A-B, if A can be completely folded into the address and
1280 // the index field with the index field unused, use -B as the index.
1281 // This is a win if a has multiple parts that can be folded into
1282 // the address. Also, this saves a mov if the base register has
1283 // other uses, since it avoids a two-address sub instruction, however
1284 // it costs an additional mov if the index register has other uses.
1286 // Add an artificial use to this node so that we can keep track of
1287 // it if it gets CSE'd with a different node.
1288 HandleSDNode Handle(N);
1290 // Test if the LHS of the sub can be folded.
1291 X86ISelAddressMode Backup = AM;
1292 if (matchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1296 // Test if the index field is free for use.
1297 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1303 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1304 // If the RHS involves a register with multiple uses, this
1305 // transformation incurs an extra mov, due to the neg instruction
1306 // clobbering its operand.
1307 if (!RHS.getNode()->hasOneUse() ||
1308 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1309 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1310 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1311 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1312 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1314 // If the base is a register with multiple uses, this
1315 // transformation may save a mov.
1316 // FIXME: Don't rely on DELETED_NODEs.
1317 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1318 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1319 !AM.Base_Reg.getNode()->hasOneUse()) ||
1320 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1322 // If the folded LHS was interesting, this transformation saves
1323 // address arithmetic.
1324 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1325 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1326 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1328 // If it doesn't look like it may be an overall win, don't do it.
1334 // Ok, the transformation is legal and appears profitable. Go for it.
1335 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1336 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1340 // Insert the new nodes into the topological ordering.
1341 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1342 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1347 if (!matchAdd(N, AM, Depth))
1352 // We want to look through a transform in InstCombine and DAGCombiner that
1353 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1354 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1355 // An 'lea' can then be used to match the shift (multiply) and add:
1357 // lea (%rsi, %rdi, 8), %rax
1358 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1359 !matchAdd(N, AM, Depth))
1364 // Perform some heroic transforms on an and of a constant-count shift
1365 // with a constant to enable use of the scaled offset field.
1367 // Scale must not be used already.
1368 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1370 SDValue Shift = N.getOperand(0);
1371 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1372 SDValue X = Shift.getOperand(0);
1374 // We only handle up to 64-bit values here as those are what matter for
1375 // addressing mode optimizations.
1376 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1378 if (!isa<ConstantSDNode>(N.getOperand(1)))
1380 uint64_t Mask = N.getConstantOperandVal(1);
1382 // Try to fold the mask and shift into an extract and scale.
1383 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1386 // Try to fold the mask and shift directly into the scale.
1387 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1390 // Try to swap the mask and shift to place shifts which can be done as
1391 // a scale on the outside of the mask.
1392 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1398 return matchAddressBase(N, AM);
1401 /// Helper for MatchAddress. Add the specified node to the
1402 /// specified addressing mode without any further recursion.
1403 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1404 // Is the base register already occupied?
1405 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1406 // If so, check to see if the scale index register is set.
1407 if (!AM.IndexReg.getNode()) {
1413 // Otherwise, we cannot select it.
1417 // Default, generate it as a register.
1418 AM.BaseType = X86ISelAddressMode::RegBase;
1423 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1424 SDValue &Scale, SDValue &Index,
1425 SDValue &Disp, SDValue &Segment) {
1427 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1430 X86ISelAddressMode AM;
1431 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1432 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1433 if (AddrSpace == 256)
1434 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1435 if (AddrSpace == 257)
1436 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1437 if (AddrSpace == 258)
1438 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1441 Base = Mgs->getBasePtr();
1442 Index = Mgs->getIndex();
1443 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
1444 Scale = getI8Imm(ScalarSize/8, DL);
1446 // If Base is 0, the whole address is in index and the Scale is 1
1447 if (isa<ConstantSDNode>(Base)) {
1448 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1449 "Unexpected base in gather/scatter");
1450 Scale = getI8Imm(1, DL);
1451 Base = CurDAG->getRegister(0, MVT::i32);
1453 if (AM.Segment.getNode())
1454 Segment = AM.Segment;
1456 Segment = CurDAG->getRegister(0, MVT::i32);
1457 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1461 /// Returns true if it is able to pattern match an addressing mode.
1462 /// It returns the operands which make up the maximal addressing mode it can
1463 /// match by reference.
1465 /// Parent is the parent node of the addr operand that is being matched. It
1466 /// is always a load, store, atomic node, or null. It is only null when
1467 /// checking memory operands for inline asm nodes.
1468 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1469 SDValue &Scale, SDValue &Index,
1470 SDValue &Disp, SDValue &Segment) {
1471 X86ISelAddressMode AM;
1474 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1475 // that are not a MemSDNode, and thus don't have proper addrspace info.
1476 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1477 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1478 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1479 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1480 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1481 unsigned AddrSpace =
1482 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1483 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1484 if (AddrSpace == 256)
1485 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1486 if (AddrSpace == 257)
1487 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1488 if (AddrSpace == 258)
1489 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1492 if (matchAddress(N, AM))
1495 MVT VT = N.getSimpleValueType();
1496 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1497 if (!AM.Base_Reg.getNode())
1498 AM.Base_Reg = CurDAG->getRegister(0, VT);
1501 if (!AM.IndexReg.getNode())
1502 AM.IndexReg = CurDAG->getRegister(0, VT);
1504 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1508 /// Match a scalar SSE load. In particular, we want to match a load whose top
1509 /// elements are either undef or zeros. The load flavor is derived from the
1510 /// type of N, which is either v4f32 or v2f64.
1513 /// PatternChainNode: this is the matched node that has a chain input and
1515 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1516 SDValue N, SDValue &Base,
1517 SDValue &Scale, SDValue &Index,
1518 SDValue &Disp, SDValue &Segment,
1519 SDValue &PatternNodeWithChain) {
1520 // We can allow a full vector load here since narrowing a load is ok.
1521 if (ISD::isNON_EXTLoad(N.getNode())) {
1522 PatternNodeWithChain = N;
1523 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1524 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1525 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1526 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1531 // We can also match the special zero extended load opcode.
1532 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1533 PatternNodeWithChain = N;
1534 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1535 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1536 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1537 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1542 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1543 // once. Otherwise the load might get duplicated and the chain output of the
1544 // duplicate load will not be observed by all dependencies.
1545 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
1546 PatternNodeWithChain = N.getOperand(0);
1547 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1548 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1549 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1550 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1551 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1556 // Also handle the case where we explicitly require zeros in the top
1557 // elements. This is a vector shuffle from the zero vector.
1558 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1559 // Check to see if the top elements are all zeros (or bitcast of zeros).
1560 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1561 N.getOperand(0).getNode()->hasOneUse()) {
1562 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1563 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1564 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1565 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1566 // Okay, this is a zero extending load. Fold it.
1567 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1568 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1577 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1578 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1579 uint64_t ImmVal = CN->getZExtValue();
1580 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1583 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1587 // In static codegen with small code model, we can get the address of a label
1588 // into a register with 'movl'. TableGen has already made sure we're looking
1589 // at a label of some kind.
1590 assert(N->getOpcode() == X86ISD::Wrapper &&
1591 "Unexpected node type for MOV32ri64");
1592 N = N.getOperand(0);
1594 // At least GNU as does not accept 'movl' for TPOFF relocations.
1595 // FIXME: We could use 'movl' when we know we are targeting MC.
1596 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
1600 if (N->getOpcode() != ISD::TargetGlobalAddress)
1601 return TM.getCodeModel() == CodeModel::Small;
1603 Optional<ConstantRange> CR =
1604 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1606 return TM.getCodeModel() == CodeModel::Small;
1608 return CR->getUnsignedMax().ult(1ull << 32);
1611 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1612 SDValue &Scale, SDValue &Index,
1613 SDValue &Disp, SDValue &Segment) {
1614 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1617 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1620 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1621 if (RN && RN->getReg() == 0)
1622 Base = CurDAG->getRegister(0, MVT::i64);
1623 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1624 // Base could already be %rip, particularly in the x32 ABI.
1625 Base = SDValue(CurDAG->getMachineNode(
1626 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1627 CurDAG->getTargetConstant(0, DL, MVT::i64),
1629 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1633 RN = dyn_cast<RegisterSDNode>(Index);
1634 if (RN && RN->getReg() == 0)
1635 Index = CurDAG->getRegister(0, MVT::i64);
1637 assert(Index.getValueType() == MVT::i32 &&
1638 "Expect to be extending 32-bit registers for use in LEA");
1639 Index = SDValue(CurDAG->getMachineNode(
1640 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1641 CurDAG->getTargetConstant(0, DL, MVT::i64),
1643 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1651 /// Calls SelectAddr and determines if the maximal addressing
1652 /// mode it matches can be cost effectively emitted as an LEA instruction.
1653 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1654 SDValue &Base, SDValue &Scale,
1655 SDValue &Index, SDValue &Disp,
1657 X86ISelAddressMode AM;
1659 // Save the DL and VT before calling matchAddress, it can invalidate N.
1661 MVT VT = N.getSimpleValueType();
1663 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1665 SDValue Copy = AM.Segment;
1666 SDValue T = CurDAG->getRegister(0, MVT::i32);
1668 if (matchAddress(N, AM))
1670 assert (T == AM.Segment);
1673 unsigned Complexity = 0;
1674 if (AM.BaseType == X86ISelAddressMode::RegBase)
1675 if (AM.Base_Reg.getNode())
1678 AM.Base_Reg = CurDAG->getRegister(0, VT);
1679 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1682 if (AM.IndexReg.getNode())
1685 AM.IndexReg = CurDAG->getRegister(0, VT);
1687 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1692 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1693 // to a LEA. This is determined with some experimentation but is by no means
1694 // optimal (especially for code size consideration). LEA is nice because of
1695 // its three-address nature. Tweak the cost function again when we can run
1696 // convertToThreeAddress() at register allocation time.
1697 if (AM.hasSymbolicDisplacement()) {
1698 // For X86-64, always use LEA to materialize RIP-relative addresses.
1699 if (Subtarget->is64Bit())
1705 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1708 // If it isn't worth using an LEA, reject it.
1709 if (Complexity <= 2)
1712 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
1716 /// This is only run on TargetGlobalTLSAddress nodes.
1717 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1718 SDValue &Scale, SDValue &Index,
1719 SDValue &Disp, SDValue &Segment) {
1720 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1721 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1723 X86ISelAddressMode AM;
1724 AM.GV = GA->getGlobal();
1725 AM.Disp += GA->getOffset();
1726 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1727 AM.SymbolFlags = GA->getTargetFlags();
1729 if (N.getValueType() == MVT::i32) {
1731 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1733 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1736 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1740 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1741 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1742 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1747 // Keep track of the original value type and whether this value was
1748 // truncated. If we see a truncation from pointer type to VT that truncates
1749 // bits that are known to be zero, we can use a narrow reference.
1750 EVT VT = N.getValueType();
1751 bool WasTruncated = false;
1752 if (N.getOpcode() == ISD::TRUNCATE) {
1753 WasTruncated = true;
1754 N = N.getOperand(0);
1757 if (N.getOpcode() != X86ISD::Wrapper)
1760 // We can only use non-GlobalValues as immediates if they were not truncated,
1761 // as we do not have any range information. If we have a GlobalValue and the
1762 // address was not truncated, we can select it as an operand directly.
1763 unsigned Opc = N.getOperand(0)->getOpcode();
1764 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1765 Op = N.getOperand(0);
1766 // We can only select the operand directly if we didn't have to look past a
1768 return !WasTruncated;
1771 // Check that the global's range fits into VT.
1772 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1773 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1774 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1777 // Okay, we can use a narrow reference.
1778 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1779 GA->getOffset(), GA->getTargetFlags());
1783 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1784 SDValue &Base, SDValue &Scale,
1785 SDValue &Index, SDValue &Disp,
1787 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1788 !IsProfitableToFold(N, P, P) ||
1789 !IsLegalToFold(N, P, P, OptLevel))
1792 return selectAddr(N.getNode(),
1793 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1796 /// Return an SDNode that returns the value of the global base register.
1797 /// Output instructions required to initialize the global base register,
1799 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1800 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1801 auto &DL = MF->getDataLayout();
1802 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1805 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1806 if (N->getOpcode() == ISD::TRUNCATE)
1807 N = N->getOperand(0).getNode();
1808 if (N->getOpcode() != X86ISD::Wrapper)
1811 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1815 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1816 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1817 CR->getSignedMax().slt(1ull << Width);
1820 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1821 /// or OF bits to be accurate.
1822 static bool hasNoSignedComparisonUses(SDNode *N) {
1823 // Examine each user of the node.
1824 for (SDNode::use_iterator UI = N->use_begin(),
1825 UE = N->use_end(); UI != UE; ++UI) {
1826 // Only examine CopyToReg uses.
1827 if (UI->getOpcode() != ISD::CopyToReg)
1829 // Only examine CopyToReg uses that copy to EFLAGS.
1830 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1833 // Examine each user of the CopyToReg use.
1834 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1835 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1836 // Only examine the Flag result.
1837 if (FlagUI.getUse().getResNo() != 1) continue;
1838 // Anything unusual: assume conservatively.
1839 if (!FlagUI->isMachineOpcode()) return false;
1840 // Examine the opcode of the user.
1841 switch (FlagUI->getMachineOpcode()) {
1842 // These comparisons don't treat the most significant bit specially.
1843 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1844 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1845 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1846 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1847 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1848 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1849 case X86::CMOVA16rr: case X86::CMOVA16rm:
1850 case X86::CMOVA32rr: case X86::CMOVA32rm:
1851 case X86::CMOVA64rr: case X86::CMOVA64rm:
1852 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1853 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1854 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1855 case X86::CMOVB16rr: case X86::CMOVB16rm:
1856 case X86::CMOVB32rr: case X86::CMOVB32rm:
1857 case X86::CMOVB64rr: case X86::CMOVB64rm:
1858 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1859 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1860 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1861 case X86::CMOVE16rr: case X86::CMOVE16rm:
1862 case X86::CMOVE32rr: case X86::CMOVE32rm:
1863 case X86::CMOVE64rr: case X86::CMOVE64rm:
1864 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1865 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1866 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1867 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1868 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1869 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1870 case X86::CMOVP16rr: case X86::CMOVP16rm:
1871 case X86::CMOVP32rr: case X86::CMOVP32rm:
1872 case X86::CMOVP64rr: case X86::CMOVP64rm:
1874 // Anything else: assume conservatively.
1875 default: return false;
1882 /// Check whether or not the chain ending in StoreNode is suitable for doing
1883 /// the {load; increment or decrement; store} to modify transformation.
1884 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1885 SDValue StoredVal, SelectionDAG *CurDAG,
1886 LoadSDNode* &LoadNode, SDValue &InputChain) {
1888 // is the value stored the result of a DEC or INC?
1889 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1891 // is the stored value result 0 of the load?
1892 if (StoredVal.getResNo() != 0) return false;
1894 // are there other uses of the loaded value than the inc or dec?
1895 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1897 // is the store non-extending and non-indexed?
1898 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1901 SDValue Load = StoredVal->getOperand(0);
1902 // Is the stored value a non-extending and non-indexed load?
1903 if (!ISD::isNormalLoad(Load.getNode())) return false;
1905 // Return LoadNode by reference.
1906 LoadNode = cast<LoadSDNode>(Load);
1907 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1908 EVT LdVT = LoadNode->getMemoryVT();
1909 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1913 // Is store the only read of the loaded value?
1914 if (!Load.hasOneUse())
1917 // Is the address of the store the same as the load?
1918 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1919 LoadNode->getOffset() != StoreNode->getOffset())
1922 // Check if the chain is produced by the load or is a TokenFactor with
1923 // the load output chain as an operand. Return InputChain by reference.
1924 SDValue Chain = StoreNode->getChain();
1926 bool ChainCheck = false;
1927 if (Chain == Load.getValue(1)) {
1929 InputChain = LoadNode->getChain();
1930 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1931 SmallVector<SDValue, 4> ChainOps;
1932 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1933 SDValue Op = Chain.getOperand(i);
1934 if (Op == Load.getValue(1)) {
1936 // Drop Load, but keep its chain. No cycle check necessary.
1937 ChainOps.push_back(Load.getOperand(0));
1941 // Make sure using Op as part of the chain would not cause a cycle here.
1942 // In theory, we could check whether the chain node is a predecessor of
1943 // the load. But that can be very expensive. Instead visit the uses and
1944 // make sure they all have smaller node id than the load.
1945 int LoadId = LoadNode->getNodeId();
1946 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1947 UE = UI->use_end(); UI != UE; ++UI) {
1948 if (UI.getUse().getResNo() != 0)
1950 if (UI->getNodeId() > LoadId)
1954 ChainOps.push_back(Op);
1958 // Make a new TokenFactor with all the other input chains except
1960 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1961 MVT::Other, ChainOps);
1969 /// Get the appropriate X86 opcode for an in-memory increment or decrement.
1970 /// Opc should be X86ISD::DEC or X86ISD::INC.
1971 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1972 if (Opc == X86ISD::DEC) {
1973 if (LdVT == MVT::i64) return X86::DEC64m;
1974 if (LdVT == MVT::i32) return X86::DEC32m;
1975 if (LdVT == MVT::i16) return X86::DEC16m;
1976 if (LdVT == MVT::i8) return X86::DEC8m;
1978 assert(Opc == X86ISD::INC && "unrecognized opcode");
1979 if (LdVT == MVT::i64) return X86::INC64m;
1980 if (LdVT == MVT::i32) return X86::INC32m;
1981 if (LdVT == MVT::i16) return X86::INC16m;
1982 if (LdVT == MVT::i8) return X86::INC8m;
1984 llvm_unreachable("unrecognized size for LdVT");
1987 void X86DAGToDAGISel::Select(SDNode *Node) {
1988 MVT NVT = Node->getSimpleValueType(0);
1990 unsigned Opcode = Node->getOpcode();
1993 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1995 if (Node->isMachineOpcode()) {
1996 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
1997 Node->setNodeId(-1);
1998 return; // Already selected.
2004 if (Subtarget->isTargetNaCl())
2005 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2006 // leave the instruction alone.
2008 if (Subtarget->isTarget64BitILP32()) {
2009 // Converts a 32-bit register to a 64-bit, zero-extended version of
2010 // it. This is needed because x86-64 can do many things, but jmp %r32
2011 // ain't one of them.
2012 const SDValue &Target = Node->getOperand(1);
2013 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2014 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2015 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2016 Node->getOperand(0), ZextTarget);
2017 ReplaceNode(Node, Brind.getNode());
2018 SelectCode(ZextTarget.getNode());
2019 SelectCode(Brind.getNode());
2024 case X86ISD::GlobalBaseReg:
2025 ReplaceNode(Node, getGlobalBaseReg());
2028 case X86ISD::SHRUNKBLEND: {
2029 // SHRUNKBLEND selects like a regular VSELECT.
2030 SDValue VSelect = CurDAG->getNode(
2031 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2032 Node->getOperand(1), Node->getOperand(2));
2033 ReplaceUses(SDValue(Node, 0), VSelect);
2034 SelectCode(VSelect.getNode());
2035 // We already called ReplaceUses.
2042 // For operations of the form (x << C1) op C2, check if we can use a smaller
2043 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2044 SDValue N0 = Node->getOperand(0);
2045 SDValue N1 = Node->getOperand(1);
2047 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2050 // i8 is unshrinkable, i16 should be promoted to i32.
2051 if (NVT != MVT::i32 && NVT != MVT::i64)
2054 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2055 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2056 if (!Cst || !ShlCst)
2059 int64_t Val = Cst->getSExtValue();
2060 uint64_t ShlVal = ShlCst->getZExtValue();
2062 // Make sure that we don't change the operation by removing bits.
2063 // This only matters for OR and XOR, AND is unaffected.
2064 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2065 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2068 unsigned ShlOp, AddOp, Op;
2071 // Check the minimum bitwidth for the new constant.
2072 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2073 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2074 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2075 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2077 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2080 // Bail if there is no smaller encoding.
2084 switch (NVT.SimpleTy) {
2085 default: llvm_unreachable("Unsupported VT!");
2087 assert(CstVT == MVT::i8);
2088 ShlOp = X86::SHL32ri;
2089 AddOp = X86::ADD32rr;
2092 default: llvm_unreachable("Impossible opcode");
2093 case ISD::AND: Op = X86::AND32ri8; break;
2094 case ISD::OR: Op = X86::OR32ri8; break;
2095 case ISD::XOR: Op = X86::XOR32ri8; break;
2099 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2100 ShlOp = X86::SHL64ri;
2101 AddOp = X86::ADD64rr;
2104 default: llvm_unreachable("Impossible opcode");
2105 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2106 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2107 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2112 // Emit the smaller op and the shift.
2113 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2114 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2116 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2119 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2120 getI8Imm(ShlVal, dl));
2124 case X86ISD::SMUL8: {
2125 SDValue N0 = Node->getOperand(0);
2126 SDValue N1 = Node->getOperand(1);
2128 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2130 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2131 N0, SDValue()).getValue(1);
2133 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2134 SDValue Ops[] = {N1, InFlag};
2135 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2137 ReplaceNode(Node, CNode);
2141 case X86ISD::UMUL: {
2142 SDValue N0 = Node->getOperand(0);
2143 SDValue N1 = Node->getOperand(1);
2146 switch (NVT.SimpleTy) {
2147 default: llvm_unreachable("Unsupported VT!");
2148 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2149 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2150 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2151 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2154 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2155 N0, SDValue()).getValue(1);
2157 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2158 SDValue Ops[] = {N1, InFlag};
2159 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2161 ReplaceNode(Node, CNode);
2165 case ISD::SMUL_LOHI:
2166 case ISD::UMUL_LOHI: {
2167 SDValue N0 = Node->getOperand(0);
2168 SDValue N1 = Node->getOperand(1);
2170 bool isSigned = Opcode == ISD::SMUL_LOHI;
2171 bool hasBMI2 = Subtarget->hasBMI2();
2173 switch (NVT.SimpleTy) {
2174 default: llvm_unreachable("Unsupported VT!");
2175 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2176 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2177 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2178 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2179 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2180 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2183 switch (NVT.SimpleTy) {
2184 default: llvm_unreachable("Unsupported VT!");
2185 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2186 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2187 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2188 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2192 unsigned SrcReg, LoReg, HiReg;
2194 default: llvm_unreachable("Unknown MUL opcode!");
2197 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2201 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2205 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2209 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2212 SrcReg = X86::EDX; LoReg = HiReg = 0;
2215 SrcReg = X86::RDX; LoReg = HiReg = 0;
2219 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2220 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2221 // Multiply is commmutative.
2223 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2228 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2229 N0, SDValue()).getValue(1);
2230 SDValue ResHi, ResLo;
2234 MachineSDNode *CNode = nullptr;
2235 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2237 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2238 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2239 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2240 ResHi = SDValue(CNode, 0);
2241 ResLo = SDValue(CNode, 1);
2242 Chain = SDValue(CNode, 2);
2243 InFlag = SDValue(CNode, 3);
2245 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2246 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2247 Chain = SDValue(CNode, 0);
2248 InFlag = SDValue(CNode, 1);
2251 // Update the chain.
2252 ReplaceUses(N1.getValue(1), Chain);
2253 // Record the mem-refs
2254 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2256 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2257 MemOp[0] = LoadNode->getMemOperand();
2258 CNode->setMemRefs(MemOp, MemOp + 1);
2261 SDValue Ops[] = { N1, InFlag };
2262 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2263 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2264 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2265 ResHi = SDValue(CNode, 0);
2266 ResLo = SDValue(CNode, 1);
2267 InFlag = SDValue(CNode, 2);
2269 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2270 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2271 InFlag = SDValue(CNode, 0);
2275 // Prevent use of AH in a REX instruction by referencing AX instead.
2276 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2277 !SDValue(Node, 1).use_empty()) {
2278 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2279 X86::AX, MVT::i16, InFlag);
2280 InFlag = Result.getValue(2);
2281 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2283 if (!SDValue(Node, 0).use_empty())
2284 ReplaceUses(SDValue(Node, 1),
2285 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2287 // Shift AX down 8 bits.
2288 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2290 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2292 // Then truncate it down to i8.
2293 ReplaceUses(SDValue(Node, 1),
2294 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2296 // Copy the low half of the result, if it is needed.
2297 if (!SDValue(Node, 0).use_empty()) {
2298 if (!ResLo.getNode()) {
2299 assert(LoReg && "Register for low half is not defined!");
2300 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2302 InFlag = ResLo.getValue(2);
2304 ReplaceUses(SDValue(Node, 0), ResLo);
2305 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2307 // Copy the high half of the result, if it is needed.
2308 if (!SDValue(Node, 1).use_empty()) {
2309 if (!ResHi.getNode()) {
2310 assert(HiReg && "Register for high half is not defined!");
2311 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2313 InFlag = ResHi.getValue(2);
2315 ReplaceUses(SDValue(Node, 1), ResHi);
2316 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2324 case X86ISD::SDIVREM8_SEXT_HREG:
2325 case X86ISD::UDIVREM8_ZEXT_HREG: {
2326 SDValue N0 = Node->getOperand(0);
2327 SDValue N1 = Node->getOperand(1);
2329 bool isSigned = (Opcode == ISD::SDIVREM ||
2330 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2332 switch (NVT.SimpleTy) {
2333 default: llvm_unreachable("Unsupported VT!");
2334 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2335 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2336 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2337 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2340 switch (NVT.SimpleTy) {
2341 default: llvm_unreachable("Unsupported VT!");
2342 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2343 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2344 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2345 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2349 unsigned LoReg, HiReg, ClrReg;
2350 unsigned SExtOpcode;
2351 switch (NVT.SimpleTy) {
2352 default: llvm_unreachable("Unsupported VT!");
2354 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2355 SExtOpcode = X86::CBW;
2358 LoReg = X86::AX; HiReg = X86::DX;
2360 SExtOpcode = X86::CWD;
2363 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2364 SExtOpcode = X86::CDQ;
2367 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2368 SExtOpcode = X86::CQO;
2372 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2373 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2374 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2377 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2378 // Special case for div8, just use a move with zero extension to AX to
2379 // clear the upper 8 bits (AH).
2380 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2381 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2382 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2384 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2385 MVT::Other, Ops), 0);
2386 Chain = Move.getValue(1);
2387 ReplaceUses(N0.getValue(1), Chain);
2390 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2391 Chain = CurDAG->getEntryNode();
2393 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2394 InFlag = Chain.getValue(1);
2397 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2398 LoReg, N0, SDValue()).getValue(1);
2399 if (isSigned && !signBitIsZero) {
2400 // Sign extend the low part into the high part.
2402 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2404 // Zero out the high part, effectively zero extending the input.
2405 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2406 switch (NVT.SimpleTy) {
2409 SDValue(CurDAG->getMachineNode(
2410 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2411 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2419 SDValue(CurDAG->getMachineNode(
2420 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2421 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2422 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2427 llvm_unreachable("Unexpected division source");
2430 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2431 ClrNode, InFlag).getValue(1);
2436 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2439 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2440 InFlag = SDValue(CNode, 1);
2441 // Update the chain.
2442 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2445 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2448 // Prevent use of AH in a REX instruction by explicitly copying it to
2449 // an ABCD_L register.
2451 // The current assumption of the register allocator is that isel
2452 // won't generate explicit references to the GR8_ABCD_H registers. If
2453 // the allocator and/or the backend get enhanced to be more robust in
2454 // that regard, this can be, and should be, removed.
2455 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2456 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2457 unsigned AHExtOpcode =
2458 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2460 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2461 MVT::Glue, AHCopy, InFlag);
2462 SDValue Result(RNode, 0);
2463 InFlag = SDValue(RNode, 1);
2465 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2466 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2467 if (Node->getValueType(1) == MVT::i64) {
2468 // It's not possible to directly movsx AH to a 64bit register, because
2469 // the latter needs the REX prefix, but the former can't have it.
2470 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2471 "Unexpected i64 sext of h-register");
2473 SDValue(CurDAG->getMachineNode(
2474 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2475 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2476 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2482 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2484 ReplaceUses(SDValue(Node, 1), Result);
2485 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2487 // Copy the division (low) result, if it is needed.
2488 if (!SDValue(Node, 0).use_empty()) {
2489 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2490 LoReg, NVT, InFlag);
2491 InFlag = Result.getValue(2);
2492 ReplaceUses(SDValue(Node, 0), Result);
2493 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2495 // Copy the remainder (high) result, if it is needed.
2496 if (!SDValue(Node, 1).use_empty()) {
2497 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2498 HiReg, NVT, InFlag);
2499 InFlag = Result.getValue(2);
2500 ReplaceUses(SDValue(Node, 1), Result);
2501 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2508 // Sometimes a SUB is used to perform comparison.
2509 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2510 // This node is not a CMP.
2512 SDValue N0 = Node->getOperand(0);
2513 SDValue N1 = Node->getOperand(1);
2515 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2516 hasNoSignedComparisonUses(Node))
2517 N0 = N0.getOperand(0);
2519 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2520 // use a smaller encoding.
2521 // Look past the truncate if CMP is the only use of it.
2522 if ((N0.getNode()->getOpcode() == ISD::AND ||
2523 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2524 N0.getNode()->hasOneUse() &&
2525 N0.getValueType() != MVT::i8 &&
2526 X86::isZeroNode(N1)) {
2527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2530 // For example, convert "testl %eax, $8" to "testb %al, $8"
2531 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2532 (!(C->getZExtValue() & 0x80) ||
2533 hasNoSignedComparisonUses(Node))) {
2534 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2535 SDValue Reg = N0.getNode()->getOperand(0);
2537 // On x86-32, only the ABCD registers have 8-bit subregisters.
2538 if (!Subtarget->is64Bit()) {
2539 const TargetRegisterClass *TRC;
2540 switch (N0.getSimpleValueType().SimpleTy) {
2541 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2542 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2543 default: llvm_unreachable("Unsupported TEST operand type!");
2545 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2546 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2547 Reg.getValueType(), Reg, RC), 0);
2550 // Extract the l-register.
2551 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2555 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2557 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2558 // one, do not call ReplaceAllUsesWith.
2559 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2560 SDValue(NewNode, 0));
2564 // For example, "testl %eax, $2048" to "testb %ah, $8".
2565 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2566 (!(C->getZExtValue() & 0x8000) ||
2567 hasNoSignedComparisonUses(Node))) {
2568 // Shift the immediate right by 8 bits.
2569 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2571 SDValue Reg = N0.getNode()->getOperand(0);
2573 // Put the value in an ABCD register.
2574 const TargetRegisterClass *TRC;
2575 switch (N0.getSimpleValueType().SimpleTy) {
2576 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2577 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2578 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2579 default: llvm_unreachable("Unsupported TEST operand type!");
2581 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2582 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2583 Reg.getValueType(), Reg, RC), 0);
2585 // Extract the h-register.
2586 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2589 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2590 // target GR8_NOREX registers, so make sure the register class is
2592 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2593 MVT::i32, Subreg, ShiftedImm);
2594 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2595 // one, do not call ReplaceAllUsesWith.
2596 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2597 SDValue(NewNode, 0));
2601 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2602 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2603 N0.getValueType() != MVT::i16 &&
2604 (!(C->getZExtValue() & 0x8000) ||
2605 hasNoSignedComparisonUses(Node))) {
2606 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2608 SDValue Reg = N0.getNode()->getOperand(0);
2610 // Extract the 16-bit subregister.
2611 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2615 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2617 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2618 // one, do not call ReplaceAllUsesWith.
2619 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2620 SDValue(NewNode, 0));
2624 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2625 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2626 N0.getValueType() == MVT::i64 &&
2627 (!(C->getZExtValue() & 0x80000000) ||
2628 hasNoSignedComparisonUses(Node))) {
2629 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2631 SDValue Reg = N0.getNode()->getOperand(0);
2633 // Extract the 32-bit subregister.
2634 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2638 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2640 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2641 // one, do not call ReplaceAllUsesWith.
2642 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2643 SDValue(NewNode, 0));
2650 // Change a chain of {load; incr or dec; store} of the same value into
2651 // a simple increment or decrement through memory of that value, if the
2652 // uses of the modified value and its address are suitable.
2653 // The DEC64m tablegen pattern is currently not able to match the case where
2654 // the EFLAGS on the original DEC are used. (This also applies to
2655 // {INC,DEC}X{64,32,16,8}.)
2656 // We'll need to improve tablegen to allow flags to be transferred from a
2657 // node in the pattern to the result node. probably with a new keyword
2658 // for example, we have this
2659 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2660 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2661 // (implicit EFLAGS)]>;
2662 // but maybe need something like this
2663 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2664 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2665 // (transferrable EFLAGS)]>;
2667 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2668 SDValue StoredVal = StoreNode->getOperand(1);
2669 unsigned Opc = StoredVal->getOpcode();
2671 LoadSDNode *LoadNode = nullptr;
2673 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2674 LoadNode, InputChain))
2677 SDValue Base, Scale, Index, Disp, Segment;
2678 if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
2679 Base, Scale, Index, Disp, Segment))
2682 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2683 MemOp[0] = StoreNode->getMemOperand();
2684 MemOp[1] = LoadNode->getMemOperand();
2685 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2686 EVT LdVT = LoadNode->getMemoryVT();
2687 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2688 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2690 MVT::i32, MVT::Other, Ops);
2691 Result->setMemRefs(MemOp, MemOp + 2);
2693 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2694 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2695 CurDAG->RemoveDeadNode(Node);
2703 bool X86DAGToDAGISel::
2704 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2705 std::vector<SDValue> &OutOps) {
2706 SDValue Op0, Op1, Op2, Op3, Op4;
2707 switch (ConstraintID) {
2709 llvm_unreachable("Unexpected asm memory constraint");
2710 case InlineAsm::Constraint_i:
2711 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2712 // be an immediate and not a memory constraint.
2714 case InlineAsm::Constraint_o: // offsetable ??
2715 case InlineAsm::Constraint_v: // not offsetable ??
2716 case InlineAsm::Constraint_m: // memory
2717 case InlineAsm::Constraint_X:
2718 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2723 OutOps.push_back(Op0);
2724 OutOps.push_back(Op1);
2725 OutOps.push_back(Op2);
2726 OutOps.push_back(Op3);
2727 OutOps.push_back(Op4);
2731 /// This pass converts a legalized DAG into a X86-specific DAG,
2732 /// ready for instruction scheduling.
2733 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2734 CodeGenOpt::Level OptLevel) {
2735 return new X86DAGToDAGISel(TM, OptLevel);