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/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/CommandLine.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");
47 //===----------------------------------------------------------------------===//
48 // Pattern Matcher Implementation
49 //===----------------------------------------------------------------------===//
52 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
53 /// SDOperand's instead of register numbers for the leaves of the matched
55 struct X86ISelAddressMode {
61 struct { // This is really a union, discriminated by BaseType!
66 bool isRIPRel; // RIP as base?
74 unsigned Align; // CP alignment.
77 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
78 GV(0), CP(0), ES(0), JT(-1), Align(0) {
84 //===--------------------------------------------------------------------===//
85 /// ISel - X86 specific code to select X86 machine instructions for
86 /// SelectionDAG operations.
88 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
89 /// ContainsFPCode - Every instruction we select that uses or defines a FP
90 /// register should set this to true.
93 /// FastISel - Enable fast(er) instruction selection.
97 /// TM - Keep a reference to X86TargetMachine.
101 /// X86Lowering - This object fully describes how to lower LLVM code to an
102 /// X86-specific SelectionDAG.
103 X86TargetLowering X86Lowering;
105 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const X86Subtarget *Subtarget;
109 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
111 unsigned GlobalBaseReg;
114 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
115 : SelectionDAGISel(X86Lowering),
116 ContainsFPCode(false), FastISel(fast), TM(tm),
117 X86Lowering(*TM.getTargetLowering()),
118 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
120 virtual bool runOnFunction(Function &Fn) {
121 // Make sure we re-emit a set of the global base reg if necessary
123 return SelectionDAGISel::runOnFunction(Fn);
126 virtual const char *getPassName() const {
127 return "X86 DAG->DAG Instruction Selection";
130 /// InstructionSelectBasicBlock - This callback is invoked by
131 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
134 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
136 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
138 // Include the pieces autogenerated from the target description.
139 #include "X86GenDAGISel.inc"
142 SDNode *Select(SDOperand N);
144 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
145 bool isRoot = true, unsigned Depth = 0);
146 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
147 bool isRoot, unsigned Depth);
148 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
149 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
150 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
151 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
152 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
153 SDOperand N, SDOperand &Base, SDOperand &Scale,
154 SDOperand &Index, SDOperand &Disp,
155 SDOperand &InChain, SDOperand &OutChain);
156 bool TryFoldLoad(SDOperand P, SDOperand N,
157 SDOperand &Base, SDOperand &Scale,
158 SDOperand &Index, SDOperand &Disp);
159 void PreprocessForRMW(SelectionDAG &DAG);
160 void PreprocessForFPConvert(SelectionDAG &DAG);
162 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
163 /// inline asm expressions.
164 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
166 std::vector<SDOperand> &OutOps,
169 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
171 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
172 SDOperand &Scale, SDOperand &Index,
174 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
175 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
177 Scale = getI8Imm(AM.Scale);
179 // These are 32-bit even in 64-bit mode since RIP relative offset
182 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
184 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
186 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
187 else if (AM.JT != -1)
188 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
190 Disp = getI32Imm(AM.Disp);
193 /// getI8Imm - Return a target constant with the specified value, of type
195 inline SDOperand getI8Imm(unsigned Imm) {
196 return CurDAG->getTargetConstant(Imm, MVT::i8);
199 /// getI16Imm - Return a target constant with the specified value, of type
201 inline SDOperand getI16Imm(unsigned Imm) {
202 return CurDAG->getTargetConstant(Imm, MVT::i16);
205 /// getI32Imm - Return a target constant with the specified value, of type
207 inline SDOperand getI32Imm(unsigned Imm) {
208 return CurDAG->getTargetConstant(Imm, MVT::i32);
211 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
212 /// base register. Return the virtual register that holds this value.
213 SDNode *getGlobalBaseReg();
215 /// getTruncate - return an SDNode that implements a subreg based truncate
216 /// of the specified operand to the the specified value type.
217 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
225 static SDNode *findFlagUse(SDNode *N) {
226 unsigned FlagResNo = N->getNumValues()-1;
227 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
229 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
230 SDOperand Op = User->getOperand(i);
231 if (Op.Val == N && Op.ResNo == FlagResNo)
238 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
239 SDNode *Root, SDNode *Skip, bool &found,
240 std::set<SDNode *> &Visited) {
242 Use->getNodeId() > Def->getNodeId() ||
243 !Visited.insert(Use).second)
246 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
247 SDNode *N = Use->getOperand(i).Val;
252 continue; // Immediate use is ok.
254 assert(Use->getOpcode() == ISD::STORE ||
255 Use->getOpcode() == X86ISD::CMP);
261 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
265 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
266 /// be reached. Return true if that's the case. However, ignore direct uses
267 /// by ImmedUse (which would be U in the example illustrated in
268 /// CanBeFoldedBy) and by Root (which can happen in the store case).
269 /// FIXME: to be really generic, we should allow direct use by any node
270 /// that is being folded. But realisticly since we only fold loads which
271 /// have one non-chain use, we only need to watch out for load/op/store
272 /// and load/op/cmp case where the root (store / cmp) may reach the load via
273 /// its chain operand.
274 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
275 SDNode *Skip = NULL) {
276 std::set<SDNode *> Visited;
278 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
283 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
284 if (FastISel) return false;
286 // If U use can somehow reach N through another path then U can't fold N or
287 // it will create a cycle. e.g. In the following diagram, U can reach N
288 // through X. If N is folded into into U, then X is both a predecessor and
299 if (isNonImmUse(Root, N, U))
302 // If U produces a flag, then it gets (even more) interesting. Since it
303 // would have been "glued" together with its flag use, we need to check if
316 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
317 // NU), then TF is a predecessor of FU and a successor of NU. But since
318 // NU and FU are flagged together, this effectively creates a cycle.
319 bool HasFlagUse = false;
320 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
321 while ((VT == MVT::Flag && !Root->use_empty())) {
322 SDNode *FU = findFlagUse(Root);
329 VT = Root->getValueType(Root->getNumValues()-1);
333 return !isNonImmUse(Root, N, Root, U);
337 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
338 /// and move load below the TokenFactor. Replace store's chain operand with
339 /// load's chain result.
340 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
341 SDOperand Store, SDOperand TF) {
342 std::vector<SDOperand> Ops;
343 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
344 if (Load.Val == TF.Val->getOperand(i).Val)
345 Ops.push_back(Load.Val->getOperand(0));
347 Ops.push_back(TF.Val->getOperand(i));
348 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
349 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
350 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
351 Store.getOperand(2), Store.getOperand(3));
354 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
355 /// This is only run if not in -fast mode (aka -O0).
356 /// This allows the instruction selector to pick more read-modify-write
357 /// instructions. This is a common case:
367 /// [TokenFactor] [Op]
374 /// The fact the store's chain operand != load's chain will prevent the
375 /// (store (op (load))) instruction from being selected. We can transform it to:
394 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
395 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
396 E = DAG.allnodes_end(); I != E; ++I) {
397 if (!ISD::isNON_TRUNCStore(I))
399 SDOperand Chain = I->getOperand(0);
400 if (Chain.Val->getOpcode() != ISD::TokenFactor)
403 SDOperand N1 = I->getOperand(1);
404 SDOperand N2 = I->getOperand(2);
405 if (MVT::isFloatingPoint(N1.getValueType()) ||
406 MVT::isVector(N1.getValueType()) ||
412 unsigned Opcode = N1.Val->getOpcode();
421 SDOperand N10 = N1.getOperand(0);
422 SDOperand N11 = N1.getOperand(1);
423 if (ISD::isNON_EXTLoad(N10.Val))
425 else if (ISD::isNON_EXTLoad(N11.Val)) {
429 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
430 (N10.getOperand(1) == N2) &&
431 (N10.Val->getValueType(0) == N1.getValueType());
446 SDOperand N10 = N1.getOperand(0);
447 if (ISD::isNON_EXTLoad(N10.Val))
448 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
449 (N10.getOperand(1) == N2) &&
450 (N10.Val->getValueType(0) == N1.getValueType());
458 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
465 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
466 /// nodes that target the FP stack to be store and load to the stack. This is a
467 /// gross hack. We would like to simply mark these as being illegal, but when
468 /// we do that, legalize produces these when it expands calls, then expands
469 /// these in the same legalize pass. We would like dag combine to be able to
470 /// hack on these between the call expansion and the node legalization. As such
471 /// this pass basically does "really late" legalization of these inline with the
473 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
474 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
475 E = DAG.allnodes_end(); I != E; ) {
476 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
477 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
480 // If the source and destination are SSE registers, then this is a legal
481 // conversion that should not be lowered.
482 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
483 MVT::ValueType DstVT = N->getValueType(0);
484 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
485 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
486 if (SrcIsSSE && DstIsSSE)
489 if (!SrcIsSSE && !DstIsSSE) {
490 // If this is an FPStack extension, it is a noop.
491 if (N->getOpcode() == ISD::FP_EXTEND)
493 // If this is a value-preserving FPStack truncation, it is a noop.
494 if (N->getConstantOperandVal(1))
498 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
499 // FPStack has extload and truncstore. SSE can fold direct loads into other
500 // operations. Based on this, decide what we want to do.
501 MVT::ValueType MemVT;
502 if (N->getOpcode() == ISD::FP_ROUND)
503 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
505 MemVT = SrcIsSSE ? SrcVT : DstVT;
507 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
509 // FIXME: optimize the case where the src/dest is a load or store?
510 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
511 MemTmp, NULL, 0, MemVT);
512 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
515 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
516 // extload we created. This will cause general havok on the dag because
517 // anything below the conversion could be folded into other existing nodes.
518 // To avoid invalidating 'I', back it up to the convert node.
520 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
522 // Now that we did that, the node is dead. Increment the iterator to the
523 // next node to process, then delete N.
529 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
530 /// when it has created a SelectionDAG for us to codegen.
531 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
533 MachineFunction::iterator FirstMBB = BB;
536 PreprocessForRMW(DAG);
538 // FIXME: This should only happen when not -fast.
539 PreprocessForFPConvert(DAG);
541 // Codegen the basic block.
543 DOUT << "===== Instruction selection begins:\n";
546 DAG.setRoot(SelectRoot(DAG.getRoot()));
548 DOUT << "===== Instruction selection ends:\n";
551 DAG.RemoveDeadNodes();
553 // Emit machine code to BB. This can change 'BB' to the last block being
555 ScheduleAndEmitDAG(DAG);
557 // If we are emitting FP stack code, scan the basic block to determine if this
558 // block defines any FP values. If so, put an FP_REG_KILL instruction before
559 // the terminator of the block.
561 // Note that FP stack instructions are used in all modes for long double,
562 // so we always need to do this check.
563 // Also note that it's possible for an FP stack register to be live across
564 // an instruction that produces multiple basic blocks (SSE CMOV) so we
565 // must check all the generated basic blocks.
567 // Scan all of the machine instructions in these MBBs, checking for FP
568 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
569 MachineFunction::iterator MBBI = FirstMBB;
570 MachineFunction::iterator EndMBB = BB; ++EndMBB;
571 for (; MBBI != EndMBB; ++MBBI) {
572 MachineBasicBlock *MBB = MBBI;
574 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
575 // before the return.
577 MachineBasicBlock::iterator EndI = MBB->end();
579 if (EndI->getDesc().isReturn())
583 bool ContainsFPCode = false;
584 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
585 !ContainsFPCode && I != E; ++I) {
586 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
587 const TargetRegisterClass *clas;
588 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
589 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
590 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
591 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
592 X86::RFP32RegisterClass ||
593 clas == X86::RFP64RegisterClass ||
594 clas == X86::RFP80RegisterClass)) {
595 ContainsFPCode = true;
601 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
602 // a copy of the input value in this block. In SSE mode, we only care about
604 if (!ContainsFPCode) {
605 // Final check, check LLVM BB's that are successors to the LLVM BB
606 // corresponding to BB for FP PHI nodes.
607 const BasicBlock *LLVMBB = BB->getBasicBlock();
609 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
610 !ContainsFPCode && SI != E; ++SI) {
611 for (BasicBlock::const_iterator II = SI->begin();
612 (PN = dyn_cast<PHINode>(II)); ++II) {
613 if (PN->getType()==Type::X86_FP80Ty ||
614 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
615 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
616 ContainsFPCode = true;
622 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
623 if (ContainsFPCode) {
624 BuildMI(*MBB, MBBI->getFirstTerminator(),
625 TM.getInstrInfo()->get(X86::FP_REG_KILL));
631 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
632 /// the main function.
633 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
634 MachineFrameInfo *MFI) {
635 const TargetInstrInfo *TII = TM.getInstrInfo();
636 if (Subtarget->isTargetCygMing())
637 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
640 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
641 // If this is main, emit special code for main.
642 MachineBasicBlock *BB = MF.begin();
643 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
644 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
647 /// MatchAddress - Add the specified node to the specified addressing mode,
648 /// returning true if it cannot be done. This just pattern matches for the
650 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
651 bool isRoot, unsigned Depth) {
654 return MatchAddressBase(N, AM, isRoot, Depth);
656 // RIP relative addressing: %rip + 32-bit displacement!
658 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
659 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
660 if (isInt32(AM.Disp + Val)) {
668 int id = N.Val->getNodeId();
669 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
671 switch (N.getOpcode()) {
673 case ISD::Constant: {
674 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
675 if (isInt32(AM.Disp + Val)) {
682 case X86ISD::Wrapper: {
683 bool is64Bit = Subtarget->is64Bit();
684 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
685 // Also, base and index reg must be 0 in order to use rip as base.
686 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
687 AM.Base.Reg.Val || AM.IndexReg.Val))
689 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
691 // If value is available in a register both base and index components have
692 // been picked, we can't fit the result available in the register in the
693 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
694 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
695 SDOperand N0 = N.getOperand(0);
696 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
697 GlobalValue *GV = G->getGlobal();
699 AM.Disp += G->getOffset();
700 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
701 Subtarget->isPICStyleRIPRel();
703 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
704 AM.CP = CP->getConstVal();
705 AM.Align = CP->getAlignment();
706 AM.Disp += CP->getOffset();
707 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
708 Subtarget->isPICStyleRIPRel();
710 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
711 AM.ES = S->getSymbol();
712 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
713 Subtarget->isPICStyleRIPRel();
715 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
716 AM.JT = J->getIndex();
717 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
718 Subtarget->isPICStyleRIPRel();
725 case ISD::FrameIndex:
726 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
727 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
728 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
734 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
738 unsigned Val = CN->getValue();
739 if (Val == 1 || Val == 2 || Val == 3) {
741 SDOperand ShVal = N.Val->getOperand(0);
743 // Okay, we know that we have a scale by now. However, if the scaled
744 // value is an add of something and a constant, we can fold the
745 // constant into the disp field here.
746 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
747 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
748 AM.IndexReg = ShVal.Val->getOperand(0);
749 ConstantSDNode *AddVal =
750 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
751 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
766 // A mul_lohi where we need the low part can be folded as a plain multiply.
767 if (N.ResNo != 0) break;
770 // X*[3,5,9] -> X+X*[2,4,8]
771 if (!AlreadySelected &&
772 AM.BaseType == X86ISelAddressMode::RegBase &&
773 AM.Base.Reg.Val == 0 &&
774 AM.IndexReg.Val == 0 &&
776 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
777 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
778 AM.Scale = unsigned(CN->getValue())-1;
780 SDOperand MulVal = N.Val->getOperand(0);
783 // Okay, we know that we have a scale by now. However, if the scaled
784 // value is an add of something and a constant, we can fold the
785 // constant into the disp field here.
786 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
787 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
788 Reg = MulVal.Val->getOperand(0);
789 ConstantSDNode *AddVal =
790 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
791 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
795 Reg = N.Val->getOperand(0);
797 Reg = N.Val->getOperand(0);
800 AM.IndexReg = AM.Base.Reg = Reg;
807 if (!AlreadySelected) {
808 X86ISelAddressMode Backup = AM;
809 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
810 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
813 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
814 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
821 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
822 if (AlreadySelected) break;
824 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
825 X86ISelAddressMode Backup = AM;
826 // Start with the LHS as an addr mode.
827 if (!MatchAddress(N.getOperand(0), AM, false) &&
828 // Address could not have picked a GV address for the displacement.
830 // On x86-64, the resultant disp must fit in 32-bits.
831 isInt32(AM.Disp + CN->getSignExtended()) &&
832 // Check to see if the LHS & C is zero.
833 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
834 AM.Disp += CN->getValue();
842 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
843 // allows us to fold the shift into this addressing mode.
844 if (AlreadySelected) break;
845 SDOperand Shift = N.getOperand(0);
846 if (Shift.getOpcode() != ISD::SHL) break;
848 // Scale must not be used already.
849 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
851 // Not when RIP is used as the base.
852 if (AM.isRIPRel) break;
854 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
855 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
856 if (!C1 || !C2) break;
858 // Not likely to be profitable if either the AND or SHIFT node has more
859 // than one use (unless all uses are for address computation). Besides,
860 // isel mechanism requires their node ids to be reused.
861 if (!N.hasOneUse() || !Shift.hasOneUse())
864 // Verify that the shift amount is something we can fold.
865 unsigned ShiftCst = C1->getValue();
866 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
869 // Get the new AND mask, this folds to a constant.
870 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
871 SDOperand(C2, 0), SDOperand(C1, 0));
872 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
873 Shift.getOperand(0), NewANDMask);
874 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
875 NewAND.Val->setNodeId(N.Val->getNodeId());
877 AM.Scale = 1 << ShiftCst;
878 AM.IndexReg = NewAND;
883 return MatchAddressBase(N, AM, isRoot, Depth);
886 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
887 /// specified addressing mode without any further recursion.
888 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
889 bool isRoot, unsigned Depth) {
890 // Is the base register already occupied?
891 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
892 // If so, check to see if the scale index register is set.
893 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
899 // Otherwise, we cannot select it.
903 // Default, generate it as a register.
904 AM.BaseType = X86ISelAddressMode::RegBase;
909 /// SelectAddr - returns true if it is able pattern match an addressing mode.
910 /// It returns the operands which make up the maximal addressing mode it can
911 /// match by reference.
912 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
913 SDOperand &Scale, SDOperand &Index,
915 X86ISelAddressMode AM;
916 if (MatchAddress(N, AM))
919 MVT::ValueType VT = N.getValueType();
920 if (AM.BaseType == X86ISelAddressMode::RegBase) {
921 if (!AM.Base.Reg.Val)
922 AM.Base.Reg = CurDAG->getRegister(0, VT);
925 if (!AM.IndexReg.Val)
926 AM.IndexReg = CurDAG->getRegister(0, VT);
928 getAddressOperands(AM, Base, Scale, Index, Disp);
932 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
934 static inline bool isZeroNode(SDOperand Elt) {
935 return ((isa<ConstantSDNode>(Elt) &&
936 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
937 (isa<ConstantFPSDNode>(Elt) &&
938 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
942 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
943 /// match a load whose top elements are either undef or zeros. The load flavor
944 /// is derived from the type of N, which is either v4f32 or v2f64.
945 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
946 SDOperand N, SDOperand &Base,
947 SDOperand &Scale, SDOperand &Index,
948 SDOperand &Disp, SDOperand &InChain,
949 SDOperand &OutChain) {
950 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
951 InChain = N.getOperand(0).getValue(1);
952 if (ISD::isNON_EXTLoad(InChain.Val) &&
953 InChain.getValue(0).hasOneUse() &&
955 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
956 LoadSDNode *LD = cast<LoadSDNode>(InChain);
957 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
959 OutChain = LD->getChain();
964 // Also handle the case where we explicitly require zeros in the top
965 // elements. This is a vector shuffle from the zero vector.
966 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
967 // Check to see if the top elements are all zeros (or bitcast of zeros).
968 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
969 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
970 N.getOperand(1).Val->hasOneUse() &&
971 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
972 N.getOperand(1).getOperand(0).hasOneUse()) {
973 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
975 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
976 SDOperand ShufMask = N.getOperand(2);
977 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
979 if (C->getValue() == VecWidth) {
980 for (unsigned i = 1; i != VecWidth; ++i) {
981 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
984 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
985 if (C->getValue() >= VecWidth) return false;
990 // Okay, this is a zero extending load. Fold it.
991 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
992 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
994 OutChain = LD->getChain();
995 InChain = SDOperand(LD, 1);
1003 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1004 /// mode it matches can be cost effectively emitted as an LEA instruction.
1005 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1006 SDOperand &Base, SDOperand &Scale,
1007 SDOperand &Index, SDOperand &Disp) {
1008 X86ISelAddressMode AM;
1009 if (MatchAddress(N, AM))
1012 MVT::ValueType VT = N.getValueType();
1013 unsigned Complexity = 0;
1014 if (AM.BaseType == X86ISelAddressMode::RegBase)
1015 if (AM.Base.Reg.Val)
1018 AM.Base.Reg = CurDAG->getRegister(0, VT);
1019 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1022 if (AM.IndexReg.Val)
1025 AM.IndexReg = CurDAG->getRegister(0, VT);
1027 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1032 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1033 // to a LEA. This is determined with some expermentation but is by no means
1034 // optimal (especially for code size consideration). LEA is nice because of
1035 // its three-address nature. Tweak the cost function again when we can run
1036 // convertToThreeAddress() at register allocation time.
1037 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1038 // For X86-64, we should always use lea to materialize RIP relative
1040 if (Subtarget->is64Bit())
1046 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1049 if (Complexity > 2) {
1050 getAddressOperands(AM, Base, Scale, Index, Disp);
1056 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1057 SDOperand &Base, SDOperand &Scale,
1058 SDOperand &Index, SDOperand &Disp) {
1059 if (ISD::isNON_EXTLoad(N.Val) &&
1061 CanBeFoldedBy(N.Val, P.Val, P.Val))
1062 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1066 /// getGlobalBaseReg - Output the instructions required to put the
1067 /// base address to use for accessing globals into a register.
1069 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1070 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1071 if (!GlobalBaseReg) {
1072 // Insert the set of GlobalBaseReg into the first MBB of the function
1073 MachineFunction *MF = BB->getParent();
1074 MachineBasicBlock &FirstMBB = MF->front();
1075 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1076 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1077 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1079 const TargetInstrInfo *TII = TM.getInstrInfo();
1080 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1081 // only used in JIT code emission as displacement to pc.
1082 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1084 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1085 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1086 if (TM.getRelocationModel() == Reloc::PIC_ &&
1087 Subtarget->isPICStyleGOT()) {
1088 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1089 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1090 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1096 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1099 static SDNode *FindCallStartFromCall(SDNode *Node) {
1100 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1101 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1102 "Node doesn't have a token chain argument!");
1103 return FindCallStartFromCall(Node->getOperand(0).Val);
1106 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1110 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1111 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1112 if (!Subtarget->is64Bit()) {
1115 switch (N0.getValueType()) {
1116 default: assert(0 && "Unknown truncate!");
1118 Opc = X86::MOV16to16_;
1122 Opc = X86::MOV32to32_;
1126 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1127 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1128 VT, N0, SRIdx, N0.getValue(1));
1132 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1135 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1137 default: assert(0 && "Unknown truncate!"); break;
1139 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1143 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1144 SDNode *Node = N.Val;
1145 MVT::ValueType NVT = Node->getValueType(0);
1147 unsigned Opcode = Node->getOpcode();
1150 DOUT << std::string(Indent, ' ') << "Selecting: ";
1151 DEBUG(Node->dump(CurDAG));
1156 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1158 DOUT << std::string(Indent-2, ' ') << "== ";
1159 DEBUG(Node->dump(CurDAG));
1163 return NULL; // Already selected.
1168 case X86ISD::GlobalBaseReg:
1169 return getGlobalBaseReg();
1171 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1172 case X86ISD::RET_FLAG:
1173 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1174 if (Amt->getSignExtended() != 0) break;
1176 // Match (X86retflag 0).
1177 SDOperand Chain = N.getOperand(0);
1178 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1180 SmallVector<SDOperand, 8> Ops0;
1181 AddToISelQueue(Chain);
1182 SDOperand InFlag(0, 0);
1184 InFlag = N.getOperand(N.getNumOperands()-1);
1185 AddToISelQueue(InFlag);
1187 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1189 AddToISelQueue(N.getOperand(i));
1190 Ops0.push_back(N.getOperand(i));
1192 Ops0.push_back(Chain);
1194 Ops0.push_back(InFlag);
1195 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1196 &Ops0[0], Ops0.size());
1201 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1202 // code and is matched first so to prevent it from being turned into
1204 // In 64-bit small code size mode, use LEA to take advantage of
1205 // RIP-relative addressing.
1206 if (TM.getCodeModel() != CodeModel::Small)
1208 MVT::ValueType PtrVT = TLI.getPointerTy();
1209 SDOperand N0 = N.getOperand(0);
1210 SDOperand N1 = N.getOperand(1);
1211 if (N.Val->getValueType(0) == PtrVT &&
1212 N0.getOpcode() == X86ISD::Wrapper &&
1213 N1.getOpcode() == ISD::Constant) {
1214 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1216 // TODO: handle ExternalSymbolSDNode.
1217 if (GlobalAddressSDNode *G =
1218 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1219 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1220 G->getOffset() + Offset);
1221 } else if (ConstantPoolSDNode *CP =
1222 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1223 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1225 CP->getOffset()+Offset);
1229 if (Subtarget->is64Bit()) {
1230 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1231 CurDAG->getRegister(0, PtrVT), C };
1232 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1234 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1238 // Other cases are handled by auto-generated code.
1242 case ISD::SMUL_LOHI:
1243 case ISD::UMUL_LOHI: {
1244 SDOperand N0 = Node->getOperand(0);
1245 SDOperand N1 = Node->getOperand(1);
1247 bool isSigned = Opcode == ISD::SMUL_LOHI;
1250 default: assert(0 && "Unsupported VT!");
1251 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1252 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1253 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1254 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1258 default: assert(0 && "Unsupported VT!");
1259 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1260 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1261 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1262 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1265 unsigned LoReg, HiReg;
1267 default: assert(0 && "Unsupported VT!");
1268 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1269 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1270 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1271 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1274 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1275 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1276 // multiplty is commmutative
1278 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1284 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1285 N0, SDOperand()).getValue(1);
1288 AddToISelQueue(N1.getOperand(0));
1289 AddToISelQueue(Tmp0);
1290 AddToISelQueue(Tmp1);
1291 AddToISelQueue(Tmp2);
1292 AddToISelQueue(Tmp3);
1293 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1295 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1296 InFlag = SDOperand(CNode, 1);
1297 // Update the chain.
1298 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1302 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1305 // Copy the low half of the result, if it is needed.
1306 if (!N.getValue(0).use_empty()) {
1307 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1308 LoReg, NVT, InFlag);
1309 InFlag = Result.getValue(2);
1310 ReplaceUses(N.getValue(0), Result);
1312 DOUT << std::string(Indent-2, ' ') << "=> ";
1313 DEBUG(Result.Val->dump(CurDAG));
1317 // Copy the high half of the result, if it is needed.
1318 if (!N.getValue(1).use_empty()) {
1320 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1321 // Prevent use of AH in a REX instruction by referencing AX instead.
1322 // Shift it down 8 bits.
1323 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1324 X86::AX, MVT::i16, InFlag);
1325 InFlag = Result.getValue(2);
1326 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1327 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1328 // Then truncate it down to i8.
1329 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1330 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1331 MVT::i8, Result, SRIdx), 0);
1333 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1334 HiReg, NVT, InFlag);
1335 InFlag = Result.getValue(2);
1337 ReplaceUses(N.getValue(1), Result);
1339 DOUT << std::string(Indent-2, ' ') << "=> ";
1340 DEBUG(Result.Val->dump(CurDAG));
1353 case ISD::UDIVREM: {
1354 SDOperand N0 = Node->getOperand(0);
1355 SDOperand N1 = Node->getOperand(1);
1357 bool isSigned = Opcode == ISD::SDIVREM;
1360 default: assert(0 && "Unsupported VT!");
1361 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1362 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1363 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1364 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1368 default: assert(0 && "Unsupported VT!");
1369 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1370 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1371 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1372 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1375 unsigned LoReg, HiReg;
1376 unsigned ClrOpcode, SExtOpcode;
1378 default: assert(0 && "Unsupported VT!");
1380 LoReg = X86::AL; HiReg = X86::AH;
1382 SExtOpcode = X86::CBW;
1385 LoReg = X86::AX; HiReg = X86::DX;
1386 ClrOpcode = X86::MOV16r0;
1387 SExtOpcode = X86::CWD;
1390 LoReg = X86::EAX; HiReg = X86::EDX;
1391 ClrOpcode = X86::MOV32r0;
1392 SExtOpcode = X86::CDQ;
1395 LoReg = X86::RAX; HiReg = X86::RDX;
1396 ClrOpcode = X86::MOV64r0;
1397 SExtOpcode = X86::CQO;
1401 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1402 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1405 if (NVT == MVT::i8 && !isSigned) {
1406 // Special case for div8, just use a move with zero extension to AX to
1407 // clear the upper 8 bits (AH).
1408 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1409 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1410 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1411 AddToISelQueue(N0.getOperand(0));
1412 AddToISelQueue(Tmp0);
1413 AddToISelQueue(Tmp1);
1414 AddToISelQueue(Tmp2);
1415 AddToISelQueue(Tmp3);
1417 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1419 Chain = Move.getValue(1);
1420 ReplaceUses(N0.getValue(1), Chain);
1424 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1425 Chain = CurDAG->getEntryNode();
1427 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1428 InFlag = Chain.getValue(1);
1432 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1433 LoReg, N0, SDOperand()).getValue(1);
1435 // Sign extend the low part into the high part.
1437 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1439 // Zero out the high part, effectively zero extending the input.
1440 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1441 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1442 ClrNode, InFlag).getValue(1);
1447 AddToISelQueue(N1.getOperand(0));
1448 AddToISelQueue(Tmp0);
1449 AddToISelQueue(Tmp1);
1450 AddToISelQueue(Tmp2);
1451 AddToISelQueue(Tmp3);
1452 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1454 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1455 InFlag = SDOperand(CNode, 1);
1456 // Update the chain.
1457 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1461 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1464 // Copy the division (low) result, if it is needed.
1465 if (!N.getValue(0).use_empty()) {
1466 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1467 LoReg, NVT, InFlag);
1468 InFlag = Result.getValue(2);
1469 ReplaceUses(N.getValue(0), Result);
1471 DOUT << std::string(Indent-2, ' ') << "=> ";
1472 DEBUG(Result.Val->dump(CurDAG));
1476 // Copy the remainder (high) result, if it is needed.
1477 if (!N.getValue(1).use_empty()) {
1479 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1480 // Prevent use of AH in a REX instruction by referencing AX instead.
1481 // Shift it down 8 bits.
1482 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1483 X86::AX, MVT::i16, InFlag);
1484 InFlag = Result.getValue(2);
1485 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1486 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1487 // Then truncate it down to i8.
1488 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1489 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1490 MVT::i8, Result, SRIdx), 0);
1492 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1493 HiReg, NVT, InFlag);
1494 InFlag = Result.getValue(2);
1496 ReplaceUses(N.getValue(1), Result);
1498 DOUT << std::string(Indent-2, ' ') << "=> ";
1499 DEBUG(Result.Val->dump(CurDAG));
1511 case ISD::ANY_EXTEND: {
1512 // Check if the type extended to supports subregs.
1516 SDOperand N0 = Node->getOperand(0);
1517 // Get the subregsiter index for the type to extend.
1518 MVT::ValueType N0VT = N0.getValueType();
1519 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1520 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1521 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1523 // If we don't have a subreg Idx, let generated ISel have a try.
1527 // If we have an index, generate an insert_subreg into undef.
1530 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
1531 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1532 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1533 NVT, Undef, N0, SRIdx);
1536 DOUT << std::string(Indent-2, ' ') << "=> ";
1537 DEBUG(ResNode->dump(CurDAG));
1544 case ISD::SIGN_EXTEND_INREG: {
1545 SDOperand N0 = Node->getOperand(0);
1548 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1549 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1553 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1554 else assert(0 && "Unknown sign_extend_inreg!");
1558 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1559 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1560 default: assert(0 && "Unknown sign_extend_inreg!");
1565 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1566 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1567 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1568 default: assert(0 && "Unknown sign_extend_inreg!");
1571 default: assert(0 && "Unknown sign_extend_inreg!");
1574 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1577 DOUT << std::string(Indent-2, ' ') << "=> ";
1578 DEBUG(TruncOp.Val->dump(CurDAG));
1580 DOUT << std::string(Indent-2, ' ') << "=> ";
1581 DEBUG(ResNode->dump(CurDAG));
1589 case ISD::TRUNCATE: {
1590 SDOperand Input = Node->getOperand(0);
1591 AddToISelQueue(Node->getOperand(0));
1592 SDNode *ResNode = getTruncate(Input, NVT);
1595 DOUT << std::string(Indent-2, ' ') << "=> ";
1596 DEBUG(ResNode->dump(CurDAG));
1605 SDNode *ResNode = SelectCode(N);
1608 DOUT << std::string(Indent-2, ' ') << "=> ";
1609 if (ResNode == NULL || ResNode == N.Val)
1610 DEBUG(N.Val->dump(CurDAG));
1612 DEBUG(ResNode->dump(CurDAG));
1620 bool X86DAGToDAGISel::
1621 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1622 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1623 SDOperand Op0, Op1, Op2, Op3;
1624 switch (ConstraintCode) {
1625 case 'o': // offsetable ??
1626 case 'v': // not offsetable ??
1627 default: return true;
1629 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1634 OutOps.push_back(Op0);
1635 OutOps.push_back(Op1);
1636 OutOps.push_back(Op2);
1637 OutOps.push_back(Op3);
1638 AddToISelQueue(Op0);
1639 AddToISelQueue(Op1);
1640 AddToISelQueue(Op2);
1641 AddToISelQueue(Op3);
1645 /// createX86ISelDag - This pass converts a legalized DAG into a
1646 /// X86-specific DAG, ready for instruction scheduling.
1648 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1649 return new X86DAGToDAGISel(TM, Fast);