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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
39 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
41 //===----------------------------------------------------------------------===//
42 // Pattern Matcher Implementation
43 //===----------------------------------------------------------------------===//
46 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
47 /// SDValue's instead of register numbers for the leaves of the matched
49 struct X86ISelAddressMode {
55 // This is really a union, discriminated by BaseType!
63 const GlobalValue *GV;
65 const BlockAddress *BlockAddr;
68 unsigned Align; // CP alignment.
69 unsigned char SymbolFlags; // X86II::MO_*
72 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
73 Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
74 SymbolFlags(X86II::MO_NO_FLAG) {
77 bool hasSymbolicDisplacement() const {
78 return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
81 bool hasBaseOrIndexReg() const {
82 return IndexReg.getNode() != 0 || Base_Reg.getNode() != 0;
85 /// isRIPRelative - Return true if this addressing mode is already RIP
87 bool isRIPRelative() const {
88 if (BaseType != RegBase) return false;
89 if (RegisterSDNode *RegNode =
90 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
91 return RegNode->getReg() == X86::RIP;
95 void setBaseReg(SDValue Reg) {
100 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
102 dbgs() << "X86ISelAddressMode " << this << '\n';
103 dbgs() << "Base_Reg ";
104 if (Base_Reg.getNode() != 0)
105 Base_Reg.getNode()->dump();
108 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
109 << " Scale" << Scale << '\n'
111 if (IndexReg.getNode() != 0)
112 IndexReg.getNode()->dump();
115 dbgs() << " Disp " << Disp << '\n'
132 dbgs() << " JT" << JT << " Align" << Align << '\n';
139 //===--------------------------------------------------------------------===//
140 /// ISel - X86 specific code to select X86 machine instructions for
141 /// SelectionDAG operations.
143 class X86DAGToDAGISel : public SelectionDAGISel {
144 /// X86Lowering - This object fully describes how to lower LLVM code to an
145 /// X86-specific SelectionDAG.
146 const X86TargetLowering &X86Lowering;
148 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
149 /// make the right decision when generating code for different targets.
150 const X86Subtarget *Subtarget;
152 /// OptForSize - If true, selector should try to optimize for code size
153 /// instead of performance.
157 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
158 : SelectionDAGISel(tm, OptLevel),
159 X86Lowering(*tm.getTargetLowering()),
160 Subtarget(&tm.getSubtarget<X86Subtarget>()),
163 virtual const char *getPassName() const {
164 return "X86 DAG->DAG Instruction Selection";
167 virtual void EmitFunctionEntryCode();
169 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
171 virtual void PreprocessISelDAG();
173 inline bool immSext8(SDNode *N) const {
174 return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
177 // i64immSExt32 predicate - True if the 64-bit immediate fits in a 32-bit
178 // sign extended field.
179 inline bool i64immSExt32(SDNode *N) const {
180 uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
181 return (int64_t)v == (int32_t)v;
184 // Include the pieces autogenerated from the target description.
185 #include "X86GenDAGISel.inc"
188 SDNode *Select(SDNode *N);
189 SDNode *SelectGather(SDNode *N, unsigned Opc);
190 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
191 SDNode *SelectAtomicLoadArith(SDNode *Node, EVT NVT);
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 MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
199 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
200 bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
201 SDValue &Scale, SDValue &Index, SDValue &Disp,
203 bool SelectMOV64Imm32(SDValue N, SDValue &Imm);
204 bool SelectLEAAddr(SDValue N, SDValue &Base,
205 SDValue &Scale, SDValue &Index, SDValue &Disp,
207 bool SelectTLSADDRAddr(SDValue N, SDValue &Base,
208 SDValue &Scale, SDValue &Index, SDValue &Disp,
210 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
211 SDValue &Base, SDValue &Scale,
212 SDValue &Index, SDValue &Disp,
214 SDValue &NodeWithChain);
216 bool TryFoldLoad(SDNode *P, SDValue N,
217 SDValue &Base, SDValue &Scale,
218 SDValue &Index, SDValue &Disp,
221 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
222 /// inline asm expressions.
223 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
225 std::vector<SDValue> &OutOps);
227 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
229 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
230 SDValue &Scale, SDValue &Index,
231 SDValue &Disp, SDValue &Segment) {
232 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
233 CurDAG->getTargetFrameIndex(AM.Base_FrameIndex, TLI.getPointerTy()) :
235 Scale = getI8Imm(AM.Scale);
237 // These are 32-bit even in 64-bit mode since RIP relative offset
240 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
244 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
245 AM.Align, AM.Disp, AM.SymbolFlags);
247 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
248 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
249 } else if (AM.JT != -1) {
250 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
251 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
252 } else if (AM.BlockAddr)
253 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
256 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
258 if (AM.Segment.getNode())
259 Segment = AM.Segment;
261 Segment = CurDAG->getRegister(0, MVT::i32);
264 /// getI8Imm - Return a target constant with the specified value, of type
266 inline SDValue getI8Imm(unsigned Imm) {
267 return CurDAG->getTargetConstant(Imm, MVT::i8);
270 /// getI32Imm - Return a target constant with the specified value, of type
272 inline SDValue getI32Imm(unsigned Imm) {
273 return CurDAG->getTargetConstant(Imm, MVT::i32);
276 /// getGlobalBaseReg - Return an SDNode that returns the value of
277 /// the global base register. Output instructions required to
278 /// initialize the global base register, if necessary.
280 SDNode *getGlobalBaseReg();
282 /// getTargetMachine - Return a reference to the TargetMachine, casted
283 /// to the target-specific type.
284 const X86TargetMachine &getTargetMachine() const {
285 return static_cast<const X86TargetMachine &>(TM);
288 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
289 /// to the target-specific type.
290 const X86InstrInfo *getInstrInfo() const {
291 return getTargetMachine().getInstrInfo();
298 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
299 if (OptLevel == CodeGenOpt::None) return false;
304 if (N.getOpcode() != ISD::LOAD)
307 // If N is a load, do additional profitability checks.
309 switch (U->getOpcode()) {
322 SDValue Op1 = U->getOperand(1);
324 // If the other operand is a 8-bit immediate we should fold the immediate
325 // instead. This reduces code size.
327 // movl 4(%esp), %eax
331 // addl 4(%esp), %eax
332 // The former is 2 bytes shorter. In case where the increment is 1, then
333 // the saving can be 4 bytes (by using incl %eax).
334 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
335 if (Imm->getAPIntValue().isSignedIntN(8))
338 // If the other operand is a TLS address, we should fold it instead.
341 // leal i@NTPOFF(%eax), %eax
343 // movl $i@NTPOFF, %eax
345 // if the block also has an access to a second TLS address this will save
347 // FIXME: This is probably also true for non TLS addresses.
348 if (Op1.getOpcode() == X86ISD::Wrapper) {
349 SDValue Val = Op1.getOperand(0);
350 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
360 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
361 /// load's chain operand and move load below the call's chain operand.
362 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
363 SDValue Call, SDValue OrigChain) {
364 SmallVector<SDValue, 8> Ops;
365 SDValue Chain = OrigChain.getOperand(0);
366 if (Chain.getNode() == Load.getNode())
367 Ops.push_back(Load.getOperand(0));
369 assert(Chain.getOpcode() == ISD::TokenFactor &&
370 "Unexpected chain operand");
371 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
372 if (Chain.getOperand(i).getNode() == Load.getNode())
373 Ops.push_back(Load.getOperand(0));
375 Ops.push_back(Chain.getOperand(i));
377 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load),
378 MVT::Other, &Ops[0], Ops.size());
380 Ops.push_back(NewChain);
382 for (unsigned i = 1, e = OrigChain.getNumOperands(); i != e; ++i)
383 Ops.push_back(OrigChain.getOperand(i));
384 CurDAG->UpdateNodeOperands(OrigChain.getNode(), &Ops[0], Ops.size());
385 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
386 Load.getOperand(1), Load.getOperand(2));
388 unsigned NumOps = Call.getNode()->getNumOperands();
390 Ops.push_back(SDValue(Load.getNode(), 1));
391 for (unsigned i = 1, e = NumOps; i != e; ++i)
392 Ops.push_back(Call.getOperand(i));
393 CurDAG->UpdateNodeOperands(Call.getNode(), &Ops[0], NumOps);
396 /// isCalleeLoad - Return true if call address is a load and it can be
397 /// moved below CALLSEQ_START and the chains leading up to the call.
398 /// Return the CALLSEQ_START by reference as a second output.
399 /// In the case of a tail call, there isn't a callseq node between the call
400 /// chain and the load.
401 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
402 // The transformation is somewhat dangerous if the call's chain was glued to
403 // the call. After MoveBelowOrigChain the load is moved between the call and
404 // the chain, this can create a cycle if the load is not folded. So it is
405 // *really* important that we are sure the load will be folded.
406 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
408 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
411 LD->getAddressingMode() != ISD::UNINDEXED ||
412 LD->getExtensionType() != ISD::NON_EXTLOAD)
415 // Now let's find the callseq_start.
416 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
417 if (!Chain.hasOneUse())
419 Chain = Chain.getOperand(0);
422 if (!Chain.getNumOperands())
424 // Since we are not checking for AA here, conservatively abort if the chain
425 // writes to memory. It's not safe to move the callee (a load) across a store.
426 if (isa<MemSDNode>(Chain.getNode()) &&
427 cast<MemSDNode>(Chain.getNode())->writeMem())
429 if (Chain.getOperand(0).getNode() == Callee.getNode())
431 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
432 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
433 Callee.getValue(1).hasOneUse())
438 void X86DAGToDAGISel::PreprocessISelDAG() {
439 // OptForSize is used in pattern predicates that isel is matching.
440 OptForSize = MF->getFunction()->getAttributes().
441 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
443 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
444 E = CurDAG->allnodes_end(); I != E; ) {
445 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
447 if (OptLevel != CodeGenOpt::None &&
448 // Only does this when target favors doesn't favor register indirect
450 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
451 (N->getOpcode() == X86ISD::TC_RETURN &&
452 // Only does this if load can be folded into TC_RETURN.
453 (Subtarget->is64Bit() ||
454 getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
455 /// Also try moving call address load from outside callseq_start to just
456 /// before the call to allow it to be folded.
474 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
475 SDValue Chain = N->getOperand(0);
476 SDValue Load = N->getOperand(1);
477 if (!isCalleeLoad(Load, Chain, HasCallSeq))
479 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
484 // Lower fpround and fpextend nodes that target the FP stack to be store and
485 // load to the stack. This is a gross hack. We would like to simply mark
486 // these as being illegal, but when we do that, legalize produces these when
487 // it expands calls, then expands these in the same legalize pass. We would
488 // like dag combine to be able to hack on these between the call expansion
489 // and the node legalization. As such this pass basically does "really
490 // late" legalization of these inline with the X86 isel pass.
491 // FIXME: This should only happen when not compiled with -O0.
492 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
495 EVT SrcVT = N->getOperand(0).getValueType();
496 EVT DstVT = N->getValueType(0);
498 // If any of the sources are vectors, no fp stack involved.
499 if (SrcVT.isVector() || DstVT.isVector())
502 // If the source and destination are SSE registers, then this is a legal
503 // conversion that should not be lowered.
504 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
505 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
506 if (SrcIsSSE && DstIsSSE)
509 if (!SrcIsSSE && !DstIsSSE) {
510 // If this is an FPStack extension, it is a noop.
511 if (N->getOpcode() == ISD::FP_EXTEND)
513 // If this is a value-preserving FPStack truncation, it is a noop.
514 if (N->getConstantOperandVal(1))
518 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
519 // FPStack has extload and truncstore. SSE can fold direct loads into other
520 // operations. Based on this, decide what we want to do.
522 if (N->getOpcode() == ISD::FP_ROUND)
523 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
525 MemVT = SrcIsSSE ? SrcVT : DstVT;
527 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
530 // FIXME: optimize the case where the src/dest is a load or store?
531 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
533 MemTmp, MachinePointerInfo(), MemVT,
535 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
536 MachinePointerInfo(),
537 MemVT, false, false, 0);
539 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
540 // extload we created. This will cause general havok on the dag because
541 // anything below the conversion could be folded into other existing nodes.
542 // To avoid invalidating 'I', back it up to the convert node.
544 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
546 // Now that we did that, the node is dead. Increment the iterator to the
547 // next node to process, then delete N.
549 CurDAG->DeleteNode(N);
554 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
555 /// the main function.
556 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
557 MachineFrameInfo *MFI) {
558 const TargetInstrInfo *TII = TM.getInstrInfo();
559 if (Subtarget->isTargetCygMing()) {
561 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
562 BuildMI(BB, DebugLoc(),
563 TII->get(CallOp)).addExternalSymbol("__main");
567 void X86DAGToDAGISel::EmitFunctionEntryCode() {
568 // If this is main, emit special code for main.
569 if (const Function *Fn = MF->getFunction())
570 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
571 EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
574 static bool isDispSafeForFrameIndex(int64_t Val) {
575 // On 64-bit platforms, we can run into an issue where a frame index
576 // includes a displacement that, when added to the explicit displacement,
577 // will overflow the displacement field. Assuming that the frame index
578 // displacement fits into a 31-bit integer (which is only slightly more
579 // aggressive than the current fundamental assumption that it fits into
580 // a 32-bit integer), a 31-bit disp should always be safe.
581 return isInt<31>(Val);
584 bool X86DAGToDAGISel::FoldOffsetIntoAddress(uint64_t Offset,
585 X86ISelAddressMode &AM) {
586 int64_t Val = AM.Disp + Offset;
587 CodeModel::Model M = TM.getCodeModel();
588 if (Subtarget->is64Bit()) {
589 if (!X86::isOffsetSuitableForCodeModel(Val, M,
590 AM.hasSymbolicDisplacement()))
592 // In addition to the checks required for a register base, check that
593 // we do not try to use an unsafe Disp with a frame index.
594 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
595 !isDispSafeForFrameIndex(Val))
603 bool X86DAGToDAGISel::MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
604 SDValue Address = N->getOperand(1);
606 // load gs:0 -> GS segment register.
607 // load fs:0 -> FS segment register.
609 // This optimization is valid because the GNU TLS model defines that
610 // gs:0 (or fs:0 on X86-64) contains its own address.
611 // For more information see http://people.redhat.com/drepper/tls.pdf
612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
613 if (C->getSExtValue() == 0 && AM.Segment.getNode() == 0 &&
614 Subtarget->isTargetLinux())
615 switch (N->getPointerInfo().getAddrSpace()) {
617 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
620 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
627 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
628 /// into an addressing mode. These wrap things that will resolve down into a
629 /// symbol reference. If no match is possible, this returns true, otherwise it
631 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
632 // If the addressing mode already has a symbol as the displacement, we can
633 // never match another symbol.
634 if (AM.hasSymbolicDisplacement())
637 SDValue N0 = N.getOperand(0);
638 CodeModel::Model M = TM.getCodeModel();
640 // Handle X86-64 rip-relative addresses. We check this before checking direct
641 // folding because RIP is preferable to non-RIP accesses.
642 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
643 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
644 // they cannot be folded into immediate fields.
645 // FIXME: This can be improved for kernel and other models?
646 (M == CodeModel::Small || M == CodeModel::Kernel)) {
647 // Base and index reg must be 0 in order to use %rip as base.
648 if (AM.hasBaseOrIndexReg())
650 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
651 X86ISelAddressMode Backup = AM;
652 AM.GV = G->getGlobal();
653 AM.SymbolFlags = G->getTargetFlags();
654 if (FoldOffsetIntoAddress(G->getOffset(), AM)) {
658 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
659 X86ISelAddressMode Backup = AM;
660 AM.CP = CP->getConstVal();
661 AM.Align = CP->getAlignment();
662 AM.SymbolFlags = CP->getTargetFlags();
663 if (FoldOffsetIntoAddress(CP->getOffset(), AM)) {
667 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
668 AM.ES = S->getSymbol();
669 AM.SymbolFlags = S->getTargetFlags();
670 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
671 AM.JT = J->getIndex();
672 AM.SymbolFlags = J->getTargetFlags();
673 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
674 X86ISelAddressMode Backup = AM;
675 AM.BlockAddr = BA->getBlockAddress();
676 AM.SymbolFlags = BA->getTargetFlags();
677 if (FoldOffsetIntoAddress(BA->getOffset(), AM)) {
682 llvm_unreachable("Unhandled symbol reference node.");
684 if (N.getOpcode() == X86ISD::WrapperRIP)
685 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
689 // Handle the case when globals fit in our immediate field: This is true for
690 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
691 // mode, this only applies to a non-RIP-relative computation.
692 if (!Subtarget->is64Bit() ||
693 M == CodeModel::Small || M == CodeModel::Kernel) {
694 assert(N.getOpcode() != X86ISD::WrapperRIP &&
695 "RIP-relative addressing already handled");
696 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
697 AM.GV = G->getGlobal();
698 AM.Disp += G->getOffset();
699 AM.SymbolFlags = G->getTargetFlags();
700 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
701 AM.CP = CP->getConstVal();
702 AM.Align = CP->getAlignment();
703 AM.Disp += CP->getOffset();
704 AM.SymbolFlags = CP->getTargetFlags();
705 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
706 AM.ES = S->getSymbol();
707 AM.SymbolFlags = S->getTargetFlags();
708 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
709 AM.JT = J->getIndex();
710 AM.SymbolFlags = J->getTargetFlags();
711 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
712 AM.BlockAddr = BA->getBlockAddress();
713 AM.Disp += BA->getOffset();
714 AM.SymbolFlags = BA->getTargetFlags();
716 llvm_unreachable("Unhandled symbol reference node.");
723 /// MatchAddress - Add the specified node to the specified addressing mode,
724 /// returning true if it cannot be done. This just pattern matches for the
726 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
727 if (MatchAddressRecursively(N, AM, 0))
730 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
731 // a smaller encoding and avoids a scaled-index.
733 AM.BaseType == X86ISelAddressMode::RegBase &&
734 AM.Base_Reg.getNode() == 0) {
735 AM.Base_Reg = AM.IndexReg;
739 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
740 // because it has a smaller encoding.
741 // TODO: Which other code models can use this?
742 if (TM.getCodeModel() == CodeModel::Small &&
743 Subtarget->is64Bit() &&
745 AM.BaseType == X86ISelAddressMode::RegBase &&
746 AM.Base_Reg.getNode() == 0 &&
747 AM.IndexReg.getNode() == 0 &&
748 AM.SymbolFlags == X86II::MO_NO_FLAG &&
749 AM.hasSymbolicDisplacement())
750 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
755 // Insert a node into the DAG at least before the Pos node's position. This
756 // will reposition the node as needed, and will assign it a node ID that is <=
757 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
758 // IDs! The selection DAG must no longer depend on their uniqueness when this
760 static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
761 if (N.getNode()->getNodeId() == -1 ||
762 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
763 DAG.RepositionNode(Pos.getNode(), N.getNode());
764 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
768 // Transform "(X >> (8-C1)) & C2" to "(X >> 8) & 0xff)" if safe. This
769 // allows us to convert the shift and and into an h-register extract and
770 // a scaled index. Returns false if the simplification is performed.
771 static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
773 SDValue Shift, SDValue X,
774 X86ISelAddressMode &AM) {
775 if (Shift.getOpcode() != ISD::SRL ||
776 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
780 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
781 if (ScaleLog <= 0 || ScaleLog >= 4 ||
782 Mask != (0xffu << ScaleLog))
785 EVT VT = N.getValueType();
787 SDValue Eight = DAG.getConstant(8, MVT::i8);
788 SDValue NewMask = DAG.getConstant(0xff, VT);
789 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
790 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
791 SDValue ShlCount = DAG.getConstant(ScaleLog, MVT::i8);
792 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
794 // Insert the new nodes into the topological ordering. We must do this in
795 // a valid topological ordering as nothing is going to go back and re-sort
796 // these nodes. We continually insert before 'N' in sequence as this is
797 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
798 // hierarchy left to express.
799 InsertDAGNode(DAG, N, Eight);
800 InsertDAGNode(DAG, N, Srl);
801 InsertDAGNode(DAG, N, NewMask);
802 InsertDAGNode(DAG, N, And);
803 InsertDAGNode(DAG, N, ShlCount);
804 InsertDAGNode(DAG, N, Shl);
805 DAG.ReplaceAllUsesWith(N, Shl);
807 AM.Scale = (1 << ScaleLog);
811 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
812 // allows us to fold the shift into this addressing mode. Returns false if the
813 // transform succeeded.
814 static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
816 SDValue Shift, SDValue X,
817 X86ISelAddressMode &AM) {
818 if (Shift.getOpcode() != ISD::SHL ||
819 !isa<ConstantSDNode>(Shift.getOperand(1)))
822 // Not likely to be profitable if either the AND or SHIFT node has more
823 // than one use (unless all uses are for address computation). Besides,
824 // isel mechanism requires their node ids to be reused.
825 if (!N.hasOneUse() || !Shift.hasOneUse())
828 // Verify that the shift amount is something we can fold.
829 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
830 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
833 EVT VT = N.getValueType();
835 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, VT);
836 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
837 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
839 // Insert the new nodes into the topological ordering. We must do this in
840 // a valid topological ordering as nothing is going to go back and re-sort
841 // these nodes. We continually insert before 'N' in sequence as this is
842 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
843 // hierarchy left to express.
844 InsertDAGNode(DAG, N, NewMask);
845 InsertDAGNode(DAG, N, NewAnd);
846 InsertDAGNode(DAG, N, NewShift);
847 DAG.ReplaceAllUsesWith(N, NewShift);
849 AM.Scale = 1 << ShiftAmt;
850 AM.IndexReg = NewAnd;
854 // Implement some heroics to detect shifts of masked values where the mask can
855 // be replaced by extending the shift and undoing that in the addressing mode
856 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
857 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
858 // the addressing mode. This results in code such as:
860 // int f(short *y, int *lookup_table) {
862 // return *y + lookup_table[*y >> 11];
866 // movzwl (%rdi), %eax
869 // addl (%rsi,%rcx,4), %eax
872 // movzwl (%rdi), %eax
876 // addl (%rsi,%rcx), %eax
878 // Note that this function assumes the mask is provided as a mask *after* the
879 // value is shifted. The input chain may or may not match that, but computing
880 // such a mask is trivial.
881 static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
883 SDValue Shift, SDValue X,
884 X86ISelAddressMode &AM) {
885 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
886 !isa<ConstantSDNode>(Shift.getOperand(1)))
889 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
890 unsigned MaskLZ = countLeadingZeros(Mask);
891 unsigned MaskTZ = countTrailingZeros(Mask);
893 // The amount of shift we're trying to fit into the addressing mode is taken
894 // from the trailing zeros of the mask.
895 unsigned AMShiftAmt = MaskTZ;
897 // There is nothing we can do here unless the mask is removing some bits.
898 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
899 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
901 // We also need to ensure that mask is a continuous run of bits.
902 if (CountTrailingOnes_64(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
904 // Scale the leading zero count down based on the actual size of the value.
905 // Also scale it down based on the size of the shift.
906 MaskLZ -= (64 - X.getValueSizeInBits()) + ShiftAmt;
908 // The final check is to ensure that any masked out high bits of X are
909 // already known to be zero. Otherwise, the mask has a semantic impact
910 // other than masking out a couple of low bits. Unfortunately, because of
911 // the mask, zero extensions will be removed from operands in some cases.
912 // This code works extra hard to look through extensions because we can
913 // replace them with zero extensions cheaply if necessary.
914 bool ReplacingAnyExtend = false;
915 if (X.getOpcode() == ISD::ANY_EXTEND) {
916 unsigned ExtendBits =
917 X.getValueSizeInBits() - X.getOperand(0).getValueSizeInBits();
918 // Assume that we'll replace the any-extend with a zero-extend, and
919 // narrow the search to the extended value.
921 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
922 ReplacingAnyExtend = true;
924 APInt MaskedHighBits = APInt::getHighBitsSet(X.getValueSizeInBits(),
926 APInt KnownZero, KnownOne;
927 DAG.ComputeMaskedBits(X, KnownZero, KnownOne);
928 if (MaskedHighBits != KnownZero) return true;
930 // We've identified a pattern that can be transformed into a single shift
931 // and an addressing mode. Make it so.
932 EVT VT = N.getValueType();
933 if (ReplacingAnyExtend) {
934 assert(X.getValueType() != VT);
935 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
936 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
937 InsertDAGNode(DAG, N, NewX);
941 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, MVT::i8);
942 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
943 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, MVT::i8);
944 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
946 // Insert the new nodes into the topological ordering. We must do this in
947 // a valid topological ordering as nothing is going to go back and re-sort
948 // these nodes. We continually insert before 'N' in sequence as this is
949 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
950 // hierarchy left to express.
951 InsertDAGNode(DAG, N, NewSRLAmt);
952 InsertDAGNode(DAG, N, NewSRL);
953 InsertDAGNode(DAG, N, NewSHLAmt);
954 InsertDAGNode(DAG, N, NewSHL);
955 DAG.ReplaceAllUsesWith(N, NewSHL);
957 AM.Scale = 1 << AMShiftAmt;
958 AM.IndexReg = NewSRL;
962 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
966 dbgs() << "MatchAddress: ";
971 return MatchAddressBase(N, AM);
973 // If this is already a %rip relative address, we can only merge immediates
974 // into it. Instead of handling this in every case, we handle it here.
975 // RIP relative addressing: %rip + 32-bit displacement!
976 if (AM.isRIPRelative()) {
977 // FIXME: JumpTable and ExternalSymbol address currently don't like
978 // displacements. It isn't very important, but this should be fixed for
980 if (!AM.ES && AM.JT != -1) return true;
982 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
983 if (!FoldOffsetIntoAddress(Cst->getSExtValue(), AM))
988 switch (N.getOpcode()) {
990 case ISD::Constant: {
991 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
992 if (!FoldOffsetIntoAddress(Val, AM))
997 case X86ISD::Wrapper:
998 case X86ISD::WrapperRIP:
999 if (!MatchWrapper(N, AM))
1004 if (!MatchLoadInAddress(cast<LoadSDNode>(N), AM))
1008 case ISD::FrameIndex:
1009 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1010 AM.Base_Reg.getNode() == 0 &&
1011 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1012 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1013 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1019 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
1023 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1024 unsigned Val = CN->getZExtValue();
1025 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1026 // that the base operand remains free for further matching. If
1027 // the base doesn't end up getting used, a post-processing step
1028 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1029 if (Val == 1 || Val == 2 || Val == 3) {
1030 AM.Scale = 1 << Val;
1031 SDValue ShVal = N.getNode()->getOperand(0);
1033 // Okay, we know that we have a scale by now. However, if the scaled
1034 // value is an add of something and a constant, we can fold the
1035 // constant into the disp field here.
1036 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1037 AM.IndexReg = ShVal.getNode()->getOperand(0);
1038 ConstantSDNode *AddVal =
1039 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1040 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1041 if (!FoldOffsetIntoAddress(Disp, AM))
1045 AM.IndexReg = ShVal;
1052 // Scale must not be used already.
1053 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1055 SDValue And = N.getOperand(0);
1056 if (And.getOpcode() != ISD::AND) break;
1057 SDValue X = And.getOperand(0);
1059 // We only handle up to 64-bit values here as those are what matter for
1060 // addressing mode optimizations.
1061 if (X.getValueSizeInBits() > 64) break;
1063 // The mask used for the transform is expected to be post-shift, but we
1064 // found the shift first so just apply the shift to the mask before passing
1066 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1067 !isa<ConstantSDNode>(And.getOperand(1)))
1069 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1071 // Try to fold the mask and shift into the scale, and return false if we
1073 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1078 case ISD::SMUL_LOHI:
1079 case ISD::UMUL_LOHI:
1080 // A mul_lohi where we need the low part can be folded as a plain multiply.
1081 if (N.getResNo() != 0) break;
1084 case X86ISD::MUL_IMM:
1085 // X*[3,5,9] -> X+X*[2,4,8]
1086 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1087 AM.Base_Reg.getNode() == 0 &&
1088 AM.IndexReg.getNode() == 0) {
1090 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1091 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1092 CN->getZExtValue() == 9) {
1093 AM.Scale = unsigned(CN->getZExtValue())-1;
1095 SDValue MulVal = N.getNode()->getOperand(0);
1098 // Okay, we know that we have a scale by now. However, if the scaled
1099 // value is an add of something and a constant, we can fold the
1100 // constant into the disp field here.
1101 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1102 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1103 Reg = MulVal.getNode()->getOperand(0);
1104 ConstantSDNode *AddVal =
1105 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1106 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1107 if (FoldOffsetIntoAddress(Disp, AM))
1108 Reg = N.getNode()->getOperand(0);
1110 Reg = N.getNode()->getOperand(0);
1113 AM.IndexReg = AM.Base_Reg = Reg;
1120 // Given A-B, if A can be completely folded into the address and
1121 // the index field with the index field unused, use -B as the index.
1122 // This is a win if a has multiple parts that can be folded into
1123 // the address. Also, this saves a mov if the base register has
1124 // other uses, since it avoids a two-address sub instruction, however
1125 // it costs an additional mov if the index register has other uses.
1127 // Add an artificial use to this node so that we can keep track of
1128 // it if it gets CSE'd with a different node.
1129 HandleSDNode Handle(N);
1131 // Test if the LHS of the sub can be folded.
1132 X86ISelAddressMode Backup = AM;
1133 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1137 // Test if the index field is free for use.
1138 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1144 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1145 // If the RHS involves a register with multiple uses, this
1146 // transformation incurs an extra mov, due to the neg instruction
1147 // clobbering its operand.
1148 if (!RHS.getNode()->hasOneUse() ||
1149 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1150 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1151 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1152 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1153 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1155 // If the base is a register with multiple uses, this
1156 // transformation may save a mov.
1157 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1158 AM.Base_Reg.getNode() &&
1159 !AM.Base_Reg.getNode()->hasOneUse()) ||
1160 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1162 // If the folded LHS was interesting, this transformation saves
1163 // address arithmetic.
1164 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1165 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1166 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1168 // If it doesn't look like it may be an overall win, don't do it.
1174 // Ok, the transformation is legal and appears profitable. Go for it.
1175 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
1176 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1180 // Insert the new nodes into the topological ordering.
1181 InsertDAGNode(*CurDAG, N, Zero);
1182 InsertDAGNode(*CurDAG, N, Neg);
1187 // Add an artificial use to this node so that we can keep track of
1188 // it if it gets CSE'd with a different node.
1189 HandleSDNode Handle(N);
1191 X86ISelAddressMode Backup = AM;
1192 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1193 !MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1197 // Try again after commuting the operands.
1198 if (!MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)&&
1199 !MatchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1203 // If we couldn't fold both operands into the address at the same time,
1204 // see if we can just put each operand into a register and fold at least
1206 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1207 !AM.Base_Reg.getNode() &&
1208 !AM.IndexReg.getNode()) {
1209 N = Handle.getValue();
1210 AM.Base_Reg = N.getOperand(0);
1211 AM.IndexReg = N.getOperand(1);
1215 N = Handle.getValue();
1220 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1221 if (CurDAG->isBaseWithConstantOffset(N)) {
1222 X86ISelAddressMode Backup = AM;
1223 ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
1225 // Start with the LHS as an addr mode.
1226 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1227 !FoldOffsetIntoAddress(CN->getSExtValue(), AM))
1234 // Perform some heroic transforms on an and of a constant-count shift
1235 // with a constant to enable use of the scaled offset field.
1237 // Scale must not be used already.
1238 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1240 SDValue Shift = N.getOperand(0);
1241 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1242 SDValue X = Shift.getOperand(0);
1244 // We only handle up to 64-bit values here as those are what matter for
1245 // addressing mode optimizations.
1246 if (X.getValueSizeInBits() > 64) break;
1248 if (!isa<ConstantSDNode>(N.getOperand(1)))
1250 uint64_t Mask = N.getConstantOperandVal(1);
1252 // Try to fold the mask and shift into an extract and scale.
1253 if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1256 // Try to fold the mask and shift directly into the scale.
1257 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1260 // Try to swap the mask and shift to place shifts which can be done as
1261 // a scale on the outside of the mask.
1262 if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1268 return MatchAddressBase(N, AM);
1271 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1272 /// specified addressing mode without any further recursion.
1273 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1274 // Is the base register already occupied?
1275 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1276 // If so, check to see if the scale index register is set.
1277 if (AM.IndexReg.getNode() == 0) {
1283 // Otherwise, we cannot select it.
1287 // Default, generate it as a register.
1288 AM.BaseType = X86ISelAddressMode::RegBase;
1293 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1294 /// It returns the operands which make up the maximal addressing mode it can
1295 /// match by reference.
1297 /// Parent is the parent node of the addr operand that is being matched. It
1298 /// is always a load, store, atomic node, or null. It is only null when
1299 /// checking memory operands for inline asm nodes.
1300 bool X86DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1301 SDValue &Scale, SDValue &Index,
1302 SDValue &Disp, SDValue &Segment) {
1303 X86ISelAddressMode AM;
1306 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1307 // that are not a MemSDNode, and thus don't have proper addrspace info.
1308 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1309 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1310 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1311 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1312 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1313 unsigned AddrSpace =
1314 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1315 // AddrSpace 256 -> GS, 257 -> FS.
1316 if (AddrSpace == 256)
1317 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1318 if (AddrSpace == 257)
1319 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1322 if (MatchAddress(N, AM))
1325 EVT VT = N.getValueType();
1326 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1327 if (!AM.Base_Reg.getNode())
1328 AM.Base_Reg = CurDAG->getRegister(0, VT);
1331 if (!AM.IndexReg.getNode())
1332 AM.IndexReg = CurDAG->getRegister(0, VT);
1334 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1338 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1339 /// match a load whose top elements are either undef or zeros. The load flavor
1340 /// is derived from the type of N, which is either v4f32 or v2f64.
1343 /// PatternChainNode: this is the matched node that has a chain input and
1345 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1346 SDValue N, SDValue &Base,
1347 SDValue &Scale, SDValue &Index,
1348 SDValue &Disp, SDValue &Segment,
1349 SDValue &PatternNodeWithChain) {
1350 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1351 PatternNodeWithChain = N.getOperand(0);
1352 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1353 PatternNodeWithChain.hasOneUse() &&
1354 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1355 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1356 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1357 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1363 // Also handle the case where we explicitly require zeros in the top
1364 // elements. This is a vector shuffle from the zero vector.
1365 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1366 // Check to see if the top elements are all zeros (or bitcast of zeros).
1367 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1368 N.getOperand(0).getNode()->hasOneUse() &&
1369 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1370 N.getOperand(0).getOperand(0).hasOneUse() &&
1371 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1372 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1373 // Okay, this is a zero extending load. Fold it.
1374 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1375 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1377 PatternNodeWithChain = SDValue(LD, 0);
1384 bool X86DAGToDAGISel::SelectMOV64Imm32(SDValue N, SDValue &Imm) {
1385 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1386 uint64_t ImmVal = CN->getZExtValue();
1387 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1390 Imm = CurDAG->getTargetConstant(ImmVal, MVT::i64);
1394 // In static codegen with small code model, we can get the address of a label
1395 // into a register with 'movl'. TableGen has already made sure we're looking
1396 // at a label of some kind.
1397 assert(N->getOpcode() == X86ISD::Wrapper && "Unexpected node type for MOV32ri64");
1398 N = N.getOperand(0);
1400 if (N->getOpcode() != ISD::TargetConstantPool &&
1401 N->getOpcode() != ISD::TargetJumpTable &&
1402 N->getOpcode() != ISD::TargetGlobalAddress &&
1403 N->getOpcode() != ISD::TargetExternalSymbol &&
1404 N->getOpcode() != ISD::TargetBlockAddress)
1408 return TM.getCodeModel() == CodeModel::Small;
1411 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1412 /// mode it matches can be cost effectively emitted as an LEA instruction.
1413 bool X86DAGToDAGISel::SelectLEAAddr(SDValue N,
1414 SDValue &Base, SDValue &Scale,
1415 SDValue &Index, SDValue &Disp,
1417 X86ISelAddressMode AM;
1419 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1421 SDValue Copy = AM.Segment;
1422 SDValue T = CurDAG->getRegister(0, MVT::i32);
1424 if (MatchAddress(N, AM))
1426 assert (T == AM.Segment);
1429 EVT VT = N.getValueType();
1430 unsigned Complexity = 0;
1431 if (AM.BaseType == X86ISelAddressMode::RegBase)
1432 if (AM.Base_Reg.getNode())
1435 AM.Base_Reg = CurDAG->getRegister(0, VT);
1436 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1439 if (AM.IndexReg.getNode())
1442 AM.IndexReg = CurDAG->getRegister(0, VT);
1444 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1449 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1450 // to a LEA. This is determined with some expermentation but is by no means
1451 // optimal (especially for code size consideration). LEA is nice because of
1452 // its three-address nature. Tweak the cost function again when we can run
1453 // convertToThreeAddress() at register allocation time.
1454 if (AM.hasSymbolicDisplacement()) {
1455 // For X86-64, we should always use lea to materialize RIP relative
1457 if (Subtarget->is64Bit())
1463 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1466 // If it isn't worth using an LEA, reject it.
1467 if (Complexity <= 2)
1470 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1474 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1475 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue N, SDValue &Base,
1476 SDValue &Scale, SDValue &Index,
1477 SDValue &Disp, SDValue &Segment) {
1478 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1479 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1481 X86ISelAddressMode AM;
1482 AM.GV = GA->getGlobal();
1483 AM.Disp += GA->getOffset();
1484 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1485 AM.SymbolFlags = GA->getTargetFlags();
1487 if (N.getValueType() == MVT::i32) {
1489 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1491 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1494 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1499 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1500 SDValue &Base, SDValue &Scale,
1501 SDValue &Index, SDValue &Disp,
1503 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1504 !IsProfitableToFold(N, P, P) ||
1505 !IsLegalToFold(N, P, P, OptLevel))
1508 return SelectAddr(N.getNode(),
1509 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1512 /// getGlobalBaseReg - Return an SDNode that returns the value of
1513 /// the global base register. Output instructions required to
1514 /// initialize the global base register, if necessary.
1516 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1517 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1518 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1521 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1522 SDValue Chain = Node->getOperand(0);
1523 SDValue In1 = Node->getOperand(1);
1524 SDValue In2L = Node->getOperand(2);
1525 SDValue In2H = Node->getOperand(3);
1527 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1528 if (!SelectAddr(Node, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1530 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1531 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1532 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1533 SDNode *ResNode = CurDAG->getMachineNode(Opc, SDLoc(Node),
1534 MVT::i32, MVT::i32, MVT::Other, Ops);
1535 cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1539 /// Atomic opcode table
1567 static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] = {
1578 X86::LOCK_ADD64mi32,
1591 X86::LOCK_SUB64mi32,
1643 X86::LOCK_AND64mi32,
1656 X86::LOCK_XOR64mi32,
1661 // Return the target constant operand for atomic-load-op and do simple
1662 // translations, such as from atomic-load-add to lock-sub. The return value is
1663 // one of the following 3 cases:
1664 // + target-constant, the operand could be supported as a target constant.
1665 // + empty, the operand is not needed any more with the new op selected.
1666 // + non-empty, otherwise.
1667 static SDValue getAtomicLoadArithTargetConstant(SelectionDAG *CurDAG,
1669 enum AtomicOpc &Op, EVT NVT,
1671 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val)) {
1672 int64_t CNVal = CN->getSExtValue();
1673 // Quit if not 32-bit imm.
1674 if ((int32_t)CNVal != CNVal)
1676 // For atomic-load-add, we could do some optimizations.
1678 // Translate to INC/DEC if ADD by 1 or -1.
1679 if ((CNVal == 1) || (CNVal == -1)) {
1680 Op = (CNVal == 1) ? INC : DEC;
1681 // No more constant operand after being translated into INC/DEC.
1684 // Translate to SUB if ADD by negative value.
1690 return CurDAG->getTargetConstant(CNVal, NVT);
1693 // If the value operand is single-used, try to optimize it.
1694 if (Op == ADD && Val.hasOneUse()) {
1695 // Translate (atomic-load-add ptr (sub 0 x)) back to (lock-sub x).
1696 if (Val.getOpcode() == ISD::SUB && X86::isZeroNode(Val.getOperand(0))) {
1698 return Val.getOperand(1);
1700 // A special case for i16, which needs truncating as, in most cases, it's
1701 // promoted to i32. We will translate
1702 // (atomic-load-add (truncate (sub 0 x))) to (lock-sub (EXTRACT_SUBREG x))
1703 if (Val.getOpcode() == ISD::TRUNCATE && NVT == MVT::i16 &&
1704 Val.getOperand(0).getOpcode() == ISD::SUB &&
1705 X86::isZeroNode(Val.getOperand(0).getOperand(0))) {
1707 Val = Val.getOperand(0);
1708 return CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, NVT,
1716 SDNode *X86DAGToDAGISel::SelectAtomicLoadArith(SDNode *Node, EVT NVT) {
1717 if (Node->hasAnyUseOfValue(0))
1722 // Optimize common patterns for __sync_or_and_fetch and similar arith
1723 // operations where the result is not used. This allows us to use the "lock"
1724 // version of the arithmetic instruction.
1725 SDValue Chain = Node->getOperand(0);
1726 SDValue Ptr = Node->getOperand(1);
1727 SDValue Val = Node->getOperand(2);
1728 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1729 if (!SelectAddr(Node, Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1732 // Which index into the table.
1734 switch (Node->getOpcode()) {
1737 case ISD::ATOMIC_LOAD_OR:
1740 case ISD::ATOMIC_LOAD_AND:
1743 case ISD::ATOMIC_LOAD_XOR:
1746 case ISD::ATOMIC_LOAD_ADD:
1751 Val = getAtomicLoadArithTargetConstant(CurDAG, dl, Op, NVT, Val);
1752 bool isUnOp = !Val.getNode();
1753 bool isCN = Val.getNode() && (Val.getOpcode() == ISD::TargetConstant);
1756 switch (NVT.getSimpleVT().SimpleTy) {
1760 Opc = AtomicOpcTbl[Op][ConstantI8];
1762 Opc = AtomicOpcTbl[Op][I8];
1766 if (immSext8(Val.getNode()))
1767 Opc = AtomicOpcTbl[Op][SextConstantI16];
1769 Opc = AtomicOpcTbl[Op][ConstantI16];
1771 Opc = AtomicOpcTbl[Op][I16];
1775 if (immSext8(Val.getNode()))
1776 Opc = AtomicOpcTbl[Op][SextConstantI32];
1778 Opc = AtomicOpcTbl[Op][ConstantI32];
1780 Opc = AtomicOpcTbl[Op][I32];
1783 Opc = AtomicOpcTbl[Op][I64];
1785 if (immSext8(Val.getNode()))
1786 Opc = AtomicOpcTbl[Op][SextConstantI64];
1787 else if (i64immSExt32(Val.getNode()))
1788 Opc = AtomicOpcTbl[Op][ConstantI64];
1793 assert(Opc != 0 && "Invalid arith lock transform!");
1796 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1798 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1799 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1801 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1802 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1804 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1805 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1807 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1808 SDValue RetVals[] = { Undef, Ret };
1809 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1812 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1813 /// any uses which require the SF or OF bits to be accurate.
1814 static bool HasNoSignedComparisonUses(SDNode *N) {
1815 // Examine each user of the node.
1816 for (SDNode::use_iterator UI = N->use_begin(),
1817 UE = N->use_end(); UI != UE; ++UI) {
1818 // Only examine CopyToReg uses.
1819 if (UI->getOpcode() != ISD::CopyToReg)
1821 // Only examine CopyToReg uses that copy to EFLAGS.
1822 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1825 // Examine each user of the CopyToReg use.
1826 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1827 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1828 // Only examine the Flag result.
1829 if (FlagUI.getUse().getResNo() != 1) continue;
1830 // Anything unusual: assume conservatively.
1831 if (!FlagUI->isMachineOpcode()) return false;
1832 // Examine the opcode of the user.
1833 switch (FlagUI->getMachineOpcode()) {
1834 // These comparisons don't treat the most significant bit specially.
1835 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1836 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1837 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1838 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1839 case X86::JA_4: case X86::JAE_4: case X86::JB_4: case X86::JBE_4:
1840 case X86::JE_4: case X86::JNE_4: case X86::JP_4: case X86::JNP_4:
1841 case X86::CMOVA16rr: case X86::CMOVA16rm:
1842 case X86::CMOVA32rr: case X86::CMOVA32rm:
1843 case X86::CMOVA64rr: case X86::CMOVA64rm:
1844 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1845 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1846 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1847 case X86::CMOVB16rr: case X86::CMOVB16rm:
1848 case X86::CMOVB32rr: case X86::CMOVB32rm:
1849 case X86::CMOVB64rr: case X86::CMOVB64rm:
1850 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1851 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1852 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1853 case X86::CMOVE16rr: case X86::CMOVE16rm:
1854 case X86::CMOVE32rr: case X86::CMOVE32rm:
1855 case X86::CMOVE64rr: case X86::CMOVE64rm:
1856 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1857 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1858 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1859 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1860 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1861 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1862 case X86::CMOVP16rr: case X86::CMOVP16rm:
1863 case X86::CMOVP32rr: case X86::CMOVP32rm:
1864 case X86::CMOVP64rr: case X86::CMOVP64rm:
1866 // Anything else: assume conservatively.
1867 default: return false;
1874 /// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNode
1875 /// is suitable for doing the {load; increment or decrement; store} to modify
1877 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1878 SDValue StoredVal, SelectionDAG *CurDAG,
1879 LoadSDNode* &LoadNode, SDValue &InputChain) {
1881 // is the value stored the result of a DEC or INC?
1882 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1884 // is the stored value result 0 of the load?
1885 if (StoredVal.getResNo() != 0) return false;
1887 // are there other uses of the loaded value than the inc or dec?
1888 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1890 // is the store non-extending and non-indexed?
1891 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1894 SDValue Load = StoredVal->getOperand(0);
1895 // Is the stored value a non-extending and non-indexed load?
1896 if (!ISD::isNormalLoad(Load.getNode())) return false;
1898 // Return LoadNode by reference.
1899 LoadNode = cast<LoadSDNode>(Load);
1900 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1901 EVT LdVT = LoadNode->getMemoryVT();
1902 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1906 // Is store the only read of the loaded value?
1907 if (!Load.hasOneUse())
1910 // Is the address of the store the same as the load?
1911 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1912 LoadNode->getOffset() != StoreNode->getOffset())
1915 // Check if the chain is produced by the load or is a TokenFactor with
1916 // the load output chain as an operand. Return InputChain by reference.
1917 SDValue Chain = StoreNode->getChain();
1919 bool ChainCheck = false;
1920 if (Chain == Load.getValue(1)) {
1922 InputChain = LoadNode->getChain();
1923 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1924 SmallVector<SDValue, 4> ChainOps;
1925 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1926 SDValue Op = Chain.getOperand(i);
1927 if (Op == Load.getValue(1)) {
1932 // Make sure using Op as part of the chain would not cause a cycle here.
1933 // In theory, we could check whether the chain node is a predecessor of
1934 // the load. But that can be very expensive. Instead visit the uses and
1935 // make sure they all have smaller node id than the load.
1936 int LoadId = LoadNode->getNodeId();
1937 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1938 UE = UI->use_end(); UI != UE; ++UI) {
1939 if (UI.getUse().getResNo() != 0)
1941 if (UI->getNodeId() > LoadId)
1945 ChainOps.push_back(Op);
1949 // Make a new TokenFactor with all the other input chains except
1951 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1952 MVT::Other, &ChainOps[0], ChainOps.size());
1960 /// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
1961 /// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
1962 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1963 if (Opc == X86ISD::DEC) {
1964 if (LdVT == MVT::i64) return X86::DEC64m;
1965 if (LdVT == MVT::i32) return X86::DEC32m;
1966 if (LdVT == MVT::i16) return X86::DEC16m;
1967 if (LdVT == MVT::i8) return X86::DEC8m;
1969 assert(Opc == X86ISD::INC && "unrecognized opcode");
1970 if (LdVT == MVT::i64) return X86::INC64m;
1971 if (LdVT == MVT::i32) return X86::INC32m;
1972 if (LdVT == MVT::i16) return X86::INC16m;
1973 if (LdVT == MVT::i8) return X86::INC8m;
1975 llvm_unreachable("unrecognized size for LdVT");
1978 /// SelectGather - Customized ISel for GATHER operations.
1980 SDNode *X86DAGToDAGISel::SelectGather(SDNode *Node, unsigned Opc) {
1981 // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
1982 SDValue Chain = Node->getOperand(0);
1983 SDValue VSrc = Node->getOperand(2);
1984 SDValue Base = Node->getOperand(3);
1985 SDValue VIdx = Node->getOperand(4);
1986 SDValue VMask = Node->getOperand(5);
1987 ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
1991 SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
1994 // Memory Operands: Base, Scale, Index, Disp, Segment
1995 SDValue Disp = CurDAG->getTargetConstant(0, MVT::i32);
1996 SDValue Segment = CurDAG->getRegister(0, MVT::i32);
1997 const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue()), VIdx,
1998 Disp, Segment, VMask, Chain};
1999 SDNode *ResNode = CurDAG->getMachineNode(Opc, SDLoc(Node), VTs, Ops);
2000 // Node has 2 outputs: VDst and MVT::Other.
2001 // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
2002 // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
2004 ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
2005 ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
2009 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
2010 EVT NVT = Node->getValueType(0);
2012 unsigned Opcode = Node->getOpcode();
2015 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2017 if (Node->isMachineOpcode()) {
2018 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
2019 return NULL; // Already selected.
2024 case ISD::INTRINSIC_W_CHAIN: {
2025 unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2028 case Intrinsic::x86_avx2_gather_d_pd:
2029 case Intrinsic::x86_avx2_gather_d_pd_256:
2030 case Intrinsic::x86_avx2_gather_q_pd:
2031 case Intrinsic::x86_avx2_gather_q_pd_256:
2032 case Intrinsic::x86_avx2_gather_d_ps:
2033 case Intrinsic::x86_avx2_gather_d_ps_256:
2034 case Intrinsic::x86_avx2_gather_q_ps:
2035 case Intrinsic::x86_avx2_gather_q_ps_256:
2036 case Intrinsic::x86_avx2_gather_d_q:
2037 case Intrinsic::x86_avx2_gather_d_q_256:
2038 case Intrinsic::x86_avx2_gather_q_q:
2039 case Intrinsic::x86_avx2_gather_q_q_256:
2040 case Intrinsic::x86_avx2_gather_d_d:
2041 case Intrinsic::x86_avx2_gather_d_d_256:
2042 case Intrinsic::x86_avx2_gather_q_d:
2043 case Intrinsic::x86_avx2_gather_q_d_256: {
2046 default: llvm_unreachable("Impossible intrinsic");
2047 case Intrinsic::x86_avx2_gather_d_pd: Opc = X86::VGATHERDPDrm; break;
2048 case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
2049 case Intrinsic::x86_avx2_gather_q_pd: Opc = X86::VGATHERQPDrm; break;
2050 case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
2051 case Intrinsic::x86_avx2_gather_d_ps: Opc = X86::VGATHERDPSrm; break;
2052 case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
2053 case Intrinsic::x86_avx2_gather_q_ps: Opc = X86::VGATHERQPSrm; break;
2054 case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
2055 case Intrinsic::x86_avx2_gather_d_q: Opc = X86::VPGATHERDQrm; break;
2056 case Intrinsic::x86_avx2_gather_d_q_256: Opc = X86::VPGATHERDQYrm; break;
2057 case Intrinsic::x86_avx2_gather_q_q: Opc = X86::VPGATHERQQrm; break;
2058 case Intrinsic::x86_avx2_gather_q_q_256: Opc = X86::VPGATHERQQYrm; break;
2059 case Intrinsic::x86_avx2_gather_d_d: Opc = X86::VPGATHERDDrm; break;
2060 case Intrinsic::x86_avx2_gather_d_d_256: Opc = X86::VPGATHERDDYrm; break;
2061 case Intrinsic::x86_avx2_gather_q_d: Opc = X86::VPGATHERQDrm; break;
2062 case Intrinsic::x86_avx2_gather_q_d_256: Opc = X86::VPGATHERQDYrm; break;
2064 SDNode *RetVal = SelectGather(Node, Opc);
2066 // We already called ReplaceUses inside SelectGather.
2073 case X86ISD::GlobalBaseReg:
2074 return getGlobalBaseReg();
2077 case X86ISD::ATOMOR64_DAG:
2078 case X86ISD::ATOMXOR64_DAG:
2079 case X86ISD::ATOMADD64_DAG:
2080 case X86ISD::ATOMSUB64_DAG:
2081 case X86ISD::ATOMNAND64_DAG:
2082 case X86ISD::ATOMAND64_DAG:
2083 case X86ISD::ATOMMAX64_DAG:
2084 case X86ISD::ATOMMIN64_DAG:
2085 case X86ISD::ATOMUMAX64_DAG:
2086 case X86ISD::ATOMUMIN64_DAG:
2087 case X86ISD::ATOMSWAP64_DAG: {
2090 default: llvm_unreachable("Impossible opcode");
2091 case X86ISD::ATOMOR64_DAG: Opc = X86::ATOMOR6432; break;
2092 case X86ISD::ATOMXOR64_DAG: Opc = X86::ATOMXOR6432; break;
2093 case X86ISD::ATOMADD64_DAG: Opc = X86::ATOMADD6432; break;
2094 case X86ISD::ATOMSUB64_DAG: Opc = X86::ATOMSUB6432; break;
2095 case X86ISD::ATOMNAND64_DAG: Opc = X86::ATOMNAND6432; break;
2096 case X86ISD::ATOMAND64_DAG: Opc = X86::ATOMAND6432; break;
2097 case X86ISD::ATOMMAX64_DAG: Opc = X86::ATOMMAX6432; break;
2098 case X86ISD::ATOMMIN64_DAG: Opc = X86::ATOMMIN6432; break;
2099 case X86ISD::ATOMUMAX64_DAG: Opc = X86::ATOMUMAX6432; break;
2100 case X86ISD::ATOMUMIN64_DAG: Opc = X86::ATOMUMIN6432; break;
2101 case X86ISD::ATOMSWAP64_DAG: Opc = X86::ATOMSWAP6432; break;
2103 SDNode *RetVal = SelectAtomic64(Node, Opc);
2109 case ISD::ATOMIC_LOAD_XOR:
2110 case ISD::ATOMIC_LOAD_AND:
2111 case ISD::ATOMIC_LOAD_OR:
2112 case ISD::ATOMIC_LOAD_ADD: {
2113 SDNode *RetVal = SelectAtomicLoadArith(Node, NVT);
2121 // For operations of the form (x << C1) op C2, check if we can use a smaller
2122 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2123 SDValue N0 = Node->getOperand(0);
2124 SDValue N1 = Node->getOperand(1);
2126 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2129 // i8 is unshrinkable, i16 should be promoted to i32.
2130 if (NVT != MVT::i32 && NVT != MVT::i64)
2133 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2134 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2135 if (!Cst || !ShlCst)
2138 int64_t Val = Cst->getSExtValue();
2139 uint64_t ShlVal = ShlCst->getZExtValue();
2141 // Make sure that we don't change the operation by removing bits.
2142 // This only matters for OR and XOR, AND is unaffected.
2143 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2144 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2150 // Check the minimum bitwidth for the new constant.
2151 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2152 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2153 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2154 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2156 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2159 // Bail if there is no smaller encoding.
2163 switch (NVT.getSimpleVT().SimpleTy) {
2164 default: llvm_unreachable("Unsupported VT!");
2166 assert(CstVT == MVT::i8);
2167 ShlOp = X86::SHL32ri;
2170 default: llvm_unreachable("Impossible opcode");
2171 case ISD::AND: Op = X86::AND32ri8; break;
2172 case ISD::OR: Op = X86::OR32ri8; break;
2173 case ISD::XOR: Op = X86::XOR32ri8; break;
2177 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2178 ShlOp = X86::SHL64ri;
2181 default: llvm_unreachable("Impossible opcode");
2182 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2183 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2184 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2189 // Emit the smaller op and the shift.
2190 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, CstVT);
2191 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2192 return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2195 case X86ISD::UMUL: {
2196 SDValue N0 = Node->getOperand(0);
2197 SDValue N1 = Node->getOperand(1);
2200 switch (NVT.getSimpleVT().SimpleTy) {
2201 default: llvm_unreachable("Unsupported VT!");
2202 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2203 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2204 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2205 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2208 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2209 N0, SDValue()).getValue(1);
2211 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2212 SDValue Ops[] = {N1, InFlag};
2213 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2215 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2216 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2217 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
2221 case ISD::SMUL_LOHI:
2222 case ISD::UMUL_LOHI: {
2223 SDValue N0 = Node->getOperand(0);
2224 SDValue N1 = Node->getOperand(1);
2226 bool isSigned = Opcode == ISD::SMUL_LOHI;
2227 bool hasBMI2 = Subtarget->hasBMI2();
2229 switch (NVT.getSimpleVT().SimpleTy) {
2230 default: llvm_unreachable("Unsupported VT!");
2231 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2232 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2233 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2234 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2235 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2236 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2239 switch (NVT.getSimpleVT().SimpleTy) {
2240 default: llvm_unreachable("Unsupported VT!");
2241 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2242 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2243 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2244 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2248 unsigned SrcReg, LoReg, HiReg;
2250 default: llvm_unreachable("Unknown MUL opcode!");
2253 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2257 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2261 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2265 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2268 SrcReg = X86::EDX; LoReg = HiReg = 0;
2271 SrcReg = X86::RDX; LoReg = HiReg = 0;
2275 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2276 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2277 // Multiply is commmutative.
2279 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2284 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2285 N0, SDValue()).getValue(1);
2286 SDValue ResHi, ResLo;
2290 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2292 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2293 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2294 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2295 ResHi = SDValue(CNode, 0);
2296 ResLo = SDValue(CNode, 1);
2297 Chain = SDValue(CNode, 2);
2298 InFlag = SDValue(CNode, 3);
2300 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2301 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2302 Chain = SDValue(CNode, 0);
2303 InFlag = SDValue(CNode, 1);
2306 // Update the chain.
2307 ReplaceUses(N1.getValue(1), Chain);
2309 SDValue Ops[] = { N1, InFlag };
2310 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2311 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2312 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2313 ResHi = SDValue(CNode, 0);
2314 ResLo = SDValue(CNode, 1);
2315 InFlag = SDValue(CNode, 2);
2317 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2318 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2319 InFlag = SDValue(CNode, 0);
2323 // Prevent use of AH in a REX instruction by referencing AX instead.
2324 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2325 !SDValue(Node, 1).use_empty()) {
2326 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2327 X86::AX, MVT::i16, InFlag);
2328 InFlag = Result.getValue(2);
2329 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2331 if (!SDValue(Node, 0).use_empty())
2332 ReplaceUses(SDValue(Node, 1),
2333 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2335 // Shift AX down 8 bits.
2336 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2338 CurDAG->getTargetConstant(8, MVT::i8)), 0);
2339 // Then truncate it down to i8.
2340 ReplaceUses(SDValue(Node, 1),
2341 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2343 // Copy the low half of the result, if it is needed.
2344 if (!SDValue(Node, 0).use_empty()) {
2345 if (ResLo.getNode() == 0) {
2346 assert(LoReg && "Register for low half is not defined!");
2347 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2349 InFlag = ResLo.getValue(2);
2351 ReplaceUses(SDValue(Node, 0), ResLo);
2352 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2354 // Copy the high half of the result, if it is needed.
2355 if (!SDValue(Node, 1).use_empty()) {
2356 if (ResHi.getNode() == 0) {
2357 assert(HiReg && "Register for high half is not defined!");
2358 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2360 InFlag = ResHi.getValue(2);
2362 ReplaceUses(SDValue(Node, 1), ResHi);
2363 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2370 case ISD::UDIVREM: {
2371 SDValue N0 = Node->getOperand(0);
2372 SDValue N1 = Node->getOperand(1);
2374 bool isSigned = Opcode == ISD::SDIVREM;
2376 switch (NVT.getSimpleVT().SimpleTy) {
2377 default: llvm_unreachable("Unsupported VT!");
2378 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2379 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2380 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2381 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2384 switch (NVT.getSimpleVT().SimpleTy) {
2385 default: llvm_unreachable("Unsupported VT!");
2386 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2387 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2388 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2389 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2393 unsigned LoReg, HiReg, ClrReg;
2394 unsigned SExtOpcode;
2395 switch (NVT.getSimpleVT().SimpleTy) {
2396 default: llvm_unreachable("Unsupported VT!");
2398 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2399 SExtOpcode = X86::CBW;
2402 LoReg = X86::AX; HiReg = X86::DX;
2404 SExtOpcode = X86::CWD;
2407 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2408 SExtOpcode = X86::CDQ;
2411 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2412 SExtOpcode = X86::CQO;
2416 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2417 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2418 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2421 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2422 // Special case for div8, just use a move with zero extension to AX to
2423 // clear the upper 8 bits (AH).
2424 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2425 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2426 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2428 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2429 MVT::Other, Ops), 0);
2430 Chain = Move.getValue(1);
2431 ReplaceUses(N0.getValue(1), Chain);
2434 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2435 Chain = CurDAG->getEntryNode();
2437 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2438 InFlag = Chain.getValue(1);
2441 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2442 LoReg, N0, SDValue()).getValue(1);
2443 if (isSigned && !signBitIsZero) {
2444 // Sign extend the low part into the high part.
2446 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2448 // Zero out the high part, effectively zero extending the input.
2449 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2450 switch (NVT.getSimpleVT().SimpleTy) {
2453 SDValue(CurDAG->getMachineNode(
2454 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2455 CurDAG->getTargetConstant(X86::sub_16bit, MVT::i32)),
2462 SDValue(CurDAG->getMachineNode(
2463 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2464 CurDAG->getTargetConstant(0, MVT::i64), ClrNode,
2465 CurDAG->getTargetConstant(X86::sub_32bit, MVT::i32)),
2469 llvm_unreachable("Unexpected division source");
2472 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2473 ClrNode, InFlag).getValue(1);
2478 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2481 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2482 InFlag = SDValue(CNode, 1);
2483 // Update the chain.
2484 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2487 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2490 // Prevent use of AH in a REX instruction by referencing AX instead.
2491 // Shift it down 8 bits.
2492 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2493 !SDValue(Node, 1).use_empty()) {
2494 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2495 X86::AX, MVT::i16, InFlag);
2496 InFlag = Result.getValue(2);
2498 // If we also need AL (the quotient), get it by extracting a subreg from
2499 // Result. The fast register allocator does not like multiple CopyFromReg
2500 // nodes using aliasing registers.
2501 if (!SDValue(Node, 0).use_empty())
2502 ReplaceUses(SDValue(Node, 0),
2503 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2505 // Shift AX right by 8 bits instead of using AH.
2506 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2508 CurDAG->getTargetConstant(8, MVT::i8)),
2510 ReplaceUses(SDValue(Node, 1),
2511 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2513 // Copy the division (low) result, if it is needed.
2514 if (!SDValue(Node, 0).use_empty()) {
2515 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2516 LoReg, NVT, InFlag);
2517 InFlag = Result.getValue(2);
2518 ReplaceUses(SDValue(Node, 0), Result);
2519 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2521 // Copy the remainder (high) result, if it is needed.
2522 if (!SDValue(Node, 1).use_empty()) {
2523 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2524 HiReg, NVT, InFlag);
2525 InFlag = Result.getValue(2);
2526 ReplaceUses(SDValue(Node, 1), Result);
2527 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2534 // Sometimes a SUB is used to perform comparison.
2535 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2536 // This node is not a CMP.
2538 SDValue N0 = Node->getOperand(0);
2539 SDValue N1 = Node->getOperand(1);
2541 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2542 // use a smaller encoding.
2543 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2544 HasNoSignedComparisonUses(Node))
2545 // Look past the truncate if CMP is the only use of it.
2546 N0 = N0.getOperand(0);
2547 if ((N0.getNode()->getOpcode() == ISD::AND ||
2548 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2549 N0.getNode()->hasOneUse() &&
2550 N0.getValueType() != MVT::i8 &&
2551 X86::isZeroNode(N1)) {
2552 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2555 // For example, convert "testl %eax, $8" to "testb %al, $8"
2556 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2557 (!(C->getZExtValue() & 0x80) ||
2558 HasNoSignedComparisonUses(Node))) {
2559 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
2560 SDValue Reg = N0.getNode()->getOperand(0);
2562 // On x86-32, only the ABCD registers have 8-bit subregisters.
2563 if (!Subtarget->is64Bit()) {
2564 const TargetRegisterClass *TRC;
2565 switch (N0.getValueType().getSimpleVT().SimpleTy) {
2566 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2567 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2568 default: llvm_unreachable("Unsupported TEST operand type!");
2570 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
2571 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2572 Reg.getValueType(), Reg, RC), 0);
2575 // Extract the l-register.
2576 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2580 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2582 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2583 // one, do not call ReplaceAllUsesWith.
2584 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2585 SDValue(NewNode, 0));
2589 // For example, "testl %eax, $2048" to "testb %ah, $8".
2590 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2591 (!(C->getZExtValue() & 0x8000) ||
2592 HasNoSignedComparisonUses(Node))) {
2593 // Shift the immediate right by 8 bits.
2594 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2596 SDValue Reg = N0.getNode()->getOperand(0);
2598 // Put the value in an ABCD register.
2599 const TargetRegisterClass *TRC;
2600 switch (N0.getValueType().getSimpleVT().SimpleTy) {
2601 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2602 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2603 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2604 default: llvm_unreachable("Unsupported TEST operand type!");
2606 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
2607 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2608 Reg.getValueType(), Reg, RC), 0);
2610 // Extract the h-register.
2611 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2614 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2615 // target GR8_NOREX registers, so make sure the register class is
2617 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2618 MVT::i32, Subreg, ShiftedImm);
2619 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2620 // one, do not call ReplaceAllUsesWith.
2621 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2622 SDValue(NewNode, 0));
2626 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2627 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2628 N0.getValueType() != MVT::i16 &&
2629 (!(C->getZExtValue() & 0x8000) ||
2630 HasNoSignedComparisonUses(Node))) {
2631 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
2632 SDValue Reg = N0.getNode()->getOperand(0);
2634 // Extract the 16-bit subregister.
2635 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2639 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2641 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2642 // one, do not call ReplaceAllUsesWith.
2643 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2644 SDValue(NewNode, 0));
2648 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2649 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2650 N0.getValueType() == MVT::i64 &&
2651 (!(C->getZExtValue() & 0x80000000) ||
2652 HasNoSignedComparisonUses(Node))) {
2653 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
2654 SDValue Reg = N0.getNode()->getOperand(0);
2656 // Extract the 32-bit subregister.
2657 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2661 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2663 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2664 // one, do not call ReplaceAllUsesWith.
2665 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2666 SDValue(NewNode, 0));
2673 // Change a chain of {load; incr or dec; store} of the same value into
2674 // a simple increment or decrement through memory of that value, if the
2675 // uses of the modified value and its address are suitable.
2676 // The DEC64m tablegen pattern is currently not able to match the case where
2677 // the EFLAGS on the original DEC are used. (This also applies to
2678 // {INC,DEC}X{64,32,16,8}.)
2679 // We'll need to improve tablegen to allow flags to be transferred from a
2680 // node in the pattern to the result node. probably with a new keyword
2681 // for example, we have this
2682 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2683 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2684 // (implicit EFLAGS)]>;
2685 // but maybe need something like this
2686 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2687 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2688 // (transferrable EFLAGS)]>;
2690 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2691 SDValue StoredVal = StoreNode->getOperand(1);
2692 unsigned Opc = StoredVal->getOpcode();
2694 LoadSDNode *LoadNode = 0;
2696 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2697 LoadNode, InputChain))
2700 SDValue Base, Scale, Index, Disp, Segment;
2701 if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
2702 Base, Scale, Index, Disp, Segment))
2705 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2706 MemOp[0] = StoreNode->getMemOperand();
2707 MemOp[1] = LoadNode->getMemOperand();
2708 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2709 EVT LdVT = LoadNode->getMemoryVT();
2710 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2711 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2713 MVT::i32, MVT::Other, Ops);
2714 Result->setMemRefs(MemOp, MemOp + 2);
2716 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2717 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2723 SDNode *ResNode = SelectCode(Node);
2725 DEBUG(dbgs() << "=> ";
2726 if (ResNode == NULL || ResNode == Node)
2729 ResNode->dump(CurDAG);
2735 bool X86DAGToDAGISel::
2736 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
2737 std::vector<SDValue> &OutOps) {
2738 SDValue Op0, Op1, Op2, Op3, Op4;
2739 switch (ConstraintCode) {
2740 case 'o': // offsetable ??
2741 case 'v': // not offsetable ??
2742 default: return true;
2744 if (!SelectAddr(0, Op, Op0, Op1, Op2, Op3, Op4))
2749 OutOps.push_back(Op0);
2750 OutOps.push_back(Op1);
2751 OutOps.push_back(Op2);
2752 OutOps.push_back(Op3);
2753 OutOps.push_back(Op4);
2757 /// createX86ISelDag - This pass converts a legalized DAG into a
2758 /// X86-specific DAG, ready for instruction scheduling.
2760 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2761 CodeGenOpt::Level OptLevel) {
2762 return new X86DAGToDAGISel(TM, OptLevel);