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/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
45 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
46 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 as base?
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 /// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
228 static SDNode *findFlagUse(SDNode *N) {
229 unsigned FlagResNo = N->getNumValues()-1;
230 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
231 SDNode *User = I->getUser();
232 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
233 SDOperand Op = User->getOperand(i);
234 if (Op.Val == N && Op.ResNo == FlagResNo)
241 /// findNonImmUse - Return true by reference in "found" if "Use" is an
242 /// non-immediate use of "Def". This function recursively traversing
243 /// up the operand chain ignoring certain nodes.
244 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
245 SDNode *Root, SDNode *Skip, bool &found,
246 SmallPtrSet<SDNode*, 16> &Visited) {
248 Use->getNodeId() > Def->getNodeId() ||
249 !Visited.insert(Use))
252 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
253 SDNode *N = Use->getOperand(i).Val;
258 continue; // We are not looking for immediate use.
260 // Must be a chain reading node where it is possible to reach its own
261 // chain operand through a path started from another operand.
262 assert(Use->getOpcode() == ISD::STORE ||
263 Use->getOpcode() == X86ISD::CMP ||
264 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
265 Use->getOpcode() == ISD::INTRINSIC_VOID);
272 // Traverse up the operand chain.
273 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
277 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
278 /// be reached. Return true if that's the case. However, ignore direct uses
279 /// by ImmedUse (which would be U in the example illustrated in
280 /// CanBeFoldedBy) and by Root (which can happen in the store case).
281 /// FIXME: to be really generic, we should allow direct use by any node
282 /// that is being folded. But realisticly since we only fold loads which
283 /// have one non-chain use, we only need to watch out for load/op/store
284 /// and load/op/cmp case where the root (store / cmp) may reach the load via
285 /// its chain operand.
286 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
287 SDNode *Skip = NULL) {
288 SmallPtrSet<SDNode*, 16> Visited;
290 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
295 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
296 if (FastISel) return false;
298 // If U use can somehow reach N through another path then U can't fold N or
299 // it will create a cycle. e.g. In the following diagram, U can reach N
300 // through X. If N is folded into into U, then X is both a predecessor and
311 if (isNonImmUse(Root, N, U))
314 // If U produces a flag, then it gets (even more) interesting. Since it
315 // would have been "glued" together with its flag use, we need to check if
328 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
329 // NU), then TF is a predecessor of FU and a successor of NU. But since
330 // NU and FU are flagged together, this effectively creates a cycle.
331 bool HasFlagUse = false;
332 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
333 while ((VT == MVT::Flag && !Root->use_empty())) {
334 SDNode *FU = findFlagUse(Root);
341 VT = Root->getValueType(Root->getNumValues()-1);
345 return !isNonImmUse(Root, N, Root, U);
349 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
350 /// and move load below the TokenFactor. Replace store's chain operand with
351 /// load's chain result.
352 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
353 SDOperand Store, SDOperand TF) {
354 std::vector<SDOperand> Ops;
355 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
356 if (Load.Val == TF.Val->getOperand(i).Val)
357 Ops.push_back(Load.Val->getOperand(0));
359 Ops.push_back(TF.Val->getOperand(i));
360 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
361 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
362 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
363 Store.getOperand(2), Store.getOperand(3));
366 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
367 /// This is only run if not in -fast mode (aka -O0).
368 /// This allows the instruction selector to pick more read-modify-write
369 /// instructions. This is a common case:
379 /// [TokenFactor] [Op]
386 /// The fact the store's chain operand != load's chain will prevent the
387 /// (store (op (load))) instruction from being selected. We can transform it to:
406 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
407 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
408 E = DAG.allnodes_end(); I != E; ++I) {
409 if (!ISD::isNON_TRUNCStore(I))
411 SDOperand Chain = I->getOperand(0);
412 if (Chain.Val->getOpcode() != ISD::TokenFactor)
415 SDOperand N1 = I->getOperand(1);
416 SDOperand N2 = I->getOperand(2);
417 if (MVT::isFloatingPoint(N1.getValueType()) ||
418 MVT::isVector(N1.getValueType()) ||
424 unsigned Opcode = N1.Val->getOpcode();
433 SDOperand N10 = N1.getOperand(0);
434 SDOperand N11 = N1.getOperand(1);
435 if (ISD::isNON_EXTLoad(N10.Val))
437 else if (ISD::isNON_EXTLoad(N11.Val)) {
441 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
442 (N10.getOperand(1) == N2) &&
443 (N10.Val->getValueType(0) == N1.getValueType());
458 SDOperand N10 = N1.getOperand(0);
459 if (ISD::isNON_EXTLoad(N10.Val))
460 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
461 (N10.getOperand(1) == N2) &&
462 (N10.Val->getValueType(0) == N1.getValueType());
470 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
477 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
478 /// nodes that target the FP stack to be store and load to the stack. This is a
479 /// gross hack. We would like to simply mark these as being illegal, but when
480 /// we do that, legalize produces these when it expands calls, then expands
481 /// these in the same legalize pass. We would like dag combine to be able to
482 /// hack on these between the call expansion and the node legalization. As such
483 /// this pass basically does "really late" legalization of these inline with the
485 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
486 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
487 E = DAG.allnodes_end(); I != E; ) {
488 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
489 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
492 // If the source and destination are SSE registers, then this is a legal
493 // conversion that should not be lowered.
494 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
495 MVT::ValueType DstVT = N->getValueType(0);
496 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
497 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
498 if (SrcIsSSE && DstIsSSE)
501 if (!SrcIsSSE && !DstIsSSE) {
502 // If this is an FPStack extension, it is a noop.
503 if (N->getOpcode() == ISD::FP_EXTEND)
505 // If this is a value-preserving FPStack truncation, it is a noop.
506 if (N->getConstantOperandVal(1))
510 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
511 // FPStack has extload and truncstore. SSE can fold direct loads into other
512 // operations. Based on this, decide what we want to do.
513 MVT::ValueType MemVT;
514 if (N->getOpcode() == ISD::FP_ROUND)
515 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
517 MemVT = SrcIsSSE ? SrcVT : DstVT;
519 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
521 // FIXME: optimize the case where the src/dest is a load or store?
522 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
523 MemTmp, NULL, 0, MemVT);
524 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
527 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
528 // extload we created. This will cause general havok on the dag because
529 // anything below the conversion could be folded into other existing nodes.
530 // To avoid invalidating 'I', back it up to the convert node.
532 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
534 // Now that we did that, the node is dead. Increment the iterator to the
535 // next node to process, then delete N.
541 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
542 /// when it has created a SelectionDAG for us to codegen.
543 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
545 MachineFunction::iterator FirstMBB = BB;
548 PreprocessForRMW(DAG);
550 // FIXME: This should only happen when not -fast.
551 PreprocessForFPConvert(DAG);
553 // Codegen the basic block.
555 DOUT << "===== Instruction selection begins:\n";
558 DAG.setRoot(SelectRoot(DAG.getRoot()));
560 DOUT << "===== Instruction selection ends:\n";
563 DAG.RemoveDeadNodes();
565 // Emit machine code to BB. This can change 'BB' to the last block being
567 ScheduleAndEmitDAG(DAG);
569 // If we are emitting FP stack code, scan the basic block to determine if this
570 // block defines any FP values. If so, put an FP_REG_KILL instruction before
571 // the terminator of the block.
573 // Note that FP stack instructions are used in all modes for long double,
574 // so we always need to do this check.
575 // Also note that it's possible for an FP stack register to be live across
576 // an instruction that produces multiple basic blocks (SSE CMOV) so we
577 // must check all the generated basic blocks.
579 // Scan all of the machine instructions in these MBBs, checking for FP
580 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
581 MachineFunction::iterator MBBI = FirstMBB;
582 MachineFunction::iterator EndMBB = BB; ++EndMBB;
583 for (; MBBI != EndMBB; ++MBBI) {
584 MachineBasicBlock *MBB = MBBI;
586 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
587 // before the return.
589 MachineBasicBlock::iterator EndI = MBB->end();
591 if (EndI->getDesc().isReturn())
595 bool ContainsFPCode = false;
596 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
597 !ContainsFPCode && I != E; ++I) {
598 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
599 const TargetRegisterClass *clas;
600 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
601 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
602 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
603 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
604 X86::RFP32RegisterClass ||
605 clas == X86::RFP64RegisterClass ||
606 clas == X86::RFP80RegisterClass)) {
607 ContainsFPCode = true;
613 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
614 // a copy of the input value in this block. In SSE mode, we only care about
616 if (!ContainsFPCode) {
617 // Final check, check LLVM BB's that are successors to the LLVM BB
618 // corresponding to BB for FP PHI nodes.
619 const BasicBlock *LLVMBB = BB->getBasicBlock();
621 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
622 !ContainsFPCode && SI != E; ++SI) {
623 for (BasicBlock::const_iterator II = SI->begin();
624 (PN = dyn_cast<PHINode>(II)); ++II) {
625 if (PN->getType()==Type::X86_FP80Ty ||
626 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
627 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
628 ContainsFPCode = true;
634 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
635 if (ContainsFPCode) {
636 BuildMI(*MBB, MBBI->getFirstTerminator(),
637 TM.getInstrInfo()->get(X86::FP_REG_KILL));
643 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
644 /// the main function.
645 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
646 MachineFrameInfo *MFI) {
647 const TargetInstrInfo *TII = TM.getInstrInfo();
648 if (Subtarget->isTargetCygMing())
649 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
652 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
653 // If this is main, emit special code for main.
654 MachineBasicBlock *BB = MF.begin();
655 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
656 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
659 /// MatchAddress - Add the specified node to the specified addressing mode,
660 /// returning true if it cannot be done. This just pattern matches for the
662 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
663 bool isRoot, unsigned Depth) {
666 return MatchAddressBase(N, AM, isRoot, Depth);
668 // RIP relative addressing: %rip + 32-bit displacement!
670 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
671 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
672 if (isInt32(AM.Disp + Val)) {
680 int id = N.Val->getNodeId();
681 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
683 switch (N.getOpcode()) {
685 case ISD::Constant: {
686 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
687 if (isInt32(AM.Disp + Val)) {
694 case X86ISD::Wrapper: {
695 bool is64Bit = Subtarget->is64Bit();
696 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
697 // Also, base and index reg must be 0 in order to use rip as base.
698 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
699 AM.Base.Reg.Val || AM.IndexReg.Val))
701 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
703 // If value is available in a register both base and index components have
704 // been picked, we can't fit the result available in the register in the
705 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
706 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
707 SDOperand N0 = N.getOperand(0);
708 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
709 GlobalValue *GV = G->getGlobal();
711 AM.Disp += G->getOffset();
712 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
713 Subtarget->isPICStyleRIPRel();
715 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
716 AM.CP = CP->getConstVal();
717 AM.Align = CP->getAlignment();
718 AM.Disp += CP->getOffset();
719 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
720 Subtarget->isPICStyleRIPRel();
722 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
723 AM.ES = S->getSymbol();
724 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
725 Subtarget->isPICStyleRIPRel();
727 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
728 AM.JT = J->getIndex();
729 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
730 Subtarget->isPICStyleRIPRel();
737 case ISD::FrameIndex:
738 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
739 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
740 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
746 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
749 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
750 unsigned Val = CN->getValue();
751 if (Val == 1 || Val == 2 || Val == 3) {
753 SDOperand ShVal = N.Val->getOperand(0);
755 // Okay, we know that we have a scale by now. However, if the scaled
756 // value is an add of something and a constant, we can fold the
757 // constant into the disp field here.
758 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
759 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
760 AM.IndexReg = ShVal.Val->getOperand(0);
761 ConstantSDNode *AddVal =
762 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
763 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
778 // A mul_lohi where we need the low part can be folded as a plain multiply.
779 if (N.ResNo != 0) break;
782 // X*[3,5,9] -> X+X*[2,4,8]
783 if (!AlreadySelected &&
784 AM.BaseType == X86ISelAddressMode::RegBase &&
785 AM.Base.Reg.Val == 0 &&
786 AM.IndexReg.Val == 0 &&
788 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
789 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
790 AM.Scale = unsigned(CN->getValue())-1;
792 SDOperand MulVal = N.Val->getOperand(0);
795 // Okay, we know that we have a scale by now. However, if the scaled
796 // value is an add of something and a constant, we can fold the
797 // constant into the disp field here.
798 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
799 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
800 Reg = MulVal.Val->getOperand(0);
801 ConstantSDNode *AddVal =
802 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
803 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
807 Reg = N.Val->getOperand(0);
809 Reg = N.Val->getOperand(0);
812 AM.IndexReg = AM.Base.Reg = Reg;
819 if (!AlreadySelected) {
820 X86ISelAddressMode Backup = AM;
821 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
822 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
825 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
826 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
833 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
834 if (AlreadySelected) break;
836 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
837 X86ISelAddressMode Backup = AM;
838 // Start with the LHS as an addr mode.
839 if (!MatchAddress(N.getOperand(0), AM, false) &&
840 // Address could not have picked a GV address for the displacement.
842 // On x86-64, the resultant disp must fit in 32-bits.
843 isInt32(AM.Disp + CN->getSignExtended()) &&
844 // Check to see if the LHS & C is zero.
845 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
846 AM.Disp += CN->getValue();
854 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
855 // allows us to fold the shift into this addressing mode.
856 if (AlreadySelected) break;
857 SDOperand Shift = N.getOperand(0);
858 if (Shift.getOpcode() != ISD::SHL) break;
860 // Scale must not be used already.
861 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
863 // Not when RIP is used as the base.
864 if (AM.isRIPRel) break;
866 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
867 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
868 if (!C1 || !C2) break;
870 // Not likely to be profitable if either the AND or SHIFT node has more
871 // than one use (unless all uses are for address computation). Besides,
872 // isel mechanism requires their node ids to be reused.
873 if (!N.hasOneUse() || !Shift.hasOneUse())
876 // Verify that the shift amount is something we can fold.
877 unsigned ShiftCst = C1->getValue();
878 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
881 // Get the new AND mask, this folds to a constant.
882 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
883 SDOperand(C2, 0), SDOperand(C1, 0));
884 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
885 Shift.getOperand(0), NewANDMask);
886 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
887 NewAND.Val->setNodeId(N.Val->getNodeId());
889 AM.Scale = 1 << ShiftCst;
890 AM.IndexReg = NewAND;
895 return MatchAddressBase(N, AM, isRoot, Depth);
898 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
899 /// specified addressing mode without any further recursion.
900 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
901 bool isRoot, unsigned Depth) {
902 // Is the base register already occupied?
903 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
904 // If so, check to see if the scale index register is set.
905 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
911 // Otherwise, we cannot select it.
915 // Default, generate it as a register.
916 AM.BaseType = X86ISelAddressMode::RegBase;
921 /// SelectAddr - returns true if it is able pattern match an addressing mode.
922 /// It returns the operands which make up the maximal addressing mode it can
923 /// match by reference.
924 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
925 SDOperand &Scale, SDOperand &Index,
927 X86ISelAddressMode AM;
928 if (MatchAddress(N, AM))
931 MVT::ValueType VT = N.getValueType();
932 if (AM.BaseType == X86ISelAddressMode::RegBase) {
933 if (!AM.Base.Reg.Val)
934 AM.Base.Reg = CurDAG->getRegister(0, VT);
937 if (!AM.IndexReg.Val)
938 AM.IndexReg = CurDAG->getRegister(0, VT);
940 getAddressOperands(AM, Base, Scale, Index, Disp);
944 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
946 static inline bool isZeroNode(SDOperand Elt) {
947 return ((isa<ConstantSDNode>(Elt) &&
948 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
949 (isa<ConstantFPSDNode>(Elt) &&
950 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
954 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
955 /// match a load whose top elements are either undef or zeros. The load flavor
956 /// is derived from the type of N, which is either v4f32 or v2f64.
957 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
958 SDOperand N, SDOperand &Base,
959 SDOperand &Scale, SDOperand &Index,
960 SDOperand &Disp, SDOperand &InChain,
961 SDOperand &OutChain) {
962 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
963 InChain = N.getOperand(0).getValue(1);
964 if (ISD::isNON_EXTLoad(InChain.Val) &&
965 InChain.getValue(0).hasOneUse() &&
967 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
968 LoadSDNode *LD = cast<LoadSDNode>(InChain);
969 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
971 OutChain = LD->getChain();
976 // Also handle the case where we explicitly require zeros in the top
977 // elements. This is a vector shuffle from the zero vector.
978 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
979 // Check to see if the top elements are all zeros (or bitcast of zeros).
980 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
981 N.getOperand(0).Val->hasOneUse() &&
982 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
983 N.getOperand(0).getOperand(0).hasOneUse()) {
984 // Okay, this is a zero extending load. Fold it.
985 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
986 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
988 OutChain = LD->getChain();
989 InChain = SDOperand(LD, 1);
996 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
997 /// mode it matches can be cost effectively emitted as an LEA instruction.
998 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
999 SDOperand &Base, SDOperand &Scale,
1000 SDOperand &Index, SDOperand &Disp) {
1001 X86ISelAddressMode AM;
1002 if (MatchAddress(N, AM))
1005 MVT::ValueType VT = N.getValueType();
1006 unsigned Complexity = 0;
1007 if (AM.BaseType == X86ISelAddressMode::RegBase)
1008 if (AM.Base.Reg.Val)
1011 AM.Base.Reg = CurDAG->getRegister(0, VT);
1012 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1015 if (AM.IndexReg.Val)
1018 AM.IndexReg = CurDAG->getRegister(0, VT);
1020 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1025 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1026 // to a LEA. This is determined with some expermentation but is by no means
1027 // optimal (especially for code size consideration). LEA is nice because of
1028 // its three-address nature. Tweak the cost function again when we can run
1029 // convertToThreeAddress() at register allocation time.
1030 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1031 // For X86-64, we should always use lea to materialize RIP relative
1033 if (Subtarget->is64Bit())
1039 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1042 if (Complexity > 2) {
1043 getAddressOperands(AM, Base, Scale, Index, Disp);
1049 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1050 SDOperand &Base, SDOperand &Scale,
1051 SDOperand &Index, SDOperand &Disp) {
1052 if (ISD::isNON_EXTLoad(N.Val) &&
1054 CanBeFoldedBy(N.Val, P.Val, P.Val))
1055 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1059 /// getGlobalBaseReg - Output the instructions required to put the
1060 /// base address to use for accessing globals into a register.
1062 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1063 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1064 if (!GlobalBaseReg) {
1065 // Insert the set of GlobalBaseReg into the first MBB of the function
1066 MachineFunction *MF = BB->getParent();
1067 MachineBasicBlock &FirstMBB = MF->front();
1068 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1069 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1070 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1072 const TargetInstrInfo *TII = TM.getInstrInfo();
1073 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1074 // only used in JIT code emission as displacement to pc.
1075 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1077 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1078 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1079 if (TM.getRelocationModel() == Reloc::PIC_ &&
1080 Subtarget->isPICStyleGOT()) {
1081 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1082 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1083 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1089 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1092 static SDNode *FindCallStartFromCall(SDNode *Node) {
1093 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1094 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1095 "Node doesn't have a token chain argument!");
1096 return FindCallStartFromCall(Node->getOperand(0).Val);
1099 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1103 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1104 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1105 if (!Subtarget->is64Bit()) {
1108 switch (N0.getValueType()) {
1109 default: assert(0 && "Unknown truncate!");
1111 Opc = X86::MOV16to16_;
1115 Opc = X86::MOV32to32_;
1119 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1120 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1121 VT, N0, SRIdx, N0.getValue(1));
1125 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1128 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1130 default: assert(0 && "Unknown truncate!"); break;
1132 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1136 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1137 SDNode *Node = N.Val;
1138 MVT::ValueType NVT = Node->getValueType(0);
1140 unsigned Opcode = Node->getOpcode();
1143 DOUT << std::string(Indent, ' ') << "Selecting: ";
1144 DEBUG(Node->dump(CurDAG));
1149 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1151 DOUT << std::string(Indent-2, ' ') << "== ";
1152 DEBUG(Node->dump(CurDAG));
1156 return NULL; // Already selected.
1161 case X86ISD::GlobalBaseReg:
1162 return getGlobalBaseReg();
1164 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1165 case X86ISD::RET_FLAG:
1166 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1167 if (Amt->getSignExtended() != 0) break;
1169 // Match (X86retflag 0).
1170 SDOperand Chain = N.getOperand(0);
1171 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1173 SmallVector<SDOperand, 8> Ops0;
1174 AddToISelQueue(Chain);
1175 SDOperand InFlag(0, 0);
1177 InFlag = N.getOperand(N.getNumOperands()-1);
1178 AddToISelQueue(InFlag);
1180 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1182 AddToISelQueue(N.getOperand(i));
1183 Ops0.push_back(N.getOperand(i));
1185 Ops0.push_back(Chain);
1187 Ops0.push_back(InFlag);
1188 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1189 &Ops0[0], Ops0.size());
1194 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1195 // code and is matched first so to prevent it from being turned into
1197 // In 64-bit small code size mode, use LEA to take advantage of
1198 // RIP-relative addressing.
1199 if (TM.getCodeModel() != CodeModel::Small)
1201 MVT::ValueType PtrVT = TLI.getPointerTy();
1202 SDOperand N0 = N.getOperand(0);
1203 SDOperand N1 = N.getOperand(1);
1204 if (N.Val->getValueType(0) == PtrVT &&
1205 N0.getOpcode() == X86ISD::Wrapper &&
1206 N1.getOpcode() == ISD::Constant) {
1207 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1209 // TODO: handle ExternalSymbolSDNode.
1210 if (GlobalAddressSDNode *G =
1211 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1212 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1213 G->getOffset() + Offset);
1214 } else if (ConstantPoolSDNode *CP =
1215 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1216 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1218 CP->getOffset()+Offset);
1222 if (Subtarget->is64Bit()) {
1223 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1224 CurDAG->getRegister(0, PtrVT), C };
1225 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1227 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1231 // Other cases are handled by auto-generated code.
1235 case ISD::SMUL_LOHI:
1236 case ISD::UMUL_LOHI: {
1237 SDOperand N0 = Node->getOperand(0);
1238 SDOperand N1 = Node->getOperand(1);
1240 bool isSigned = Opcode == ISD::SMUL_LOHI;
1243 default: assert(0 && "Unsupported VT!");
1244 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1245 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1246 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1247 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1251 default: assert(0 && "Unsupported VT!");
1252 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1253 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1254 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1255 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1258 unsigned LoReg, HiReg;
1260 default: assert(0 && "Unsupported VT!");
1261 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1262 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1263 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1264 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1267 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1268 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1269 // multiplty is commmutative
1271 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1277 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1278 N0, SDOperand()).getValue(1);
1281 AddToISelQueue(N1.getOperand(0));
1282 AddToISelQueue(Tmp0);
1283 AddToISelQueue(Tmp1);
1284 AddToISelQueue(Tmp2);
1285 AddToISelQueue(Tmp3);
1286 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1288 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1289 InFlag = SDOperand(CNode, 1);
1290 // Update the chain.
1291 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1295 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1298 // Copy the low half of the result, if it is needed.
1299 if (!N.getValue(0).use_empty()) {
1300 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1301 LoReg, NVT, InFlag);
1302 InFlag = Result.getValue(2);
1303 ReplaceUses(N.getValue(0), Result);
1305 DOUT << std::string(Indent-2, ' ') << "=> ";
1306 DEBUG(Result.Val->dump(CurDAG));
1310 // Copy the high half of the result, if it is needed.
1311 if (!N.getValue(1).use_empty()) {
1313 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1314 // Prevent use of AH in a REX instruction by referencing AX instead.
1315 // Shift it down 8 bits.
1316 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1317 X86::AX, MVT::i16, InFlag);
1318 InFlag = Result.getValue(2);
1319 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1320 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1321 // Then truncate it down to i8.
1322 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1323 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1324 MVT::i8, Result, SRIdx), 0);
1326 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1327 HiReg, NVT, InFlag);
1328 InFlag = Result.getValue(2);
1330 ReplaceUses(N.getValue(1), Result);
1332 DOUT << std::string(Indent-2, ' ') << "=> ";
1333 DEBUG(Result.Val->dump(CurDAG));
1346 case ISD::UDIVREM: {
1347 SDOperand N0 = Node->getOperand(0);
1348 SDOperand N1 = Node->getOperand(1);
1350 bool isSigned = Opcode == ISD::SDIVREM;
1353 default: assert(0 && "Unsupported VT!");
1354 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1355 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1356 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1357 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1361 default: assert(0 && "Unsupported VT!");
1362 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1363 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1364 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1365 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1368 unsigned LoReg, HiReg;
1369 unsigned ClrOpcode, SExtOpcode;
1371 default: assert(0 && "Unsupported VT!");
1373 LoReg = X86::AL; HiReg = X86::AH;
1375 SExtOpcode = X86::CBW;
1378 LoReg = X86::AX; HiReg = X86::DX;
1379 ClrOpcode = X86::MOV16r0;
1380 SExtOpcode = X86::CWD;
1383 LoReg = X86::EAX; HiReg = X86::EDX;
1384 ClrOpcode = X86::MOV32r0;
1385 SExtOpcode = X86::CDQ;
1388 LoReg = X86::RAX; HiReg = X86::RDX;
1389 ClrOpcode = X86::MOV64r0;
1390 SExtOpcode = X86::CQO;
1394 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1395 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1398 if (NVT == MVT::i8 && !isSigned) {
1399 // Special case for div8, just use a move with zero extension to AX to
1400 // clear the upper 8 bits (AH).
1401 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1402 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1403 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1404 AddToISelQueue(N0.getOperand(0));
1405 AddToISelQueue(Tmp0);
1406 AddToISelQueue(Tmp1);
1407 AddToISelQueue(Tmp2);
1408 AddToISelQueue(Tmp3);
1410 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1412 Chain = Move.getValue(1);
1413 ReplaceUses(N0.getValue(1), Chain);
1417 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1418 Chain = CurDAG->getEntryNode();
1420 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1421 InFlag = Chain.getValue(1);
1425 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1426 LoReg, N0, SDOperand()).getValue(1);
1428 // Sign extend the low part into the high part.
1430 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1432 // Zero out the high part, effectively zero extending the input.
1433 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1434 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1435 ClrNode, InFlag).getValue(1);
1440 AddToISelQueue(N1.getOperand(0));
1441 AddToISelQueue(Tmp0);
1442 AddToISelQueue(Tmp1);
1443 AddToISelQueue(Tmp2);
1444 AddToISelQueue(Tmp3);
1445 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1447 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1448 InFlag = SDOperand(CNode, 1);
1449 // Update the chain.
1450 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1454 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1457 // Copy the division (low) result, if it is needed.
1458 if (!N.getValue(0).use_empty()) {
1459 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1460 LoReg, NVT, InFlag);
1461 InFlag = Result.getValue(2);
1462 ReplaceUses(N.getValue(0), Result);
1464 DOUT << std::string(Indent-2, ' ') << "=> ";
1465 DEBUG(Result.Val->dump(CurDAG));
1469 // Copy the remainder (high) result, if it is needed.
1470 if (!N.getValue(1).use_empty()) {
1472 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1473 // Prevent use of AH in a REX instruction by referencing AX instead.
1474 // Shift it down 8 bits.
1475 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1476 X86::AX, MVT::i16, InFlag);
1477 InFlag = Result.getValue(2);
1478 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1479 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1480 // Then truncate it down to i8.
1481 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1482 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1483 MVT::i8, Result, SRIdx), 0);
1485 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1486 HiReg, NVT, InFlag);
1487 InFlag = Result.getValue(2);
1489 ReplaceUses(N.getValue(1), Result);
1491 DOUT << std::string(Indent-2, ' ') << "=> ";
1492 DEBUG(Result.Val->dump(CurDAG));
1504 case ISD::ANY_EXTEND: {
1505 // Check if the type extended to supports subregs.
1509 SDOperand N0 = Node->getOperand(0);
1510 // Get the subregsiter index for the type to extend.
1511 MVT::ValueType N0VT = N0.getValueType();
1512 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1513 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1514 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1516 // If we don't have a subreg Idx, let generated ISel have a try.
1520 // If we have an index, generate an insert_subreg into undef.
1523 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
1524 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1525 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1526 NVT, Undef, N0, SRIdx);
1529 DOUT << std::string(Indent-2, ' ') << "=> ";
1530 DEBUG(ResNode->dump(CurDAG));
1537 case ISD::SIGN_EXTEND_INREG: {
1538 SDOperand N0 = Node->getOperand(0);
1541 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1542 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1546 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1547 else assert(0 && "Unknown sign_extend_inreg!");
1551 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1552 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1553 default: assert(0 && "Unknown sign_extend_inreg!");
1558 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1559 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1560 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1561 default: assert(0 && "Unknown sign_extend_inreg!");
1564 default: assert(0 && "Unknown sign_extend_inreg!");
1567 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1570 DOUT << std::string(Indent-2, ' ') << "=> ";
1571 DEBUG(TruncOp.Val->dump(CurDAG));
1573 DOUT << std::string(Indent-2, ' ') << "=> ";
1574 DEBUG(ResNode->dump(CurDAG));
1582 case ISD::TRUNCATE: {
1583 SDOperand Input = Node->getOperand(0);
1584 AddToISelQueue(Node->getOperand(0));
1585 SDNode *ResNode = getTruncate(Input, NVT);
1588 DOUT << std::string(Indent-2, ' ') << "=> ";
1589 DEBUG(ResNode->dump(CurDAG));
1598 SDNode *ResNode = SelectCode(N);
1601 DOUT << std::string(Indent-2, ' ') << "=> ";
1602 if (ResNode == NULL || ResNode == N.Val)
1603 DEBUG(N.Val->dump(CurDAG));
1605 DEBUG(ResNode->dump(CurDAG));
1613 bool X86DAGToDAGISel::
1614 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1615 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1616 SDOperand Op0, Op1, Op2, Op3;
1617 switch (ConstraintCode) {
1618 case 'o': // offsetable ??
1619 case 'v': // not offsetable ??
1620 default: return true;
1622 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1627 OutOps.push_back(Op0);
1628 OutOps.push_back(Op1);
1629 OutOps.push_back(Op2);
1630 OutOps.push_back(Op3);
1631 AddToISelQueue(Op0);
1632 AddToISelQueue(Op1);
1633 AddToISelQueue(Op2);
1634 AddToISelQueue(Op3);
1638 /// createX86ISelDag - This pass converts a legalized DAG into a
1639 /// X86-specific DAG, ready for instruction scheduling.
1641 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1642 return new X86DAGToDAGISel(TM, Fast);