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 "X86ISelLowering.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Type.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAGISel.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/ADT/Statistic.h"
44 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
45 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
48 //===----------------------------------------------------------------------===//
49 // Pattern Matcher Implementation
50 //===----------------------------------------------------------------------===//
53 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
54 /// SDOperand's instead of register numbers for the leaves of the matched
56 struct X86ISelAddressMode {
62 struct { // This is really a union, discriminated by BaseType!
67 bool isRIPRel; // RIP relative?
75 unsigned Align; // CP alignment.
78 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
79 GV(0), CP(0), ES(0), JT(-1), Align(0) {
85 //===--------------------------------------------------------------------===//
86 /// ISel - X86 specific code to select X86 machine instructions for
87 /// SelectionDAG operations.
89 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
90 /// ContainsFPCode - Every instruction we select that uses or defines a FP
91 /// register should set this to true.
94 /// FastISel - Enable fast(er) instruction selection.
98 /// TM - Keep a reference to X86TargetMachine.
100 X86TargetMachine &TM;
102 /// X86Lowering - This object fully describes how to lower LLVM code to an
103 /// X86-specific SelectionDAG.
104 X86TargetLowering X86Lowering;
106 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
107 /// make the right decision when generating code for different targets.
108 const X86Subtarget *Subtarget;
110 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
112 unsigned GlobalBaseReg;
115 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
116 : SelectionDAGISel(X86Lowering),
117 ContainsFPCode(false), FastISel(fast), TM(tm),
118 X86Lowering(*TM.getTargetLowering()),
119 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
121 virtual bool runOnFunction(Function &Fn) {
122 // Make sure we re-emit a set of the global base reg if necessary
124 return SelectionDAGISel::runOnFunction(Fn);
127 virtual const char *getPassName() const {
128 return "X86 DAG->DAG Instruction Selection";
131 /// InstructionSelectBasicBlock - This callback is invoked by
132 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
133 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
135 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
137 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
139 // Include the pieces autogenerated from the target description.
140 #include "X86GenDAGISel.inc"
143 SDNode *Select(SDOperand N);
145 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
146 bool isRoot = true, unsigned Depth = 0);
147 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
148 bool isRoot, unsigned Depth);
149 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
150 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
151 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
152 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
153 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
154 SDOperand N, SDOperand &Base, SDOperand &Scale,
155 SDOperand &Index, SDOperand &Disp,
156 SDOperand &InChain, SDOperand &OutChain);
157 bool TryFoldLoad(SDOperand P, SDOperand N,
158 SDOperand &Base, SDOperand &Scale,
159 SDOperand &Index, SDOperand &Disp);
160 void PreprocessForRMW(SelectionDAG &DAG);
161 void PreprocessForFPConvert(SelectionDAG &DAG);
163 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
164 /// inline asm expressions.
165 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
167 std::vector<SDOperand> &OutOps,
170 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
172 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
173 SDOperand &Scale, SDOperand &Index,
175 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
176 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
178 Scale = getI8Imm(AM.Scale);
180 // These are 32-bit even in 64-bit mode since RIP relative offset
183 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
185 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
187 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
188 else if (AM.JT != -1)
189 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
191 Disp = getI32Imm(AM.Disp);
194 /// getI8Imm - Return a target constant with the specified value, of type
196 inline SDOperand getI8Imm(unsigned Imm) {
197 return CurDAG->getTargetConstant(Imm, MVT::i8);
200 /// getI16Imm - Return a target constant with the specified value, of type
202 inline SDOperand getI16Imm(unsigned Imm) {
203 return CurDAG->getTargetConstant(Imm, MVT::i16);
206 /// getI32Imm - Return a target constant with the specified value, of type
208 inline SDOperand getI32Imm(unsigned Imm) {
209 return CurDAG->getTargetConstant(Imm, MVT::i32);
212 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
213 /// base register. Return the virtual register that holds this value.
214 SDNode *getGlobalBaseReg();
216 /// getTruncate - return an SDNode that implements a subreg based truncate
217 /// of the specified operand to the the specified value type.
218 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
226 static SDNode *findFlagUse(SDNode *N) {
227 unsigned FlagResNo = N->getNumValues()-1;
228 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
230 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
231 SDOperand Op = User->getOperand(i);
232 if (Op.Val == N && Op.ResNo == FlagResNo)
239 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
240 SDNode *Root, SDNode *Skip, bool &found,
241 std::set<SDNode *> &Visited) {
243 Use->getNodeId() > Def->getNodeId() ||
244 !Visited.insert(Use).second)
247 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
248 SDNode *N = Use->getOperand(i).Val;
253 continue; // Immediate use is ok.
255 assert(Use->getOpcode() == ISD::STORE ||
256 Use->getOpcode() == X86ISD::CMP);
262 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
266 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
267 /// be reached. Return true if that's the case. However, ignore direct uses
268 /// by ImmedUse (which would be U in the example illustrated in
269 /// CanBeFoldedBy) and by Root (which can happen in the store case).
270 /// FIXME: to be really generic, we should allow direct use by any node
271 /// that is being folded. But realisticly since we only fold loads which
272 /// have one non-chain use, we only need to watch out for load/op/store
273 /// and load/op/cmp case where the root (store / cmp) may reach the load via
274 /// its chain operand.
275 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
276 SDNode *Skip = NULL) {
277 std::set<SDNode *> Visited;
279 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
284 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
285 if (FastISel) return false;
287 // If U use can somehow reach N through another path then U can't fold N or
288 // it will create a cycle. e.g. In the following diagram, U can reach N
289 // through X. If N is folded into into U, then X is both a predecessor and
300 if (isNonImmUse(Root, N, U))
303 // If U produces a flag, then it gets (even more) interesting. Since it
304 // would have been "glued" together with its flag use, we need to check if
317 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
318 // NU), then TF is a predecessor of FU and a successor of NU. But since
319 // NU and FU are flagged together, this effectively creates a cycle.
320 bool HasFlagUse = false;
321 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
322 while ((VT == MVT::Flag && !Root->use_empty())) {
323 SDNode *FU = findFlagUse(Root);
330 VT = Root->getValueType(Root->getNumValues()-1);
334 return !isNonImmUse(Root, N, Root, U);
338 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
339 /// and move load below the TokenFactor. Replace store's chain operand with
340 /// load's chain result.
341 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
342 SDOperand Store, SDOperand TF) {
343 std::vector<SDOperand> Ops;
344 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
345 if (Load.Val == TF.Val->getOperand(i).Val)
346 Ops.push_back(Load.Val->getOperand(0));
348 Ops.push_back(TF.Val->getOperand(i));
349 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
350 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
351 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
352 Store.getOperand(2), Store.getOperand(3));
355 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
356 /// This is only run if not in -fast mode (aka -O0).
357 /// This allows the instruction selector to pick more read-modify-write
358 /// instructions. This is a common case:
368 /// [TokenFactor] [Op]
375 /// The fact the store's chain operand != load's chain will prevent the
376 /// (store (op (load))) instruction from being selected. We can transform it to:
395 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
396 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
397 E = DAG.allnodes_end(); I != E; ++I) {
398 if (!ISD::isNON_TRUNCStore(I))
400 SDOperand Chain = I->getOperand(0);
401 if (Chain.Val->getOpcode() != ISD::TokenFactor)
404 SDOperand N1 = I->getOperand(1);
405 SDOperand N2 = I->getOperand(2);
406 if (MVT::isFloatingPoint(N1.getValueType()) ||
407 MVT::isVector(N1.getValueType()) ||
413 unsigned Opcode = N1.Val->getOpcode();
422 SDOperand N10 = N1.getOperand(0);
423 SDOperand N11 = N1.getOperand(1);
424 if (ISD::isNON_EXTLoad(N10.Val))
426 else if (ISD::isNON_EXTLoad(N11.Val)) {
430 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
431 (N10.getOperand(1) == N2) &&
432 (N10.Val->getValueType(0) == N1.getValueType());
447 SDOperand N10 = N1.getOperand(0);
448 if (ISD::isNON_EXTLoad(N10.Val))
449 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
450 (N10.getOperand(1) == N2) &&
451 (N10.Val->getValueType(0) == N1.getValueType());
459 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
466 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
467 /// nodes that target the FP stack to be store and load to the stack. This is a
468 /// gross hack. We would like to simply mark these as being illegal, but when
469 /// we do that, legalize produces these when it expands calls, then expands
470 /// these in the same legalize pass. We would like dag combine to be able to
471 /// hack on these between the call expansion and the node legalization. As such
472 /// this pass basically does "really late" legalization of these inline with the
474 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
475 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
476 E = DAG.allnodes_end(); I != E; ) {
477 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
478 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
481 // If the source and destination are SSE registers, then this is a legal
482 // conversion that should not be lowered.
483 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
484 MVT::ValueType DstVT = N->getValueType(0);
485 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
486 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
487 if (SrcIsSSE && DstIsSSE)
490 // If this is an FPStack extension (but not a truncation), it is a noop.
491 if (!SrcIsSSE && !DstIsSSE && N->getOpcode() == ISD::FP_EXTEND)
494 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
495 // FPStack has extload and truncstore. SSE can fold direct loads into other
496 // operations. Based on this, decide what we want to do.
497 MVT::ValueType MemVT;
498 if (N->getOpcode() == ISD::FP_ROUND)
499 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
501 MemVT = SrcIsSSE ? SrcVT : DstVT;
503 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
505 // FIXME: optimize the case where the src/dest is a load or store?
506 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
507 MemTmp, NULL, 0, MemVT);
508 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
511 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
512 // extload we created. This will cause general havok on the dag because
513 // anything below the conversion could be folded into other existing nodes.
514 // To avoid invalidating 'I', back it up to the convert node.
516 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
518 // Now that we did that, the node is dead. Increment the iterator to the
519 // next node to process, then delete N.
525 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
526 /// when it has created a SelectionDAG for us to codegen.
527 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
529 MachineFunction::iterator FirstMBB = BB;
532 PreprocessForRMW(DAG);
534 // FIXME: This should only happen when not -fast.
535 PreprocessForFPConvert(DAG);
537 // Codegen the basic block.
539 DOUT << "===== Instruction selection begins:\n";
542 DAG.setRoot(SelectRoot(DAG.getRoot()));
544 DOUT << "===== Instruction selection ends:\n";
547 DAG.RemoveDeadNodes();
549 // Emit machine code to BB.
550 ScheduleAndEmitDAG(DAG);
552 // If we are emitting FP stack code, scan the basic block to determine if this
553 // block defines any FP values. If so, put an FP_REG_KILL instruction before
554 // the terminator of the block.
556 // Note that FP stack instructions are used in all modes for long double,
557 // so we always need to do this check.
558 // Also note that it's possible for an FP stack register to be live across
559 // an instruction that produces multiple basic blocks (SSE CMOV) so we
560 // must check all the generated basic blocks.
562 // Scan all of the machine instructions in these MBBs, checking for FP
563 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
564 MachineFunction::iterator MBBI = FirstMBB;
566 bool ContainsFPCode = false;
567 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
568 !ContainsFPCode && I != E; ++I) {
569 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
570 const TargetRegisterClass *clas;
571 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
572 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
573 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
574 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
575 X86::RFP32RegisterClass ||
576 clas == X86::RFP64RegisterClass ||
577 clas == X86::RFP80RegisterClass)) {
578 ContainsFPCode = true;
584 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
585 // a copy of the input value in this block. In SSE mode, we only care about
587 if (!ContainsFPCode) {
588 // Final check, check LLVM BB's that are successors to the LLVM BB
589 // corresponding to BB for FP PHI nodes.
590 const BasicBlock *LLVMBB = BB->getBasicBlock();
592 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
593 !ContainsFPCode && SI != E; ++SI) {
594 for (BasicBlock::const_iterator II = SI->begin();
595 (PN = dyn_cast<PHINode>(II)); ++II) {
596 if (PN->getType()==Type::X86_FP80Ty ||
597 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
598 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
599 ContainsFPCode = true;
605 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
606 if (ContainsFPCode) {
607 BuildMI(*MBBI, MBBI->getFirstTerminator(),
608 TM.getInstrInfo()->get(X86::FP_REG_KILL));
611 } while (&*(MBBI++) != BB);
614 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
615 /// the main function.
616 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
617 MachineFrameInfo *MFI) {
618 const TargetInstrInfo *TII = TM.getInstrInfo();
619 if (Subtarget->isTargetCygMing())
620 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
623 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
624 // If this is main, emit special code for main.
625 MachineBasicBlock *BB = MF.begin();
626 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
627 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
630 /// MatchAddress - Add the specified node to the specified addressing mode,
631 /// returning true if it cannot be done. This just pattern matches for the
633 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
634 bool isRoot, unsigned Depth) {
637 return MatchAddressBase(N, AM, isRoot, Depth);
639 // RIP relative addressing: %rip + 32-bit displacement!
641 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
642 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
643 if (isInt32(AM.Disp + Val)) {
651 int id = N.Val->getNodeId();
652 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
654 switch (N.getOpcode()) {
656 case ISD::Constant: {
657 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
658 if (isInt32(AM.Disp + Val)) {
665 case X86ISD::Wrapper: {
666 bool is64Bit = Subtarget->is64Bit();
667 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
668 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
670 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
672 // If value is available in a register both base and index components have
673 // been picked, we can't fit the result available in the register in the
674 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
675 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
676 bool isStatic = TM.getRelocationModel() == Reloc::Static;
677 SDOperand N0 = N.getOperand(0);
678 // Mac OS X X86-64 lower 4G address is not available.
679 bool isAbs32 = !is64Bit ||
680 (isStatic && Subtarget->hasLow4GUserSpaceAddress());
681 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
682 GlobalValue *GV = G->getGlobal();
683 if (isAbs32 || isRoot) {
685 AM.Disp += G->getOffset();
686 AM.isRIPRel = !isAbs32;
689 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
690 if (isAbs32 || isRoot) {
691 AM.CP = CP->getConstVal();
692 AM.Align = CP->getAlignment();
693 AM.Disp += CP->getOffset();
694 AM.isRIPRel = !isAbs32;
697 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
698 if (isAbs32 || isRoot) {
699 AM.ES = S->getSymbol();
700 AM.isRIPRel = !isAbs32;
703 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
704 if (isAbs32 || isRoot) {
705 AM.JT = J->getIndex();
706 AM.isRIPRel = !isAbs32;
714 case ISD::FrameIndex:
715 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
716 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
717 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
723 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1)
726 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
727 unsigned Val = CN->getValue();
728 if (Val == 1 || Val == 2 || Val == 3) {
730 SDOperand ShVal = N.Val->getOperand(0);
732 // Okay, we know that we have a scale by now. However, if the scaled
733 // value is an add of something and a constant, we can fold the
734 // constant into the disp field here.
735 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
736 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
737 AM.IndexReg = ShVal.Val->getOperand(0);
738 ConstantSDNode *AddVal =
739 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
740 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
755 // A mul_lohi where we need the low part can be folded as a plain multiply.
756 if (N.ResNo != 0) break;
759 // X*[3,5,9] -> X+X*[2,4,8]
760 if (!AlreadySelected &&
761 AM.BaseType == X86ISelAddressMode::RegBase &&
762 AM.Base.Reg.Val == 0 &&
763 AM.IndexReg.Val == 0) {
764 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
765 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
766 AM.Scale = unsigned(CN->getValue())-1;
768 SDOperand MulVal = N.Val->getOperand(0);
771 // Okay, we know that we have a scale by now. However, if the scaled
772 // value is an add of something and a constant, we can fold the
773 // constant into the disp field here.
774 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
775 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
776 Reg = MulVal.Val->getOperand(0);
777 ConstantSDNode *AddVal =
778 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
779 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
783 Reg = N.Val->getOperand(0);
785 Reg = N.Val->getOperand(0);
788 AM.IndexReg = AM.Base.Reg = Reg;
795 if (!AlreadySelected) {
796 X86ISelAddressMode Backup = AM;
797 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
798 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
801 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
802 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
809 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
810 if (AlreadySelected) break;
812 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
813 X86ISelAddressMode Backup = AM;
814 // Start with the LHS as an addr mode.
815 if (!MatchAddress(N.getOperand(0), AM, false) &&
816 // Address could not have picked a GV address for the displacement.
818 // On x86-64, the resultant disp must fit in 32-bits.
819 isInt32(AM.Disp + CN->getSignExtended()) &&
820 // Check to see if the LHS & C is zero.
821 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
822 AM.Disp += CN->getValue();
830 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
831 // allows us to fold the shift into this addressing mode.
832 if (AlreadySelected) break;
833 SDOperand Shift = N.getOperand(0);
834 if (Shift.getOpcode() != ISD::SHL) break;
836 // Scale must not be used already.
837 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
839 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
840 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
841 if (!C1 || !C2) break;
843 // Not likely to be profitable if either the AND or SHIFT node has more
844 // than one use (unless all uses are for address computation). Besides,
845 // isel mechanism requires their node ids to be reused.
846 if (!N.hasOneUse() || !Shift.hasOneUse())
849 // Verify that the shift amount is something we can fold.
850 unsigned ShiftCst = C1->getValue();
851 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
854 // Get the new AND mask, this folds to a constant.
855 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
856 SDOperand(C2, 0), SDOperand(C1, 0));
857 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
858 Shift.getOperand(0), NewANDMask);
859 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
860 NewAND.Val->setNodeId(N.Val->getNodeId());
862 AM.Scale = 1 << ShiftCst;
863 AM.IndexReg = NewAND;
868 return MatchAddressBase(N, AM, isRoot, Depth);
871 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
872 /// specified addressing mode without any further recursion.
873 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
874 bool isRoot, unsigned Depth) {
875 // Is the base register already occupied?
876 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
877 // If so, check to see if the scale index register is set.
878 if (AM.IndexReg.Val == 0) {
884 // Otherwise, we cannot select it.
888 // Default, generate it as a register.
889 AM.BaseType = X86ISelAddressMode::RegBase;
894 /// SelectAddr - returns true if it is able pattern match an addressing mode.
895 /// It returns the operands which make up the maximal addressing mode it can
896 /// match by reference.
897 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
898 SDOperand &Scale, SDOperand &Index,
900 X86ISelAddressMode AM;
901 if (MatchAddress(N, AM))
904 MVT::ValueType VT = N.getValueType();
905 if (AM.BaseType == X86ISelAddressMode::RegBase) {
906 if (!AM.Base.Reg.Val)
907 AM.Base.Reg = CurDAG->getRegister(0, VT);
910 if (!AM.IndexReg.Val)
911 AM.IndexReg = CurDAG->getRegister(0, VT);
913 getAddressOperands(AM, Base, Scale, Index, Disp);
917 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
919 static inline bool isZeroNode(SDOperand Elt) {
920 return ((isa<ConstantSDNode>(Elt) &&
921 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
922 (isa<ConstantFPSDNode>(Elt) &&
923 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
927 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
928 /// match a load whose top elements are either undef or zeros. The load flavor
929 /// is derived from the type of N, which is either v4f32 or v2f64.
930 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
931 SDOperand N, SDOperand &Base,
932 SDOperand &Scale, SDOperand &Index,
933 SDOperand &Disp, SDOperand &InChain,
934 SDOperand &OutChain) {
935 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
936 InChain = N.getOperand(0).getValue(1);
937 if (ISD::isNON_EXTLoad(InChain.Val) &&
938 InChain.getValue(0).hasOneUse() &&
940 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
941 LoadSDNode *LD = cast<LoadSDNode>(InChain);
942 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
944 OutChain = LD->getChain();
949 // Also handle the case where we explicitly require zeros in the top
950 // elements. This is a vector shuffle from the zero vector.
951 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
952 // Check to see if the top elements are all zeros (or bitcast of zeros).
953 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
954 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
955 N.getOperand(1).Val->hasOneUse() &&
956 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
957 N.getOperand(1).getOperand(0).hasOneUse()) {
958 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
960 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
961 SDOperand ShufMask = N.getOperand(2);
962 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
963 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
964 if (C->getValue() == VecWidth) {
965 for (unsigned i = 1; i != VecWidth; ++i) {
966 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
969 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
970 if (C->getValue() >= VecWidth) return false;
975 // Okay, this is a zero extending load. Fold it.
976 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
977 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
979 OutChain = LD->getChain();
980 InChain = SDOperand(LD, 1);
988 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
989 /// mode it matches can be cost effectively emitted as an LEA instruction.
990 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
991 SDOperand &Base, SDOperand &Scale,
992 SDOperand &Index, SDOperand &Disp) {
993 X86ISelAddressMode AM;
994 if (MatchAddress(N, AM))
997 MVT::ValueType VT = N.getValueType();
998 unsigned Complexity = 0;
999 if (AM.BaseType == X86ISelAddressMode::RegBase)
1000 if (AM.Base.Reg.Val)
1003 AM.Base.Reg = CurDAG->getRegister(0, VT);
1004 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1007 if (AM.IndexReg.Val)
1010 AM.IndexReg = CurDAG->getRegister(0, VT);
1012 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1017 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1018 // to a LEA. This is determined with some expermentation but is by no means
1019 // optimal (especially for code size consideration). LEA is nice because of
1020 // its three-address nature. Tweak the cost function again when we can run
1021 // convertToThreeAddress() at register allocation time.
1022 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1023 // For X86-64, we should always use lea to materialize RIP relative
1025 if (Subtarget->is64Bit())
1031 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1034 if (Complexity > 2) {
1035 getAddressOperands(AM, Base, Scale, Index, Disp);
1041 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1042 SDOperand &Base, SDOperand &Scale,
1043 SDOperand &Index, SDOperand &Disp) {
1044 if (ISD::isNON_EXTLoad(N.Val) &&
1046 CanBeFoldedBy(N.Val, P.Val, P.Val))
1047 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1051 /// getGlobalBaseReg - Output the instructions required to put the
1052 /// base address to use for accessing globals into a register.
1054 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1055 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1056 if (!GlobalBaseReg) {
1057 // Insert the set of GlobalBaseReg into the first MBB of the function
1058 MachineFunction *MF = BB->getParent();
1059 MachineBasicBlock &FirstMBB = MF->front();
1060 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1061 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1062 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1064 const TargetInstrInfo *TII = TM.getInstrInfo();
1065 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1066 // only used in JIT code emission as displacement to pc.
1067 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1069 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1070 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1071 if (TM.getRelocationModel() == Reloc::PIC_ &&
1072 Subtarget->isPICStyleGOT()) {
1073 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1074 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1075 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1081 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1084 static SDNode *FindCallStartFromCall(SDNode *Node) {
1085 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1086 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1087 "Node doesn't have a token chain argument!");
1088 return FindCallStartFromCall(Node->getOperand(0).Val);
1091 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1095 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1096 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1097 if (!Subtarget->is64Bit()) {
1100 switch (N0.getValueType()) {
1101 default: assert(0 && "Unknown truncate!");
1103 Opc = X86::MOV16to16_;
1107 Opc = X86::MOV32to32_;
1111 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1112 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1113 VT, N0, SRIdx, N0.getValue(1));
1117 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1120 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1122 default: assert(0 && "Unknown truncate!"); break;
1124 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1128 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1129 SDNode *Node = N.Val;
1130 MVT::ValueType NVT = Node->getValueType(0);
1132 unsigned Opcode = Node->getOpcode();
1135 DOUT << std::string(Indent, ' ') << "Selecting: ";
1136 DEBUG(Node->dump(CurDAG));
1141 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1143 DOUT << std::string(Indent-2, ' ') << "== ";
1144 DEBUG(Node->dump(CurDAG));
1148 return NULL; // Already selected.
1153 case X86ISD::GlobalBaseReg:
1154 return getGlobalBaseReg();
1156 case X86ISD::FP_GET_RESULT2: {
1157 SDOperand Chain = N.getOperand(0);
1158 SDOperand InFlag = N.getOperand(1);
1159 AddToISelQueue(Chain);
1160 AddToISelQueue(InFlag);
1161 std::vector<MVT::ValueType> Tys;
1162 Tys.push_back(MVT::f80);
1163 Tys.push_back(MVT::f80);
1164 Tys.push_back(MVT::Other);
1165 Tys.push_back(MVT::Flag);
1166 SDOperand Ops[] = { Chain, InFlag };
1167 SDNode *ResNode = CurDAG->getTargetNode(X86::FpGETRESULT80x2, Tys,
1169 Chain = SDOperand(ResNode, 2);
1170 InFlag = SDOperand(ResNode, 3);
1171 ReplaceUses(SDOperand(N.Val, 2), Chain);
1172 ReplaceUses(SDOperand(N.Val, 3), InFlag);
1177 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1178 // code and is matched first so to prevent it from being turned into
1180 // In 64-bit small code size mode, use LEA to take advantage of
1181 // RIP-relative addressing.
1182 if (TM.getCodeModel() != CodeModel::Small)
1184 MVT::ValueType PtrVT = TLI.getPointerTy();
1185 SDOperand N0 = N.getOperand(0);
1186 SDOperand N1 = N.getOperand(1);
1187 if (N.Val->getValueType(0) == PtrVT &&
1188 N0.getOpcode() == X86ISD::Wrapper &&
1189 N1.getOpcode() == ISD::Constant) {
1190 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1192 // TODO: handle ExternalSymbolSDNode.
1193 if (GlobalAddressSDNode *G =
1194 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1195 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1196 G->getOffset() + Offset);
1197 } else if (ConstantPoolSDNode *CP =
1198 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1199 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1201 CP->getOffset()+Offset);
1205 if (Subtarget->is64Bit()) {
1206 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1207 CurDAG->getRegister(0, PtrVT), C };
1208 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1210 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1214 // Other cases are handled by auto-generated code.
1218 case ISD::SMUL_LOHI:
1219 case ISD::UMUL_LOHI: {
1220 SDOperand N0 = Node->getOperand(0);
1221 SDOperand N1 = Node->getOperand(1);
1223 // There are several forms of IMUL that just return the low part and
1224 // don't have fixed-register operands. If we don't need the high part,
1225 // use these instead. They can be selected with the generated ISel code.
1226 if (NVT != MVT::i8 &&
1227 N.getValue(1).use_empty()) {
1228 N = CurDAG->getNode(ISD::MUL, NVT, N0, N1);
1232 bool isSigned = Opcode == ISD::SMUL_LOHI;
1235 default: assert(0 && "Unsupported VT!");
1236 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1237 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1238 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1239 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1243 default: assert(0 && "Unsupported VT!");
1244 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1245 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1246 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1247 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1250 unsigned LoReg, HiReg;
1252 default: assert(0 && "Unsupported VT!");
1253 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1254 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1255 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1256 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1259 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1260 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1261 // multiplty is commmutative
1263 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1269 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1270 N0, SDOperand()).getValue(1);
1273 AddToISelQueue(N1.getOperand(0));
1274 AddToISelQueue(Tmp0);
1275 AddToISelQueue(Tmp1);
1276 AddToISelQueue(Tmp2);
1277 AddToISelQueue(Tmp3);
1278 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1280 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1281 InFlag = SDOperand(CNode, 1);
1282 // Update the chain.
1283 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1287 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1290 // Copy the low half of the result, if it is needed.
1291 if (!N.getValue(0).use_empty()) {
1292 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1293 LoReg, NVT, InFlag);
1294 InFlag = Result.getValue(2);
1295 ReplaceUses(N.getValue(0), Result);
1297 DOUT << std::string(Indent-2, ' ') << "=> ";
1298 DEBUG(Result.Val->dump(CurDAG));
1302 // Copy the high half of the result, if it is needed.
1303 if (!N.getValue(1).use_empty()) {
1305 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1306 // Prevent use of AH in a REX instruction by referencing AX instead.
1307 // Shift it down 8 bits.
1308 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1309 X86::AX, MVT::i16, InFlag);
1310 InFlag = Result.getValue(2);
1311 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1312 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1313 // Then truncate it down to i8.
1314 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1315 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1316 MVT::i8, Result, SRIdx), 0);
1318 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1319 HiReg, NVT, InFlag);
1320 InFlag = Result.getValue(2);
1322 ReplaceUses(N.getValue(1), Result);
1324 DOUT << std::string(Indent-2, ' ') << "=> ";
1325 DEBUG(Result.Val->dump(CurDAG));
1338 case ISD::UDIVREM: {
1339 SDOperand N0 = Node->getOperand(0);
1340 SDOperand N1 = Node->getOperand(1);
1342 bool isSigned = Opcode == ISD::SDIVREM;
1345 default: assert(0 && "Unsupported VT!");
1346 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1347 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1348 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1349 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1353 default: assert(0 && "Unsupported VT!");
1354 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1355 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1356 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1357 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1360 unsigned LoReg, HiReg;
1361 unsigned ClrOpcode, SExtOpcode;
1363 default: assert(0 && "Unsupported VT!");
1365 LoReg = X86::AL; HiReg = X86::AH;
1367 SExtOpcode = X86::CBW;
1370 LoReg = X86::AX; HiReg = X86::DX;
1371 ClrOpcode = X86::MOV16r0;
1372 SExtOpcode = X86::CWD;
1375 LoReg = X86::EAX; HiReg = X86::EDX;
1376 ClrOpcode = X86::MOV32r0;
1377 SExtOpcode = X86::CDQ;
1380 LoReg = X86::RAX; HiReg = X86::RDX;
1381 ClrOpcode = X86::MOV64r0;
1382 SExtOpcode = X86::CQO;
1386 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1387 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1390 if (NVT == MVT::i8 && !isSigned) {
1391 // Special case for div8, just use a move with zero extension to AX to
1392 // clear the upper 8 bits (AH).
1393 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1394 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1395 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1396 AddToISelQueue(N0.getOperand(0));
1397 AddToISelQueue(Tmp0);
1398 AddToISelQueue(Tmp1);
1399 AddToISelQueue(Tmp2);
1400 AddToISelQueue(Tmp3);
1402 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1404 Chain = Move.getValue(1);
1405 ReplaceUses(N0.getValue(1), Chain);
1409 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1410 Chain = CurDAG->getEntryNode();
1412 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1413 InFlag = Chain.getValue(1);
1417 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1418 LoReg, N0, SDOperand()).getValue(1);
1420 // Sign extend the low part into the high part.
1422 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1424 // Zero out the high part, effectively zero extending the input.
1425 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1426 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1427 ClrNode, InFlag).getValue(1);
1432 AddToISelQueue(N1.getOperand(0));
1433 AddToISelQueue(Tmp0);
1434 AddToISelQueue(Tmp1);
1435 AddToISelQueue(Tmp2);
1436 AddToISelQueue(Tmp3);
1437 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1439 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1440 InFlag = SDOperand(CNode, 1);
1441 // Update the chain.
1442 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1446 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1449 // Copy the division (low) result, if it is needed.
1450 if (!N.getValue(0).use_empty()) {
1451 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1452 LoReg, NVT, InFlag);
1453 InFlag = Result.getValue(2);
1454 ReplaceUses(N.getValue(0), Result);
1456 DOUT << std::string(Indent-2, ' ') << "=> ";
1457 DEBUG(Result.Val->dump(CurDAG));
1461 // Copy the remainder (high) result, if it is needed.
1462 if (!N.getValue(1).use_empty()) {
1464 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1465 // Prevent use of AH in a REX instruction by referencing AX instead.
1466 // Shift it down 8 bits.
1467 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1468 X86::AX, MVT::i16, InFlag);
1469 InFlag = Result.getValue(2);
1470 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1471 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1472 // Then truncate it down to i8.
1473 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1474 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1475 MVT::i8, Result, SRIdx), 0);
1477 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1478 HiReg, NVT, InFlag);
1479 InFlag = Result.getValue(2);
1481 ReplaceUses(N.getValue(1), Result);
1483 DOUT << std::string(Indent-2, ' ') << "=> ";
1484 DEBUG(Result.Val->dump(CurDAG));
1496 case ISD::ANY_EXTEND: {
1497 SDOperand N0 = Node->getOperand(0);
1499 if (NVT == MVT::i64 || NVT == MVT::i32 || NVT == MVT::i16) {
1501 switch(N0.getValueType()) {
1503 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1506 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1509 if (Subtarget->is64Bit())
1510 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1512 default: assert(0 && "Unknown any_extend!");
1515 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1519 DOUT << std::string(Indent-2, ' ') << "=> ";
1520 DEBUG(ResNode->dump(CurDAG));
1525 } // Otherwise let generated ISel handle it.
1530 case ISD::SIGN_EXTEND_INREG: {
1531 SDOperand N0 = Node->getOperand(0);
1534 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1535 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1539 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1540 else assert(0 && "Unknown sign_extend_inreg!");
1544 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1545 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1546 default: assert(0 && "Unknown sign_extend_inreg!");
1551 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1552 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1553 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1554 default: assert(0 && "Unknown sign_extend_inreg!");
1557 default: assert(0 && "Unknown sign_extend_inreg!");
1560 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1563 DOUT << std::string(Indent-2, ' ') << "=> ";
1564 DEBUG(TruncOp.Val->dump(CurDAG));
1566 DOUT << std::string(Indent-2, ' ') << "=> ";
1567 DEBUG(ResNode->dump(CurDAG));
1575 case ISD::TRUNCATE: {
1576 SDOperand Input = Node->getOperand(0);
1577 AddToISelQueue(Node->getOperand(0));
1578 SDNode *ResNode = getTruncate(Input, NVT);
1581 DOUT << std::string(Indent-2, ' ') << "=> ";
1582 DEBUG(ResNode->dump(CurDAG));
1591 SDNode *ResNode = SelectCode(N);
1594 DOUT << std::string(Indent-2, ' ') << "=> ";
1595 if (ResNode == NULL || ResNode == N.Val)
1596 DEBUG(N.Val->dump(CurDAG));
1598 DEBUG(ResNode->dump(CurDAG));
1606 bool X86DAGToDAGISel::
1607 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1608 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1609 SDOperand Op0, Op1, Op2, Op3;
1610 switch (ConstraintCode) {
1611 case 'o': // offsetable ??
1612 case 'v': // not offsetable ??
1613 default: return true;
1615 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1620 OutOps.push_back(Op0);
1621 OutOps.push_back(Op1);
1622 OutOps.push_back(Op2);
1623 OutOps.push_back(Op3);
1624 AddToISelQueue(Op0);
1625 AddToISelQueue(Op1);
1626 AddToISelQueue(Op2);
1627 AddToISelQueue(Op3);
1631 /// createX86ISelDag - This pass converts a legalized DAG into a
1632 /// X86-specific DAG, ready for instruction scheduling.
1634 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1635 return new X86DAGToDAGISel(TM, Fast);