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()) {
425 SDValue Op1 = U->getOperand(1);
427 // If the other operand is a 8-bit immediate we should fold the immediate
428 // instead. This reduces code size.
430 // movl 4(%esp), %eax
434 // addl 4(%esp), %eax
435 // The former is 2 bytes shorter. In case where the increment is 1, then
436 // the saving can be 4 bytes (by using incl %eax).
437 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
438 if (Imm->getAPIntValue().isSignedIntN(8))
441 // If the other operand is a TLS address, we should fold it instead.
444 // leal i@NTPOFF(%eax), %eax
446 // movl $i@NTPOFF, %eax
448 // if the block also has an access to a second TLS address this will save
450 // FIXME: This is probably also true for non-TLS addresses.
451 if (Op1.getOpcode() == X86ISD::Wrapper) {
452 SDValue Val = Op1.getOperand(0);
453 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
463 /// Replace the original chain operand of the call with
464 /// load's chain operand and move load below the call's chain operand.
465 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
466 SDValue Call, SDValue OrigChain) {
467 SmallVector<SDValue, 8> Ops;
468 SDValue Chain = OrigChain.getOperand(0);
469 if (Chain.getNode() == Load.getNode())
470 Ops.push_back(Load.getOperand(0));
472 assert(Chain.getOpcode() == ISD::TokenFactor &&
473 "Unexpected chain operand");
474 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
475 if (Chain.getOperand(i).getNode() == Load.getNode())
476 Ops.push_back(Load.getOperand(0));
478 Ops.push_back(Chain.getOperand(i));
480 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
482 Ops.push_back(NewChain);
484 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
485 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
486 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
487 Load.getOperand(1), Load.getOperand(2));
490 Ops.push_back(SDValue(Load.getNode(), 1));
491 Ops.append(Call->op_begin() + 1, Call->op_end());
492 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
495 /// Return true if call address is a load and it can be
496 /// moved below CALLSEQ_START and the chains leading up to the call.
497 /// Return the CALLSEQ_START by reference as a second output.
498 /// In the case of a tail call, there isn't a callseq node between the call
499 /// chain and the load.
500 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
501 // The transformation is somewhat dangerous if the call's chain was glued to
502 // the call. After MoveBelowOrigChain the load is moved between the call and
503 // the chain, this can create a cycle if the load is not folded. So it is
504 // *really* important that we are sure the load will be folded.
505 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
507 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
510 LD->getAddressingMode() != ISD::UNINDEXED ||
511 LD->getExtensionType() != ISD::NON_EXTLOAD)
514 // Now let's find the callseq_start.
515 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
516 if (!Chain.hasOneUse())
518 Chain = Chain.getOperand(0);
521 if (!Chain.getNumOperands())
523 // Since we are not checking for AA here, conservatively abort if the chain
524 // writes to memory. It's not safe to move the callee (a load) across a store.
525 if (isa<MemSDNode>(Chain.getNode()) &&
526 cast<MemSDNode>(Chain.getNode())->writeMem())
528 if (Chain.getOperand(0).getNode() == Callee.getNode())
530 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
531 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
532 Callee.getValue(1).hasOneUse())
537 void X86DAGToDAGISel::PreprocessISelDAG() {
538 // OptFor[Min]Size are used in pattern predicates that isel is matching.
539 OptForSize = MF->getFunction()->optForSize();
540 OptForMinSize = MF->getFunction()->optForMinSize();
541 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
543 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
544 E = CurDAG->allnodes_end(); I != E; ) {
545 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
547 if (OptLevel != CodeGenOpt::None &&
548 // Only does this when target favors doesn't favor register indirect
550 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
551 (N->getOpcode() == X86ISD::TC_RETURN &&
552 // Only does this if load can be folded into TC_RETURN.
553 (Subtarget->is64Bit() ||
554 !getTargetMachine().isPositionIndependent())))) {
555 /// Also try moving call address load from outside callseq_start to just
556 /// before the call to allow it to be folded.
574 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
575 SDValue Chain = N->getOperand(0);
576 SDValue Load = N->getOperand(1);
577 if (!isCalleeLoad(Load, Chain, HasCallSeq))
579 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
584 // Lower fpround and fpextend nodes that target the FP stack to be store and
585 // load to the stack. This is a gross hack. We would like to simply mark
586 // these as being illegal, but when we do that, legalize produces these when
587 // it expands calls, then expands these in the same legalize pass. We would
588 // like dag combine to be able to hack on these between the call expansion
589 // and the node legalization. As such this pass basically does "really
590 // late" legalization of these inline with the X86 isel pass.
591 // FIXME: This should only happen when not compiled with -O0.
592 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
595 MVT SrcVT = N->getOperand(0).getSimpleValueType();
596 MVT DstVT = N->getSimpleValueType(0);
598 // If any of the sources are vectors, no fp stack involved.
599 if (SrcVT.isVector() || DstVT.isVector())
602 // If the source and destination are SSE registers, then this is a legal
603 // conversion that should not be lowered.
604 const X86TargetLowering *X86Lowering =
605 static_cast<const X86TargetLowering *>(TLI);
606 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
607 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
608 if (SrcIsSSE && DstIsSSE)
611 if (!SrcIsSSE && !DstIsSSE) {
612 // If this is an FPStack extension, it is a noop.
613 if (N->getOpcode() == ISD::FP_EXTEND)
615 // If this is a value-preserving FPStack truncation, it is a noop.
616 if (N->getConstantOperandVal(1))
620 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
621 // FPStack has extload and truncstore. SSE can fold direct loads into other
622 // operations. Based on this, decide what we want to do.
624 if (N->getOpcode() == ISD::FP_ROUND)
625 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
627 MemVT = SrcIsSSE ? SrcVT : DstVT;
629 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
632 // FIXME: optimize the case where the src/dest is a load or store?
634 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
635 MemTmp, MachinePointerInfo(), MemVT);
636 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
637 MachinePointerInfo(), MemVT);
639 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
640 // extload we created. This will cause general havok on the dag because
641 // anything below the conversion could be folded into other existing nodes.
642 // To avoid invalidating 'I', back it up to the convert node.
644 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
646 // Now that we did that, the node is dead. Increment the iterator to the
647 // next node to process, then delete N.
649 CurDAG->DeleteNode(N);
654 /// Emit any code that needs to be executed only in the main function.
655 void X86DAGToDAGISel::emitSpecialCodeForMain() {
656 if (Subtarget->isTargetCygMing()) {
657 TargetLowering::ArgListTy Args;
658 auto &DL = CurDAG->getDataLayout();
660 TargetLowering::CallLoweringInfo CLI(*CurDAG);
661 CLI.setChain(CurDAG->getRoot())
662 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
663 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
665 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
666 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
667 CurDAG->setRoot(Result.second);
671 void X86DAGToDAGISel::EmitFunctionEntryCode() {
672 // If this is main, emit special code for main.
673 if (const Function *Fn = MF->getFunction())
674 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
675 emitSpecialCodeForMain();
678 static bool isDispSafeForFrameIndex(int64_t Val) {
679 // On 64-bit platforms, we can run into an issue where a frame index
680 // includes a displacement that, when added to the explicit displacement,
681 // will overflow the displacement field. Assuming that the frame index
682 // displacement fits into a 31-bit integer (which is only slightly more
683 // aggressive than the current fundamental assumption that it fits into
684 // a 32-bit integer), a 31-bit disp should always be safe.
685 return isInt<31>(Val);
688 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
689 X86ISelAddressMode &AM) {
690 // Cannot combine ExternalSymbol displacements with integer offsets.
691 if (Offset != 0 && (AM.ES || AM.MCSym))
693 int64_t Val = AM.Disp + Offset;
694 CodeModel::Model M = TM.getCodeModel();
695 if (Subtarget->is64Bit()) {
696 if (!X86::isOffsetSuitableForCodeModel(Val, M,
697 AM.hasSymbolicDisplacement()))
699 // In addition to the checks required for a register base, check that
700 // we do not try to use an unsafe Disp with a frame index.
701 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
702 !isDispSafeForFrameIndex(Val))
710 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
711 SDValue Address = N->getOperand(1);
713 // load gs:0 -> GS segment register.
714 // load fs:0 -> FS segment register.
716 // This optimization is valid because the GNU TLS model defines that
717 // gs:0 (or fs:0 on X86-64) contains its own address.
718 // For more information see http://people.redhat.com/drepper/tls.pdf
719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
720 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
721 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
722 Subtarget->isTargetFuchsia()))
723 switch (N->getPointerInfo().getAddrSpace()) {
725 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
728 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
730 // Address space 258 is not handled here, because it is not used to
731 // address TLS areas.
737 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
738 /// mode. These wrap things that will resolve down into a symbol reference.
739 /// If no match is possible, this returns true, otherwise it returns false.
740 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
741 // If the addressing mode already has a symbol as the displacement, we can
742 // never match another symbol.
743 if (AM.hasSymbolicDisplacement())
746 SDValue N0 = N.getOperand(0);
747 CodeModel::Model M = TM.getCodeModel();
749 // Handle X86-64 rip-relative addresses. We check this before checking direct
750 // folding because RIP is preferable to non-RIP accesses.
751 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
752 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
753 // they cannot be folded into immediate fields.
754 // FIXME: This can be improved for kernel and other models?
755 (M == CodeModel::Small || M == CodeModel::Kernel)) {
756 // Base and index reg must be 0 in order to use %rip as base.
757 if (AM.hasBaseOrIndexReg())
759 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
760 X86ISelAddressMode Backup = AM;
761 AM.GV = G->getGlobal();
762 AM.SymbolFlags = G->getTargetFlags();
763 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
767 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
768 X86ISelAddressMode Backup = AM;
769 AM.CP = CP->getConstVal();
770 AM.Align = CP->getAlignment();
771 AM.SymbolFlags = CP->getTargetFlags();
772 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
776 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
777 AM.ES = S->getSymbol();
778 AM.SymbolFlags = S->getTargetFlags();
779 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
780 AM.MCSym = S->getMCSymbol();
781 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
782 AM.JT = J->getIndex();
783 AM.SymbolFlags = J->getTargetFlags();
784 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
785 X86ISelAddressMode Backup = AM;
786 AM.BlockAddr = BA->getBlockAddress();
787 AM.SymbolFlags = BA->getTargetFlags();
788 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
793 llvm_unreachable("Unhandled symbol reference node.");
795 if (N.getOpcode() == X86ISD::WrapperRIP)
796 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
800 // Handle the case when globals fit in our immediate field: This is true for
801 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
802 // mode, this only applies to a non-RIP-relative computation.
803 if (!Subtarget->is64Bit() ||
804 M == CodeModel::Small || M == CodeModel::Kernel) {
805 assert(N.getOpcode() != X86ISD::WrapperRIP &&
806 "RIP-relative addressing already handled");
807 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
808 AM.GV = G->getGlobal();
809 AM.Disp += G->getOffset();
810 AM.SymbolFlags = G->getTargetFlags();
811 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
812 AM.CP = CP->getConstVal();
813 AM.Align = CP->getAlignment();
814 AM.Disp += CP->getOffset();
815 AM.SymbolFlags = CP->getTargetFlags();
816 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
817 AM.ES = S->getSymbol();
818 AM.SymbolFlags = S->getTargetFlags();
819 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
820 AM.MCSym = S->getMCSymbol();
821 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
822 AM.JT = J->getIndex();
823 AM.SymbolFlags = J->getTargetFlags();
824 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
825 AM.BlockAddr = BA->getBlockAddress();
826 AM.Disp += BA->getOffset();
827 AM.SymbolFlags = BA->getTargetFlags();
829 llvm_unreachable("Unhandled symbol reference node.");
836 /// Add the specified node to the specified addressing mode, returning true if
837 /// it cannot be done. This just pattern matches for the addressing mode.
838 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
839 if (matchAddressRecursively(N, AM, 0))
842 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
843 // a smaller encoding and avoids a scaled-index.
845 AM.BaseType == X86ISelAddressMode::RegBase &&
846 AM.Base_Reg.getNode() == nullptr) {
847 AM.Base_Reg = AM.IndexReg;
851 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
852 // because it has a smaller encoding.
853 // TODO: Which other code models can use this?
854 if (TM.getCodeModel() == CodeModel::Small &&
855 Subtarget->is64Bit() &&
857 AM.BaseType == X86ISelAddressMode::RegBase &&
858 AM.Base_Reg.getNode() == nullptr &&
859 AM.IndexReg.getNode() == nullptr &&
860 AM.SymbolFlags == X86II::MO_NO_FLAG &&
861 AM.hasSymbolicDisplacement())
862 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
867 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
869 // Add an artificial use to this node so that we can keep track of
870 // it if it gets CSE'd with a different node.
871 HandleSDNode Handle(N);
873 X86ISelAddressMode Backup = AM;
874 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
875 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
879 // Try again after commuting the operands.
880 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
881 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
885 // If we couldn't fold both operands into the address at the same time,
886 // see if we can just put each operand into a register and fold at least
888 if (AM.BaseType == X86ISelAddressMode::RegBase &&
889 !AM.Base_Reg.getNode() &&
890 !AM.IndexReg.getNode()) {
891 N = Handle.getValue();
892 AM.Base_Reg = N.getOperand(0);
893 AM.IndexReg = N.getOperand(1);
897 N = Handle.getValue();
901 // Insert a node into the DAG at least before the Pos node's position. This
902 // will reposition the node as needed, and will assign it a node ID that is <=
903 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
904 // IDs! The selection DAG must no longer depend on their uniqueness when this
906 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
907 if (N.getNode()->getNodeId() == -1 ||
908 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
909 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
910 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
914 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
915 // safe. This allows us to convert the shift and and into an h-register
916 // extract and a scaled index. Returns false if the simplification is
918 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
920 SDValue Shift, SDValue X,
921 X86ISelAddressMode &AM) {
922 if (Shift.getOpcode() != ISD::SRL ||
923 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
927 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
928 if (ScaleLog <= 0 || ScaleLog >= 4 ||
929 Mask != (0xffu << ScaleLog))
932 MVT VT = N.getSimpleValueType();
934 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
935 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
936 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
937 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
938 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
939 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
941 // Insert the new nodes into the topological ordering. We must do this in
942 // a valid topological ordering as nothing is going to go back and re-sort
943 // these nodes. We continually insert before 'N' in sequence as this is
944 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
945 // hierarchy left to express.
946 insertDAGNode(DAG, N, Eight);
947 insertDAGNode(DAG, N, Srl);
948 insertDAGNode(DAG, N, NewMask);
949 insertDAGNode(DAG, N, And);
950 insertDAGNode(DAG, N, ShlCount);
951 insertDAGNode(DAG, N, Shl);
952 DAG.ReplaceAllUsesWith(N, Shl);
954 AM.Scale = (1 << ScaleLog);
958 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
959 // allows us to fold the shift into this addressing mode. Returns false if the
960 // transform succeeded.
961 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
963 SDValue Shift, SDValue X,
964 X86ISelAddressMode &AM) {
965 if (Shift.getOpcode() != ISD::SHL ||
966 !isa<ConstantSDNode>(Shift.getOperand(1)))
969 // Not likely to be profitable if either the AND or SHIFT node has more
970 // than one use (unless all uses are for address computation). Besides,
971 // isel mechanism requires their node ids to be reused.
972 if (!N.hasOneUse() || !Shift.hasOneUse())
975 // Verify that the shift amount is something we can fold.
976 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
977 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
980 MVT VT = N.getSimpleValueType();
982 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
983 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
984 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
986 // Insert the new nodes into the topological ordering. We must do this in
987 // a valid topological ordering as nothing is going to go back and re-sort
988 // these nodes. We continually insert before 'N' in sequence as this is
989 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
990 // hierarchy left to express.
991 insertDAGNode(DAG, N, NewMask);
992 insertDAGNode(DAG, N, NewAnd);
993 insertDAGNode(DAG, N, NewShift);
994 DAG.ReplaceAllUsesWith(N, NewShift);
996 AM.Scale = 1 << ShiftAmt;
997 AM.IndexReg = NewAnd;
1001 // Implement some heroics to detect shifts of masked values where the mask can
1002 // be replaced by extending the shift and undoing that in the addressing mode
1003 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1004 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1005 // the addressing mode. This results in code such as:
1007 // int f(short *y, int *lookup_table) {
1009 // return *y + lookup_table[*y >> 11];
1013 // movzwl (%rdi), %eax
1016 // addl (%rsi,%rcx,4), %eax
1019 // movzwl (%rdi), %eax
1023 // addl (%rsi,%rcx), %eax
1025 // Note that this function assumes the mask is provided as a mask *after* the
1026 // value is shifted. The input chain may or may not match that, but computing
1027 // such a mask is trivial.
1028 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1030 SDValue Shift, SDValue X,
1031 X86ISelAddressMode &AM) {
1032 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1033 !isa<ConstantSDNode>(Shift.getOperand(1)))
1036 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1037 unsigned MaskLZ = countLeadingZeros(Mask);
1038 unsigned MaskTZ = countTrailingZeros(Mask);
1040 // The amount of shift we're trying to fit into the addressing mode is taken
1041 // from the trailing zeros of the mask.
1042 unsigned AMShiftAmt = MaskTZ;
1044 // There is nothing we can do here unless the mask is removing some bits.
1045 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1046 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1048 // We also need to ensure that mask is a continuous run of bits.
1049 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1051 // Scale the leading zero count down based on the actual size of the value.
1052 // Also scale it down based on the size of the shift.
1053 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1055 // The final check is to ensure that any masked out high bits of X are
1056 // already known to be zero. Otherwise, the mask has a semantic impact
1057 // other than masking out a couple of low bits. Unfortunately, because of
1058 // the mask, zero extensions will be removed from operands in some cases.
1059 // This code works extra hard to look through extensions because we can
1060 // replace them with zero extensions cheaply if necessary.
1061 bool ReplacingAnyExtend = false;
1062 if (X.getOpcode() == ISD::ANY_EXTEND) {
1063 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1064 X.getOperand(0).getSimpleValueType().getSizeInBits();
1065 // Assume that we'll replace the any-extend with a zero-extend, and
1066 // narrow the search to the extended value.
1067 X = X.getOperand(0);
1068 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1069 ReplacingAnyExtend = true;
1071 APInt MaskedHighBits =
1072 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1074 DAG.computeKnownBits(X, Known);
1075 if (MaskedHighBits != Known.Zero) return true;
1077 // We've identified a pattern that can be transformed into a single shift
1078 // and an addressing mode. Make it so.
1079 MVT VT = N.getSimpleValueType();
1080 if (ReplacingAnyExtend) {
1081 assert(X.getValueType() != VT);
1082 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1083 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1084 insertDAGNode(DAG, N, NewX);
1088 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1089 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1090 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1091 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1093 // Insert the new nodes into the topological ordering. We must do this in
1094 // a valid topological ordering as nothing is going to go back and re-sort
1095 // these nodes. We continually insert before 'N' in sequence as this is
1096 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1097 // hierarchy left to express.
1098 insertDAGNode(DAG, N, NewSRLAmt);
1099 insertDAGNode(DAG, N, NewSRL);
1100 insertDAGNode(DAG, N, NewSHLAmt);
1101 insertDAGNode(DAG, N, NewSHL);
1102 DAG.ReplaceAllUsesWith(N, NewSHL);
1104 AM.Scale = 1 << AMShiftAmt;
1105 AM.IndexReg = NewSRL;
1109 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1113 dbgs() << "MatchAddress: ";
1118 return matchAddressBase(N, AM);
1120 // If this is already a %rip relative address, we can only merge immediates
1121 // into it. Instead of handling this in every case, we handle it here.
1122 // RIP relative addressing: %rip + 32-bit displacement!
1123 if (AM.isRIPRelative()) {
1124 // FIXME: JumpTable and ExternalSymbol address currently don't like
1125 // displacements. It isn't very important, but this should be fixed for
1127 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1130 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1131 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1136 switch (N.getOpcode()) {
1138 case ISD::LOCAL_RECOVER: {
1139 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1140 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1141 // Use the symbol and don't prefix it.
1142 AM.MCSym = ESNode->getMCSymbol();
1147 case ISD::Constant: {
1148 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1149 if (!foldOffsetIntoAddress(Val, AM))
1154 case X86ISD::Wrapper:
1155 case X86ISD::WrapperRIP:
1156 if (!matchWrapper(N, AM))
1161 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1165 case ISD::FrameIndex:
1166 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1167 AM.Base_Reg.getNode() == nullptr &&
1168 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1169 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1170 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1176 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1179 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1180 unsigned Val = CN->getZExtValue();
1181 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1182 // that the base operand remains free for further matching. If
1183 // the base doesn't end up getting used, a post-processing step
1184 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1185 if (Val == 1 || Val == 2 || Val == 3) {
1186 AM.Scale = 1 << Val;
1187 SDValue ShVal = N.getOperand(0);
1189 // Okay, we know that we have a scale by now. However, if the scaled
1190 // value is an add of something and a constant, we can fold the
1191 // constant into the disp field here.
1192 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1193 AM.IndexReg = ShVal.getOperand(0);
1194 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1195 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1196 if (!foldOffsetIntoAddress(Disp, AM))
1200 AM.IndexReg = ShVal;
1207 // Scale must not be used already.
1208 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1210 SDValue And = N.getOperand(0);
1211 if (And.getOpcode() != ISD::AND) break;
1212 SDValue X = And.getOperand(0);
1214 // We only handle up to 64-bit values here as those are what matter for
1215 // addressing mode optimizations.
1216 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1218 // The mask used for the transform is expected to be post-shift, but we
1219 // found the shift first so just apply the shift to the mask before passing
1221 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1222 !isa<ConstantSDNode>(And.getOperand(1)))
1224 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1226 // Try to fold the mask and shift into the scale, and return false if we
1228 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1233 case ISD::SMUL_LOHI:
1234 case ISD::UMUL_LOHI:
1235 // A mul_lohi where we need the low part can be folded as a plain multiply.
1236 if (N.getResNo() != 0) break;
1239 case X86ISD::MUL_IMM:
1240 // X*[3,5,9] -> X+X*[2,4,8]
1241 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1242 AM.Base_Reg.getNode() == nullptr &&
1243 AM.IndexReg.getNode() == nullptr) {
1244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1245 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1246 CN->getZExtValue() == 9) {
1247 AM.Scale = unsigned(CN->getZExtValue())-1;
1249 SDValue MulVal = N.getOperand(0);
1252 // Okay, we know that we have a scale by now. However, if the scaled
1253 // value is an add of something and a constant, we can fold the
1254 // constant into the disp field here.
1255 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1256 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1257 Reg = MulVal.getOperand(0);
1258 ConstantSDNode *AddVal =
1259 cast<ConstantSDNode>(MulVal.getOperand(1));
1260 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1261 if (foldOffsetIntoAddress(Disp, AM))
1262 Reg = N.getOperand(0);
1264 Reg = N.getOperand(0);
1267 AM.IndexReg = AM.Base_Reg = Reg;
1274 // Given A-B, if A can be completely folded into the address and
1275 // the index field with the index field unused, use -B as the index.
1276 // This is a win if a has multiple parts that can be folded into
1277 // the address. Also, this saves a mov if the base register has
1278 // other uses, since it avoids a two-address sub instruction, however
1279 // it costs an additional mov if the index register has other uses.
1281 // Add an artificial use to this node so that we can keep track of
1282 // it if it gets CSE'd with a different node.
1283 HandleSDNode Handle(N);
1285 // Test if the LHS of the sub can be folded.
1286 X86ISelAddressMode Backup = AM;
1287 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1291 // Test if the index field is free for use.
1292 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1298 SDValue RHS = Handle.getValue().getOperand(1);
1299 // If the RHS involves a register with multiple uses, this
1300 // transformation incurs an extra mov, due to the neg instruction
1301 // clobbering its operand.
1302 if (!RHS.getNode()->hasOneUse() ||
1303 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1304 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1305 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1306 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1307 RHS.getOperand(0).getValueType() == MVT::i32))
1309 // If the base is a register with multiple uses, this
1310 // transformation may save a mov.
1311 // FIXME: Don't rely on DELETED_NODEs.
1312 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1313 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1314 !AM.Base_Reg.getNode()->hasOneUse()) ||
1315 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1317 // If the folded LHS was interesting, this transformation saves
1318 // address arithmetic.
1319 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1320 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1321 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1323 // If it doesn't look like it may be an overall win, don't do it.
1329 // Ok, the transformation is legal and appears profitable. Go for it.
1330 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1331 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1335 // Insert the new nodes into the topological ordering.
1336 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1337 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1342 if (!matchAdd(N, AM, Depth))
1347 // We want to look through a transform in InstCombine and DAGCombiner that
1348 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1349 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1350 // An 'lea' can then be used to match the shift (multiply) and add:
1352 // lea (%rsi, %rdi, 8), %rax
1353 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1354 !matchAdd(N, AM, Depth))
1359 // Perform some heroic transforms on an and of a constant-count shift
1360 // with a constant to enable use of the scaled offset field.
1362 // Scale must not be used already.
1363 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1365 SDValue Shift = N.getOperand(0);
1366 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1367 SDValue X = Shift.getOperand(0);
1369 // We only handle up to 64-bit values here as those are what matter for
1370 // addressing mode optimizations.
1371 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1373 if (!isa<ConstantSDNode>(N.getOperand(1)))
1375 uint64_t Mask = N.getConstantOperandVal(1);
1377 // Try to fold the mask and shift into an extract and scale.
1378 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1381 // Try to fold the mask and shift directly into the scale.
1382 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1385 // Try to swap the mask and shift to place shifts which can be done as
1386 // a scale on the outside of the mask.
1387 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1393 return matchAddressBase(N, AM);
1396 /// Helper for MatchAddress. Add the specified node to the
1397 /// specified addressing mode without any further recursion.
1398 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1399 // Is the base register already occupied?
1400 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1401 // If so, check to see if the scale index register is set.
1402 if (!AM.IndexReg.getNode()) {
1408 // Otherwise, we cannot select it.
1412 // Default, generate it as a register.
1413 AM.BaseType = X86ISelAddressMode::RegBase;
1418 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1419 SDValue &Scale, SDValue &Index,
1420 SDValue &Disp, SDValue &Segment) {
1422 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1425 X86ISelAddressMode AM;
1426 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1427 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1428 if (AddrSpace == 256)
1429 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1430 if (AddrSpace == 257)
1431 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1432 if (AddrSpace == 258)
1433 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1436 Base = Mgs->getBasePtr();
1437 Index = Mgs->getIndex();
1438 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
1439 Scale = getI8Imm(ScalarSize/8, DL);
1441 // If Base is 0, the whole address is in index and the Scale is 1
1442 if (isa<ConstantSDNode>(Base)) {
1443 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1444 "Unexpected base in gather/scatter");
1445 Scale = getI8Imm(1, DL);
1446 Base = CurDAG->getRegister(0, MVT::i32);
1448 if (AM.Segment.getNode())
1449 Segment = AM.Segment;
1451 Segment = CurDAG->getRegister(0, MVT::i32);
1452 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1456 /// Returns true if it is able to pattern match an addressing mode.
1457 /// It returns the operands which make up the maximal addressing mode it can
1458 /// match by reference.
1460 /// Parent is the parent node of the addr operand that is being matched. It
1461 /// is always a load, store, atomic node, or null. It is only null when
1462 /// checking memory operands for inline asm nodes.
1463 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1464 SDValue &Scale, SDValue &Index,
1465 SDValue &Disp, SDValue &Segment) {
1466 X86ISelAddressMode AM;
1469 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1470 // that are not a MemSDNode, and thus don't have proper addrspace info.
1471 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1472 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1473 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1474 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1475 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1476 unsigned AddrSpace =
1477 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1478 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1479 if (AddrSpace == 256)
1480 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1481 if (AddrSpace == 257)
1482 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1483 if (AddrSpace == 258)
1484 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1487 if (matchAddress(N, AM))
1490 MVT VT = N.getSimpleValueType();
1491 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1492 if (!AM.Base_Reg.getNode())
1493 AM.Base_Reg = CurDAG->getRegister(0, VT);
1496 if (!AM.IndexReg.getNode())
1497 AM.IndexReg = CurDAG->getRegister(0, VT);
1499 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1503 /// Match a scalar SSE load. In particular, we want to match a load whose top
1504 /// elements are either undef or zeros. The load flavor is derived from the
1505 /// type of N, which is either v4f32 or v2f64.
1508 /// PatternChainNode: this is the matched node that has a chain input and
1510 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1511 SDValue N, SDValue &Base,
1512 SDValue &Scale, SDValue &Index,
1513 SDValue &Disp, SDValue &Segment,
1514 SDValue &PatternNodeWithChain) {
1515 // We can allow a full vector load here since narrowing a load is ok.
1516 if (ISD::isNON_EXTLoad(N.getNode())) {
1517 PatternNodeWithChain = N;
1518 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1519 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1520 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1521 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1526 // We can also match the special zero extended load opcode.
1527 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1528 PatternNodeWithChain = N;
1529 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1530 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1531 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1532 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1537 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1538 // once. Otherwise the load might get duplicated and the chain output of the
1539 // duplicate load will not be observed by all dependencies.
1540 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
1541 PatternNodeWithChain = N.getOperand(0);
1542 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1543 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1544 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1545 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1546 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1551 // Also handle the case where we explicitly require zeros in the top
1552 // elements. This is a vector shuffle from the zero vector.
1553 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1554 // Check to see if the top elements are all zeros (or bitcast of zeros).
1555 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1556 N.getOperand(0).getNode()->hasOneUse()) {
1557 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1558 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1559 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1560 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1561 // Okay, this is a zero extending load. Fold it.
1562 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1563 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1572 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1573 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1574 uint64_t ImmVal = CN->getZExtValue();
1575 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1578 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1582 // In static codegen with small code model, we can get the address of a label
1583 // into a register with 'movl'. TableGen has already made sure we're looking
1584 // at a label of some kind.
1585 assert(N->getOpcode() == X86ISD::Wrapper &&
1586 "Unexpected node type for MOV32ri64");
1587 N = N.getOperand(0);
1589 // At least GNU as does not accept 'movl' for TPOFF relocations.
1590 // FIXME: We could use 'movl' when we know we are targeting MC.
1591 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
1595 if (N->getOpcode() != ISD::TargetGlobalAddress)
1596 return TM.getCodeModel() == CodeModel::Small;
1598 Optional<ConstantRange> CR =
1599 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1601 return TM.getCodeModel() == CodeModel::Small;
1603 return CR->getUnsignedMax().ult(1ull << 32);
1606 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1607 SDValue &Scale, SDValue &Index,
1608 SDValue &Disp, SDValue &Segment) {
1609 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1612 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1615 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1616 if (RN && RN->getReg() == 0)
1617 Base = CurDAG->getRegister(0, MVT::i64);
1618 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1619 // Base could already be %rip, particularly in the x32 ABI.
1620 Base = SDValue(CurDAG->getMachineNode(
1621 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1622 CurDAG->getTargetConstant(0, DL, MVT::i64),
1624 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1628 RN = dyn_cast<RegisterSDNode>(Index);
1629 if (RN && RN->getReg() == 0)
1630 Index = CurDAG->getRegister(0, MVT::i64);
1632 assert(Index.getValueType() == MVT::i32 &&
1633 "Expect to be extending 32-bit registers for use in LEA");
1634 Index = SDValue(CurDAG->getMachineNode(
1635 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1636 CurDAG->getTargetConstant(0, DL, MVT::i64),
1638 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1646 /// Calls SelectAddr and determines if the maximal addressing
1647 /// mode it matches can be cost effectively emitted as an LEA instruction.
1648 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1649 SDValue &Base, SDValue &Scale,
1650 SDValue &Index, SDValue &Disp,
1652 X86ISelAddressMode AM;
1654 // Save the DL and VT before calling matchAddress, it can invalidate N.
1656 MVT VT = N.getSimpleValueType();
1658 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1660 SDValue Copy = AM.Segment;
1661 SDValue T = CurDAG->getRegister(0, MVT::i32);
1663 if (matchAddress(N, AM))
1665 assert (T == AM.Segment);
1668 unsigned Complexity = 0;
1669 if (AM.BaseType == X86ISelAddressMode::RegBase)
1670 if (AM.Base_Reg.getNode())
1673 AM.Base_Reg = CurDAG->getRegister(0, VT);
1674 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1677 if (AM.IndexReg.getNode())
1680 AM.IndexReg = CurDAG->getRegister(0, VT);
1682 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1687 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1688 // to a LEA. This is determined with some experimentation but is by no means
1689 // optimal (especially for code size consideration). LEA is nice because of
1690 // its three-address nature. Tweak the cost function again when we can run
1691 // convertToThreeAddress() at register allocation time.
1692 if (AM.hasSymbolicDisplacement()) {
1693 // For X86-64, always use LEA to materialize RIP-relative addresses.
1694 if (Subtarget->is64Bit())
1700 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1703 // If it isn't worth using an LEA, reject it.
1704 if (Complexity <= 2)
1707 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
1711 /// This is only run on TargetGlobalTLSAddress nodes.
1712 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1713 SDValue &Scale, SDValue &Index,
1714 SDValue &Disp, SDValue &Segment) {
1715 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1716 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1718 X86ISelAddressMode AM;
1719 AM.GV = GA->getGlobal();
1720 AM.Disp += GA->getOffset();
1721 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1722 AM.SymbolFlags = GA->getTargetFlags();
1724 if (N.getValueType() == MVT::i32) {
1726 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1728 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1731 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1735 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1736 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1737 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1742 // Keep track of the original value type and whether this value was
1743 // truncated. If we see a truncation from pointer type to VT that truncates
1744 // bits that are known to be zero, we can use a narrow reference.
1745 EVT VT = N.getValueType();
1746 bool WasTruncated = false;
1747 if (N.getOpcode() == ISD::TRUNCATE) {
1748 WasTruncated = true;
1749 N = N.getOperand(0);
1752 if (N.getOpcode() != X86ISD::Wrapper)
1755 // We can only use non-GlobalValues as immediates if they were not truncated,
1756 // as we do not have any range information. If we have a GlobalValue and the
1757 // address was not truncated, we can select it as an operand directly.
1758 unsigned Opc = N.getOperand(0)->getOpcode();
1759 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1760 Op = N.getOperand(0);
1761 // We can only select the operand directly if we didn't have to look past a
1763 return !WasTruncated;
1766 // Check that the global's range fits into VT.
1767 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1768 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1769 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1772 // Okay, we can use a narrow reference.
1773 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1774 GA->getOffset(), GA->getTargetFlags());
1778 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1779 SDValue &Base, SDValue &Scale,
1780 SDValue &Index, SDValue &Disp,
1782 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1783 !IsProfitableToFold(N, P, P) ||
1784 !IsLegalToFold(N, P, P, OptLevel))
1787 return selectAddr(N.getNode(),
1788 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1791 /// Return an SDNode that returns the value of the global base register.
1792 /// Output instructions required to initialize the global base register,
1794 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1795 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1796 auto &DL = MF->getDataLayout();
1797 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1800 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1801 if (N->getOpcode() == ISD::TRUNCATE)
1802 N = N->getOperand(0).getNode();
1803 if (N->getOpcode() != X86ISD::Wrapper)
1806 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1810 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1811 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1812 CR->getSignedMax().slt(1ull << Width);
1815 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1816 /// or OF bits to be accurate.
1817 static bool hasNoSignedComparisonUses(SDNode *N) {
1818 // Examine each user of the node.
1819 for (SDNode::use_iterator UI = N->use_begin(),
1820 UE = N->use_end(); UI != UE; ++UI) {
1821 // Only examine CopyToReg uses.
1822 if (UI->getOpcode() != ISD::CopyToReg)
1824 // Only examine CopyToReg uses that copy to EFLAGS.
1825 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1828 // Examine each user of the CopyToReg use.
1829 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1830 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1831 // Only examine the Flag result.
1832 if (FlagUI.getUse().getResNo() != 1) continue;
1833 // Anything unusual: assume conservatively.
1834 if (!FlagUI->isMachineOpcode()) return false;
1835 // Examine the opcode of the user.
1836 switch (FlagUI->getMachineOpcode()) {
1837 // These comparisons don't treat the most significant bit specially.
1838 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1839 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1840 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1841 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1842 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1843 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1844 case X86::CMOVA16rr: case X86::CMOVA16rm:
1845 case X86::CMOVA32rr: case X86::CMOVA32rm:
1846 case X86::CMOVA64rr: case X86::CMOVA64rm:
1847 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1848 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1849 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1850 case X86::CMOVB16rr: case X86::CMOVB16rm:
1851 case X86::CMOVB32rr: case X86::CMOVB32rm:
1852 case X86::CMOVB64rr: case X86::CMOVB64rm:
1853 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1854 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1855 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1856 case X86::CMOVE16rr: case X86::CMOVE16rm:
1857 case X86::CMOVE32rr: case X86::CMOVE32rm:
1858 case X86::CMOVE64rr: case X86::CMOVE64rm:
1859 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1860 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1861 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1862 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1863 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1864 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1865 case X86::CMOVP16rr: case X86::CMOVP16rm:
1866 case X86::CMOVP32rr: case X86::CMOVP32rm:
1867 case X86::CMOVP64rr: case X86::CMOVP64rm:
1869 // Anything else: assume conservatively.
1870 default: return false;
1877 /// Check whether or not the chain ending in StoreNode is suitable for doing
1878 /// the {load; increment or decrement; store} to modify transformation.
1879 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1880 SDValue StoredVal, SelectionDAG *CurDAG,
1881 LoadSDNode* &LoadNode, SDValue &InputChain) {
1883 // is the value stored the result of a DEC or INC?
1884 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1886 // is the stored value result 0 of the load?
1887 if (StoredVal.getResNo() != 0) return false;
1889 // are there other uses of the loaded value than the inc or dec?
1890 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1892 // is the store non-extending and non-indexed?
1893 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1896 SDValue Load = StoredVal->getOperand(0);
1897 // Is the stored value a non-extending and non-indexed load?
1898 if (!ISD::isNormalLoad(Load.getNode())) return false;
1900 // Return LoadNode by reference.
1901 LoadNode = cast<LoadSDNode>(Load);
1902 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1903 EVT LdVT = LoadNode->getMemoryVT();
1904 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1908 // Is store the only read of the loaded value?
1909 if (!Load.hasOneUse())
1912 // Is the address of the store the same as the load?
1913 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1914 LoadNode->getOffset() != StoreNode->getOffset())
1917 // Check if the chain is produced by the load or is a TokenFactor with
1918 // the load output chain as an operand. Return InputChain by reference.
1919 SDValue Chain = StoreNode->getChain();
1921 bool ChainCheck = false;
1922 if (Chain == Load.getValue(1)) {
1924 InputChain = LoadNode->getChain();
1925 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1926 SmallVector<SDValue, 4> ChainOps;
1927 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1928 SDValue Op = Chain.getOperand(i);
1929 if (Op == Load.getValue(1)) {
1931 // Drop Load, but keep its chain. No cycle check necessary.
1932 ChainOps.push_back(Load.getOperand(0));
1936 // Make sure using Op as part of the chain would not cause a cycle here.
1937 // In theory, we could check whether the chain node is a predecessor of
1938 // the load. But that can be very expensive. Instead visit the uses and
1939 // make sure they all have smaller node id than the load.
1940 int LoadId = LoadNode->getNodeId();
1941 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1942 UE = UI->use_end(); UI != UE; ++UI) {
1943 if (UI.getUse().getResNo() != 0)
1945 if (UI->getNodeId() > LoadId)
1949 ChainOps.push_back(Op);
1953 // Make a new TokenFactor with all the other input chains except
1955 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1956 MVT::Other, ChainOps);
1964 /// Get the appropriate X86 opcode for an in-memory increment or decrement.
1965 /// Opc should be X86ISD::DEC or X86ISD::INC.
1966 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1967 if (Opc == X86ISD::DEC) {
1968 if (LdVT == MVT::i64) return X86::DEC64m;
1969 if (LdVT == MVT::i32) return X86::DEC32m;
1970 if (LdVT == MVT::i16) return X86::DEC16m;
1971 if (LdVT == MVT::i8) return X86::DEC8m;
1973 assert(Opc == X86ISD::INC && "unrecognized opcode");
1974 if (LdVT == MVT::i64) return X86::INC64m;
1975 if (LdVT == MVT::i32) return X86::INC32m;
1976 if (LdVT == MVT::i16) return X86::INC16m;
1977 if (LdVT == MVT::i8) return X86::INC8m;
1979 llvm_unreachable("unrecognized size for LdVT");
1982 void X86DAGToDAGISel::Select(SDNode *Node) {
1983 MVT NVT = Node->getSimpleValueType(0);
1985 unsigned Opcode = Node->getOpcode();
1988 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1990 if (Node->isMachineOpcode()) {
1991 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
1992 Node->setNodeId(-1);
1993 return; // Already selected.
1999 if (Subtarget->isTargetNaCl())
2000 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2001 // leave the instruction alone.
2003 if (Subtarget->isTarget64BitILP32()) {
2004 // Converts a 32-bit register to a 64-bit, zero-extended version of
2005 // it. This is needed because x86-64 can do many things, but jmp %r32
2006 // ain't one of them.
2007 const SDValue &Target = Node->getOperand(1);
2008 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2009 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2010 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2011 Node->getOperand(0), ZextTarget);
2012 ReplaceNode(Node, Brind.getNode());
2013 SelectCode(ZextTarget.getNode());
2014 SelectCode(Brind.getNode());
2019 case X86ISD::GlobalBaseReg:
2020 ReplaceNode(Node, getGlobalBaseReg());
2023 case X86ISD::SHRUNKBLEND: {
2024 // SHRUNKBLEND selects like a regular VSELECT.
2025 SDValue VSelect = CurDAG->getNode(
2026 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2027 Node->getOperand(1), Node->getOperand(2));
2028 ReplaceUses(SDValue(Node, 0), VSelect);
2029 SelectCode(VSelect.getNode());
2030 // We already called ReplaceUses.
2037 // For operations of the form (x << C1) op C2, check if we can use a smaller
2038 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2039 SDValue N0 = Node->getOperand(0);
2040 SDValue N1 = Node->getOperand(1);
2042 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2045 // i8 is unshrinkable, i16 should be promoted to i32.
2046 if (NVT != MVT::i32 && NVT != MVT::i64)
2049 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2050 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2051 if (!Cst || !ShlCst)
2054 int64_t Val = Cst->getSExtValue();
2055 uint64_t ShlVal = ShlCst->getZExtValue();
2057 // Make sure that we don't change the operation by removing bits.
2058 // This only matters for OR and XOR, AND is unaffected.
2059 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2060 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2063 unsigned ShlOp, AddOp, Op;
2066 // Check the minimum bitwidth for the new constant.
2067 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2068 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2069 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2070 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2072 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2075 // Bail if there is no smaller encoding.
2079 switch (NVT.SimpleTy) {
2080 default: llvm_unreachable("Unsupported VT!");
2082 assert(CstVT == MVT::i8);
2083 ShlOp = X86::SHL32ri;
2084 AddOp = X86::ADD32rr;
2087 default: llvm_unreachable("Impossible opcode");
2088 case ISD::AND: Op = X86::AND32ri8; break;
2089 case ISD::OR: Op = X86::OR32ri8; break;
2090 case ISD::XOR: Op = X86::XOR32ri8; break;
2094 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2095 ShlOp = X86::SHL64ri;
2096 AddOp = X86::ADD64rr;
2099 default: llvm_unreachable("Impossible opcode");
2100 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2101 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2102 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2107 // Emit the smaller op and the shift.
2108 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2109 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2111 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2114 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2115 getI8Imm(ShlVal, dl));
2119 case X86ISD::SMUL8: {
2120 SDValue N0 = Node->getOperand(0);
2121 SDValue N1 = Node->getOperand(1);
2123 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2125 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2126 N0, SDValue()).getValue(1);
2128 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2129 SDValue Ops[] = {N1, InFlag};
2130 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2132 ReplaceNode(Node, CNode);
2136 case X86ISD::UMUL: {
2137 SDValue N0 = Node->getOperand(0);
2138 SDValue N1 = Node->getOperand(1);
2141 switch (NVT.SimpleTy) {
2142 default: llvm_unreachable("Unsupported VT!");
2143 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2144 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2145 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2146 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2149 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2150 N0, SDValue()).getValue(1);
2152 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2153 SDValue Ops[] = {N1, InFlag};
2154 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2156 ReplaceNode(Node, CNode);
2160 case ISD::SMUL_LOHI:
2161 case ISD::UMUL_LOHI: {
2162 SDValue N0 = Node->getOperand(0);
2163 SDValue N1 = Node->getOperand(1);
2165 bool isSigned = Opcode == ISD::SMUL_LOHI;
2166 bool hasBMI2 = Subtarget->hasBMI2();
2168 switch (NVT.SimpleTy) {
2169 default: llvm_unreachable("Unsupported VT!");
2170 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2171 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2172 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2173 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2174 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2175 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2178 switch (NVT.SimpleTy) {
2179 default: llvm_unreachable("Unsupported VT!");
2180 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2181 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2182 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2183 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2187 unsigned SrcReg, LoReg, HiReg;
2189 default: llvm_unreachable("Unknown MUL opcode!");
2192 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2196 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2200 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2204 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2207 SrcReg = X86::EDX; LoReg = HiReg = 0;
2210 SrcReg = X86::RDX; LoReg = HiReg = 0;
2214 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2215 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2216 // Multiply is commmutative.
2218 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2223 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2224 N0, SDValue()).getValue(1);
2225 SDValue ResHi, ResLo;
2229 MachineSDNode *CNode = nullptr;
2230 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2232 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2233 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2234 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2235 ResHi = SDValue(CNode, 0);
2236 ResLo = SDValue(CNode, 1);
2237 Chain = SDValue(CNode, 2);
2238 InFlag = SDValue(CNode, 3);
2240 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2241 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2242 Chain = SDValue(CNode, 0);
2243 InFlag = SDValue(CNode, 1);
2246 // Update the chain.
2247 ReplaceUses(N1.getValue(1), Chain);
2248 // Record the mem-refs
2249 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2251 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2252 MemOp[0] = LoadNode->getMemOperand();
2253 CNode->setMemRefs(MemOp, MemOp + 1);
2256 SDValue Ops[] = { N1, InFlag };
2257 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2258 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2259 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2260 ResHi = SDValue(CNode, 0);
2261 ResLo = SDValue(CNode, 1);
2262 InFlag = SDValue(CNode, 2);
2264 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2265 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2266 InFlag = SDValue(CNode, 0);
2270 // Prevent use of AH in a REX instruction by referencing AX instead.
2271 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2272 !SDValue(Node, 1).use_empty()) {
2273 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2274 X86::AX, MVT::i16, InFlag);
2275 InFlag = Result.getValue(2);
2276 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2278 if (!SDValue(Node, 0).use_empty())
2279 ReplaceUses(SDValue(Node, 1),
2280 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2282 // Shift AX down 8 bits.
2283 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2285 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2287 // Then truncate it down to i8.
2288 ReplaceUses(SDValue(Node, 1),
2289 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2291 // Copy the low half of the result, if it is needed.
2292 if (!SDValue(Node, 0).use_empty()) {
2293 if (!ResLo.getNode()) {
2294 assert(LoReg && "Register for low half is not defined!");
2295 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2297 InFlag = ResLo.getValue(2);
2299 ReplaceUses(SDValue(Node, 0), ResLo);
2300 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2302 // Copy the high half of the result, if it is needed.
2303 if (!SDValue(Node, 1).use_empty()) {
2304 if (!ResHi.getNode()) {
2305 assert(HiReg && "Register for high half is not defined!");
2306 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2308 InFlag = ResHi.getValue(2);
2310 ReplaceUses(SDValue(Node, 1), ResHi);
2311 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2319 case X86ISD::SDIVREM8_SEXT_HREG:
2320 case X86ISD::UDIVREM8_ZEXT_HREG: {
2321 SDValue N0 = Node->getOperand(0);
2322 SDValue N1 = Node->getOperand(1);
2324 bool isSigned = (Opcode == ISD::SDIVREM ||
2325 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2327 switch (NVT.SimpleTy) {
2328 default: llvm_unreachable("Unsupported VT!");
2329 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2330 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2331 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2332 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2335 switch (NVT.SimpleTy) {
2336 default: llvm_unreachable("Unsupported VT!");
2337 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2338 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2339 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2340 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2344 unsigned LoReg, HiReg, ClrReg;
2345 unsigned SExtOpcode;
2346 switch (NVT.SimpleTy) {
2347 default: llvm_unreachable("Unsupported VT!");
2349 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2350 SExtOpcode = X86::CBW;
2353 LoReg = X86::AX; HiReg = X86::DX;
2355 SExtOpcode = X86::CWD;
2358 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2359 SExtOpcode = X86::CDQ;
2362 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2363 SExtOpcode = X86::CQO;
2367 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2368 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2369 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2372 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2373 // Special case for div8, just use a move with zero extension to AX to
2374 // clear the upper 8 bits (AH).
2375 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2376 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2377 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2379 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2380 MVT::Other, Ops), 0);
2381 Chain = Move.getValue(1);
2382 ReplaceUses(N0.getValue(1), Chain);
2385 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2386 Chain = CurDAG->getEntryNode();
2388 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2389 InFlag = Chain.getValue(1);
2392 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2393 LoReg, N0, SDValue()).getValue(1);
2394 if (isSigned && !signBitIsZero) {
2395 // Sign extend the low part into the high part.
2397 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2399 // Zero out the high part, effectively zero extending the input.
2400 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2401 switch (NVT.SimpleTy) {
2404 SDValue(CurDAG->getMachineNode(
2405 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2406 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2414 SDValue(CurDAG->getMachineNode(
2415 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2416 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2417 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2422 llvm_unreachable("Unexpected division source");
2425 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2426 ClrNode, InFlag).getValue(1);
2431 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2434 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2435 InFlag = SDValue(CNode, 1);
2436 // Update the chain.
2437 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2440 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2443 // Prevent use of AH in a REX instruction by explicitly copying it to
2444 // an ABCD_L register.
2446 // The current assumption of the register allocator is that isel
2447 // won't generate explicit references to the GR8_ABCD_H registers. If
2448 // the allocator and/or the backend get enhanced to be more robust in
2449 // that regard, this can be, and should be, removed.
2450 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2451 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2452 unsigned AHExtOpcode =
2453 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2455 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2456 MVT::Glue, AHCopy, InFlag);
2457 SDValue Result(RNode, 0);
2458 InFlag = SDValue(RNode, 1);
2460 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2461 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2462 if (Node->getValueType(1) == MVT::i64) {
2463 // It's not possible to directly movsx AH to a 64bit register, because
2464 // the latter needs the REX prefix, but the former can't have it.
2465 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2466 "Unexpected i64 sext of h-register");
2468 SDValue(CurDAG->getMachineNode(
2469 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2470 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2471 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2477 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2479 ReplaceUses(SDValue(Node, 1), Result);
2480 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2482 // Copy the division (low) result, if it is needed.
2483 if (!SDValue(Node, 0).use_empty()) {
2484 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2485 LoReg, NVT, InFlag);
2486 InFlag = Result.getValue(2);
2487 ReplaceUses(SDValue(Node, 0), Result);
2488 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2490 // Copy the remainder (high) result, if it is needed.
2491 if (!SDValue(Node, 1).use_empty()) {
2492 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2493 HiReg, NVT, InFlag);
2494 InFlag = Result.getValue(2);
2495 ReplaceUses(SDValue(Node, 1), Result);
2496 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2503 // Sometimes a SUB is used to perform comparison.
2504 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2505 // This node is not a CMP.
2507 SDValue N0 = Node->getOperand(0);
2508 SDValue N1 = Node->getOperand(1);
2510 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2511 hasNoSignedComparisonUses(Node))
2512 N0 = N0.getOperand(0);
2514 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2515 // use a smaller encoding.
2516 // Look past the truncate if CMP is the only use of it.
2517 if ((N0.getNode()->getOpcode() == ISD::AND ||
2518 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2519 N0.getNode()->hasOneUse() &&
2520 N0.getValueType() != MVT::i8 &&
2521 X86::isZeroNode(N1)) {
2522 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2525 // For example, convert "testl %eax, $8" to "testb %al, $8"
2526 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2527 (!(C->getZExtValue() & 0x80) ||
2528 hasNoSignedComparisonUses(Node))) {
2529 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2530 SDValue Reg = N0.getOperand(0);
2532 // On x86-32, only the ABCD registers have 8-bit subregisters.
2533 if (!Subtarget->is64Bit()) {
2534 const TargetRegisterClass *TRC;
2535 switch (N0.getSimpleValueType().SimpleTy) {
2536 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2537 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2538 default: llvm_unreachable("Unsupported TEST operand type!");
2540 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2541 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2542 Reg.getValueType(), Reg, RC), 0);
2545 // Extract the l-register.
2546 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2550 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2552 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2553 // one, do not call ReplaceAllUsesWith.
2554 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2555 SDValue(NewNode, 0));
2559 // For example, "testl %eax, $2048" to "testb %ah, $8".
2560 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2561 (!(C->getZExtValue() & 0x8000) ||
2562 hasNoSignedComparisonUses(Node))) {
2563 // Shift the immediate right by 8 bits.
2564 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2566 SDValue Reg = N0.getOperand(0);
2568 // Put the value in an ABCD register.
2569 const TargetRegisterClass *TRC;
2570 switch (N0.getSimpleValueType().SimpleTy) {
2571 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2572 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2573 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2574 default: llvm_unreachable("Unsupported TEST operand type!");
2576 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2577 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2578 Reg.getValueType(), Reg, RC), 0);
2580 // Extract the h-register.
2581 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2584 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2585 // target GR8_NOREX registers, so make sure the register class is
2587 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2588 MVT::i32, Subreg, ShiftedImm);
2589 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2590 // one, do not call ReplaceAllUsesWith.
2591 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2592 SDValue(NewNode, 0));
2596 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2597 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2598 N0.getValueType() != MVT::i16 &&
2599 (!(C->getZExtValue() & 0x8000) ||
2600 hasNoSignedComparisonUses(Node))) {
2601 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2603 SDValue Reg = N0.getOperand(0);
2605 // Extract the 16-bit subregister.
2606 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2610 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2612 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2613 // one, do not call ReplaceAllUsesWith.
2614 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2615 SDValue(NewNode, 0));
2619 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2620 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2621 N0.getValueType() == MVT::i64 &&
2622 (!(C->getZExtValue() & 0x80000000) ||
2623 hasNoSignedComparisonUses(Node))) {
2624 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2626 SDValue Reg = N0.getOperand(0);
2628 // Extract the 32-bit subregister.
2629 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2633 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2635 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2636 // one, do not call ReplaceAllUsesWith.
2637 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2638 SDValue(NewNode, 0));
2645 // Change a chain of {load; incr or dec; store} of the same value into
2646 // a simple increment or decrement through memory of that value, if the
2647 // uses of the modified value and its address are suitable.
2648 // The DEC64m tablegen pattern is currently not able to match the case where
2649 // the EFLAGS on the original DEC are used. (This also applies to
2650 // {INC,DEC}X{64,32,16,8}.)
2651 // We'll need to improve tablegen to allow flags to be transferred from a
2652 // node in the pattern to the result node. probably with a new keyword
2653 // for example, we have this
2654 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2655 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2656 // (implicit EFLAGS)]>;
2657 // but maybe need something like this
2658 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2659 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2660 // (transferrable EFLAGS)]>;
2662 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2663 SDValue StoredVal = StoreNode->getOperand(1);
2664 unsigned Opc = StoredVal->getOpcode();
2666 LoadSDNode *LoadNode = nullptr;
2668 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2669 LoadNode, InputChain))
2672 SDValue Base, Scale, Index, Disp, Segment;
2673 if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
2674 Base, Scale, Index, Disp, Segment))
2677 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2678 MemOp[0] = StoreNode->getMemOperand();
2679 MemOp[1] = LoadNode->getMemOperand();
2680 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2681 EVT LdVT = LoadNode->getMemoryVT();
2682 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2683 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2685 MVT::i32, MVT::Other, Ops);
2686 Result->setMemRefs(MemOp, MemOp + 2);
2688 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2689 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2690 CurDAG->RemoveDeadNode(Node);
2698 bool X86DAGToDAGISel::
2699 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2700 std::vector<SDValue> &OutOps) {
2701 SDValue Op0, Op1, Op2, Op3, Op4;
2702 switch (ConstraintID) {
2704 llvm_unreachable("Unexpected asm memory constraint");
2705 case InlineAsm::Constraint_i:
2706 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2707 // be an immediate and not a memory constraint.
2709 case InlineAsm::Constraint_o: // offsetable ??
2710 case InlineAsm::Constraint_v: // not offsetable ??
2711 case InlineAsm::Constraint_m: // memory
2712 case InlineAsm::Constraint_X:
2713 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2718 OutOps.push_back(Op0);
2719 OutOps.push_back(Op1);
2720 OutOps.push_back(Op2);
2721 OutOps.push_back(Op3);
2722 OutOps.push_back(Op4);
2726 /// This pass converts a legalized DAG into a X86-specific DAG,
2727 /// ready for instruction scheduling.
2728 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2729 CodeGenOpt::Level OptLevel) {
2730 return new X86DAGToDAGISel(TM, OptLevel);