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 assert(Use->getOpcode() == ISD::STORE ||
261 Use->getOpcode() == X86ISD::CMP ||
262 Use->getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
263 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
264 Use->getOpcode() == ISD::INTRINSIC_VOID);
271 // Traverse up the operand chain.
272 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
276 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
277 /// be reached. Return true if that's the case. However, ignore direct uses
278 /// by ImmedUse (which would be U in the example illustrated in
279 /// CanBeFoldedBy) and by Root (which can happen in the store case).
280 /// FIXME: to be really generic, we should allow direct use by any node
281 /// that is being folded. But realisticly since we only fold loads which
282 /// have one non-chain use, we only need to watch out for load/op/store
283 /// and load/op/cmp case where the root (store / cmp) may reach the load via
284 /// its chain operand.
285 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
286 SDNode *Skip = NULL) {
287 SmallPtrSet<SDNode*, 16> Visited;
289 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
294 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
295 if (FastISel) return false;
297 // If U use can somehow reach N through another path then U can't fold N or
298 // it will create a cycle. e.g. In the following diagram, U can reach N
299 // through X. If N is folded into into U, then X is both a predecessor and
310 if (isNonImmUse(Root, N, U))
313 // If U produces a flag, then it gets (even more) interesting. Since it
314 // would have been "glued" together with its flag use, we need to check if
327 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
328 // NU), then TF is a predecessor of FU and a successor of NU. But since
329 // NU and FU are flagged together, this effectively creates a cycle.
330 bool HasFlagUse = false;
331 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
332 while ((VT == MVT::Flag && !Root->use_empty())) {
333 SDNode *FU = findFlagUse(Root);
340 VT = Root->getValueType(Root->getNumValues()-1);
344 return !isNonImmUse(Root, N, Root, U);
348 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
349 /// and move load below the TokenFactor. Replace store's chain operand with
350 /// load's chain result.
351 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
352 SDOperand Store, SDOperand TF) {
353 std::vector<SDOperand> Ops;
354 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
355 if (Load.Val == TF.Val->getOperand(i).Val)
356 Ops.push_back(Load.Val->getOperand(0));
358 Ops.push_back(TF.Val->getOperand(i));
359 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
360 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
361 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
362 Store.getOperand(2), Store.getOperand(3));
365 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
366 /// This is only run if not in -fast mode (aka -O0).
367 /// This allows the instruction selector to pick more read-modify-write
368 /// instructions. This is a common case:
378 /// [TokenFactor] [Op]
385 /// The fact the store's chain operand != load's chain will prevent the
386 /// (store (op (load))) instruction from being selected. We can transform it to:
405 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
406 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
407 E = DAG.allnodes_end(); I != E; ++I) {
408 if (!ISD::isNON_TRUNCStore(I))
410 SDOperand Chain = I->getOperand(0);
411 if (Chain.Val->getOpcode() != ISD::TokenFactor)
414 SDOperand N1 = I->getOperand(1);
415 SDOperand N2 = I->getOperand(2);
416 if (MVT::isFloatingPoint(N1.getValueType()) ||
417 MVT::isVector(N1.getValueType()) ||
423 unsigned Opcode = N1.Val->getOpcode();
432 SDOperand N10 = N1.getOperand(0);
433 SDOperand N11 = N1.getOperand(1);
434 if (ISD::isNON_EXTLoad(N10.Val))
436 else if (ISD::isNON_EXTLoad(N11.Val)) {
440 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
441 (N10.getOperand(1) == N2) &&
442 (N10.Val->getValueType(0) == N1.getValueType());
457 SDOperand N10 = N1.getOperand(0);
458 if (ISD::isNON_EXTLoad(N10.Val))
459 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
460 (N10.getOperand(1) == N2) &&
461 (N10.Val->getValueType(0) == N1.getValueType());
469 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
476 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
477 /// nodes that target the FP stack to be store and load to the stack. This is a
478 /// gross hack. We would like to simply mark these as being illegal, but when
479 /// we do that, legalize produces these when it expands calls, then expands
480 /// these in the same legalize pass. We would like dag combine to be able to
481 /// hack on these between the call expansion and the node legalization. As such
482 /// this pass basically does "really late" legalization of these inline with the
484 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
485 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
486 E = DAG.allnodes_end(); I != E; ) {
487 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
488 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
491 // If the source and destination are SSE registers, then this is a legal
492 // conversion that should not be lowered.
493 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
494 MVT::ValueType DstVT = N->getValueType(0);
495 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
496 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
497 if (SrcIsSSE && DstIsSSE)
500 if (!SrcIsSSE && !DstIsSSE) {
501 // If this is an FPStack extension, it is a noop.
502 if (N->getOpcode() == ISD::FP_EXTEND)
504 // If this is a value-preserving FPStack truncation, it is a noop.
505 if (N->getConstantOperandVal(1))
509 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
510 // FPStack has extload and truncstore. SSE can fold direct loads into other
511 // operations. Based on this, decide what we want to do.
512 MVT::ValueType MemVT;
513 if (N->getOpcode() == ISD::FP_ROUND)
514 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
516 MemVT = SrcIsSSE ? SrcVT : DstVT;
518 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
520 // FIXME: optimize the case where the src/dest is a load or store?
521 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
522 MemTmp, NULL, 0, MemVT);
523 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
526 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
527 // extload we created. This will cause general havok on the dag because
528 // anything below the conversion could be folded into other existing nodes.
529 // To avoid invalidating 'I', back it up to the convert node.
531 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
533 // Now that we did that, the node is dead. Increment the iterator to the
534 // next node to process, then delete N.
540 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
541 /// when it has created a SelectionDAG for us to codegen.
542 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
544 MachineFunction::iterator FirstMBB = BB;
547 PreprocessForRMW(DAG);
549 // FIXME: This should only happen when not -fast.
550 PreprocessForFPConvert(DAG);
552 // Codegen the basic block.
554 DOUT << "===== Instruction selection begins:\n";
557 DAG.setRoot(SelectRoot(DAG.getRoot()));
559 DOUT << "===== Instruction selection ends:\n";
562 DAG.RemoveDeadNodes();
564 // Emit machine code to BB. This can change 'BB' to the last block being
566 ScheduleAndEmitDAG(DAG);
568 // If we are emitting FP stack code, scan the basic block to determine if this
569 // block defines any FP values. If so, put an FP_REG_KILL instruction before
570 // the terminator of the block.
572 // Note that FP stack instructions are used in all modes for long double,
573 // so we always need to do this check.
574 // Also note that it's possible for an FP stack register to be live across
575 // an instruction that produces multiple basic blocks (SSE CMOV) so we
576 // must check all the generated basic blocks.
578 // Scan all of the machine instructions in these MBBs, checking for FP
579 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
580 MachineFunction::iterator MBBI = FirstMBB;
581 MachineFunction::iterator EndMBB = BB; ++EndMBB;
582 for (; MBBI != EndMBB; ++MBBI) {
583 MachineBasicBlock *MBB = MBBI;
585 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
586 // before the return.
588 MachineBasicBlock::iterator EndI = MBB->end();
590 if (EndI->getDesc().isReturn())
594 bool ContainsFPCode = false;
595 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
596 !ContainsFPCode && I != E; ++I) {
597 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
598 const TargetRegisterClass *clas;
599 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
600 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
601 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
602 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
603 X86::RFP32RegisterClass ||
604 clas == X86::RFP64RegisterClass ||
605 clas == X86::RFP80RegisterClass)) {
606 ContainsFPCode = true;
612 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
613 // a copy of the input value in this block. In SSE mode, we only care about
615 if (!ContainsFPCode) {
616 // Final check, check LLVM BB's that are successors to the LLVM BB
617 // corresponding to BB for FP PHI nodes.
618 const BasicBlock *LLVMBB = BB->getBasicBlock();
620 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
621 !ContainsFPCode && SI != E; ++SI) {
622 for (BasicBlock::const_iterator II = SI->begin();
623 (PN = dyn_cast<PHINode>(II)); ++II) {
624 if (PN->getType()==Type::X86_FP80Ty ||
625 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
626 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
627 ContainsFPCode = true;
633 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
634 if (ContainsFPCode) {
635 BuildMI(*MBB, MBBI->getFirstTerminator(),
636 TM.getInstrInfo()->get(X86::FP_REG_KILL));
642 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
643 /// the main function.
644 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
645 MachineFrameInfo *MFI) {
646 const TargetInstrInfo *TII = TM.getInstrInfo();
647 if (Subtarget->isTargetCygMing())
648 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
651 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
652 // If this is main, emit special code for main.
653 MachineBasicBlock *BB = MF.begin();
654 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
655 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
658 /// MatchAddress - Add the specified node to the specified addressing mode,
659 /// returning true if it cannot be done. This just pattern matches for the
661 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
662 bool isRoot, unsigned Depth) {
665 return MatchAddressBase(N, AM, isRoot, Depth);
667 // RIP relative addressing: %rip + 32-bit displacement!
669 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
670 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
671 if (isInt32(AM.Disp + Val)) {
679 int id = N.Val->getNodeId();
680 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
682 switch (N.getOpcode()) {
684 case ISD::Constant: {
685 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
686 if (isInt32(AM.Disp + Val)) {
693 case X86ISD::Wrapper: {
694 bool is64Bit = Subtarget->is64Bit();
695 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
696 // Also, base and index reg must be 0 in order to use rip as base.
697 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
698 AM.Base.Reg.Val || AM.IndexReg.Val))
700 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
702 // If value is available in a register both base and index components have
703 // been picked, we can't fit the result available in the register in the
704 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
705 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
706 SDOperand N0 = N.getOperand(0);
707 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
708 GlobalValue *GV = G->getGlobal();
710 AM.Disp += G->getOffset();
711 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
712 Subtarget->isPICStyleRIPRel();
714 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
715 AM.CP = CP->getConstVal();
716 AM.Align = CP->getAlignment();
717 AM.Disp += CP->getOffset();
718 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
719 Subtarget->isPICStyleRIPRel();
721 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
722 AM.ES = S->getSymbol();
723 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
724 Subtarget->isPICStyleRIPRel();
726 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
727 AM.JT = J->getIndex();
728 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
729 Subtarget->isPICStyleRIPRel();
736 case ISD::FrameIndex:
737 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
738 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
739 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
745 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
748 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
749 unsigned Val = CN->getValue();
750 if (Val == 1 || Val == 2 || Val == 3) {
752 SDOperand ShVal = N.Val->getOperand(0);
754 // Okay, we know that we have a scale by now. However, if the scaled
755 // value is an add of something and a constant, we can fold the
756 // constant into the disp field here.
757 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
758 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
759 AM.IndexReg = ShVal.Val->getOperand(0);
760 ConstantSDNode *AddVal =
761 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
762 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
777 // A mul_lohi where we need the low part can be folded as a plain multiply.
778 if (N.ResNo != 0) break;
781 // X*[3,5,9] -> X+X*[2,4,8]
782 if (!AlreadySelected &&
783 AM.BaseType == X86ISelAddressMode::RegBase &&
784 AM.Base.Reg.Val == 0 &&
785 AM.IndexReg.Val == 0 &&
787 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
788 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
789 AM.Scale = unsigned(CN->getValue())-1;
791 SDOperand MulVal = N.Val->getOperand(0);
794 // Okay, we know that we have a scale by now. However, if the scaled
795 // value is an add of something and a constant, we can fold the
796 // constant into the disp field here.
797 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
798 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
799 Reg = MulVal.Val->getOperand(0);
800 ConstantSDNode *AddVal =
801 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
802 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
806 Reg = N.Val->getOperand(0);
808 Reg = N.Val->getOperand(0);
811 AM.IndexReg = AM.Base.Reg = Reg;
818 if (!AlreadySelected) {
819 X86ISelAddressMode Backup = AM;
820 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
821 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
824 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
825 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
832 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
833 if (AlreadySelected) break;
835 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
836 X86ISelAddressMode Backup = AM;
837 // Start with the LHS as an addr mode.
838 if (!MatchAddress(N.getOperand(0), AM, false) &&
839 // Address could not have picked a GV address for the displacement.
841 // On x86-64, the resultant disp must fit in 32-bits.
842 isInt32(AM.Disp + CN->getSignExtended()) &&
843 // Check to see if the LHS & C is zero.
844 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
845 AM.Disp += CN->getValue();
853 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
854 // allows us to fold the shift into this addressing mode.
855 if (AlreadySelected) break;
856 SDOperand Shift = N.getOperand(0);
857 if (Shift.getOpcode() != ISD::SHL) break;
859 // Scale must not be used already.
860 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
862 // Not when RIP is used as the base.
863 if (AM.isRIPRel) break;
865 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
866 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
867 if (!C1 || !C2) break;
869 // Not likely to be profitable if either the AND or SHIFT node has more
870 // than one use (unless all uses are for address computation). Besides,
871 // isel mechanism requires their node ids to be reused.
872 if (!N.hasOneUse() || !Shift.hasOneUse())
875 // Verify that the shift amount is something we can fold.
876 unsigned ShiftCst = C1->getValue();
877 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
880 // Get the new AND mask, this folds to a constant.
881 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
882 SDOperand(C2, 0), SDOperand(C1, 0));
883 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
884 Shift.getOperand(0), NewANDMask);
885 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
886 NewAND.Val->setNodeId(N.Val->getNodeId());
888 AM.Scale = 1 << ShiftCst;
889 AM.IndexReg = NewAND;
894 return MatchAddressBase(N, AM, isRoot, Depth);
897 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
898 /// specified addressing mode without any further recursion.
899 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
900 bool isRoot, unsigned Depth) {
901 // Is the base register already occupied?
902 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
903 // If so, check to see if the scale index register is set.
904 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
910 // Otherwise, we cannot select it.
914 // Default, generate it as a register.
915 AM.BaseType = X86ISelAddressMode::RegBase;
920 /// SelectAddr - returns true if it is able pattern match an addressing mode.
921 /// It returns the operands which make up the maximal addressing mode it can
922 /// match by reference.
923 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
924 SDOperand &Scale, SDOperand &Index,
926 X86ISelAddressMode AM;
927 if (MatchAddress(N, AM))
930 MVT::ValueType VT = N.getValueType();
931 if (AM.BaseType == X86ISelAddressMode::RegBase) {
932 if (!AM.Base.Reg.Val)
933 AM.Base.Reg = CurDAG->getRegister(0, VT);
936 if (!AM.IndexReg.Val)
937 AM.IndexReg = CurDAG->getRegister(0, VT);
939 getAddressOperands(AM, Base, Scale, Index, Disp);
943 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
945 static inline bool isZeroNode(SDOperand Elt) {
946 return ((isa<ConstantSDNode>(Elt) &&
947 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
948 (isa<ConstantFPSDNode>(Elt) &&
949 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
953 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
954 /// match a load whose top elements are either undef or zeros. The load flavor
955 /// is derived from the type of N, which is either v4f32 or v2f64.
956 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
957 SDOperand N, SDOperand &Base,
958 SDOperand &Scale, SDOperand &Index,
959 SDOperand &Disp, SDOperand &InChain,
960 SDOperand &OutChain) {
961 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
962 InChain = N.getOperand(0).getValue(1);
963 if (ISD::isNON_EXTLoad(InChain.Val) &&
964 InChain.getValue(0).hasOneUse() &&
966 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
967 LoadSDNode *LD = cast<LoadSDNode>(InChain);
968 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
970 OutChain = LD->getChain();
975 // Also handle the case where we explicitly require zeros in the top
976 // elements. This is a vector shuffle from the zero vector.
977 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
978 // Check to see if the top elements are all zeros (or bitcast of zeros).
979 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
980 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
981 N.getOperand(1).Val->hasOneUse() &&
982 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
983 N.getOperand(1).getOperand(0).hasOneUse()) {
984 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
986 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
987 SDOperand ShufMask = N.getOperand(2);
988 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
990 if (C->getValue() == VecWidth) {
991 for (unsigned i = 1; i != VecWidth; ++i) {
992 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
995 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
996 if (C->getValue() >= VecWidth) return false;
1001 // Okay, this is a zero extending load. Fold it.
1002 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
1003 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1005 OutChain = LD->getChain();
1006 InChain = SDOperand(LD, 1);
1014 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1015 /// mode it matches can be cost effectively emitted as an LEA instruction.
1016 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1017 SDOperand &Base, SDOperand &Scale,
1018 SDOperand &Index, SDOperand &Disp) {
1019 X86ISelAddressMode AM;
1020 if (MatchAddress(N, AM))
1023 MVT::ValueType VT = N.getValueType();
1024 unsigned Complexity = 0;
1025 if (AM.BaseType == X86ISelAddressMode::RegBase)
1026 if (AM.Base.Reg.Val)
1029 AM.Base.Reg = CurDAG->getRegister(0, VT);
1030 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1033 if (AM.IndexReg.Val)
1036 AM.IndexReg = CurDAG->getRegister(0, VT);
1038 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1043 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1044 // to a LEA. This is determined with some expermentation but is by no means
1045 // optimal (especially for code size consideration). LEA is nice because of
1046 // its three-address nature. Tweak the cost function again when we can run
1047 // convertToThreeAddress() at register allocation time.
1048 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1049 // For X86-64, we should always use lea to materialize RIP relative
1051 if (Subtarget->is64Bit())
1057 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1060 if (Complexity > 2) {
1061 getAddressOperands(AM, Base, Scale, Index, Disp);
1067 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1068 SDOperand &Base, SDOperand &Scale,
1069 SDOperand &Index, SDOperand &Disp) {
1070 if (ISD::isNON_EXTLoad(N.Val) &&
1072 CanBeFoldedBy(N.Val, P.Val, P.Val))
1073 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1077 /// getGlobalBaseReg - Output the instructions required to put the
1078 /// base address to use for accessing globals into a register.
1080 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1081 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1082 if (!GlobalBaseReg) {
1083 // Insert the set of GlobalBaseReg into the first MBB of the function
1084 MachineFunction *MF = BB->getParent();
1085 MachineBasicBlock &FirstMBB = MF->front();
1086 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1087 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1088 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1090 const TargetInstrInfo *TII = TM.getInstrInfo();
1091 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1092 // only used in JIT code emission as displacement to pc.
1093 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1095 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1096 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1097 if (TM.getRelocationModel() == Reloc::PIC_ &&
1098 Subtarget->isPICStyleGOT()) {
1099 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1100 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1101 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1107 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1110 static SDNode *FindCallStartFromCall(SDNode *Node) {
1111 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1112 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1113 "Node doesn't have a token chain argument!");
1114 return FindCallStartFromCall(Node->getOperand(0).Val);
1117 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1121 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1122 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1123 if (!Subtarget->is64Bit()) {
1126 switch (N0.getValueType()) {
1127 default: assert(0 && "Unknown truncate!");
1129 Opc = X86::MOV16to16_;
1133 Opc = X86::MOV32to32_;
1137 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1138 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1139 VT, N0, SRIdx, N0.getValue(1));
1143 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1146 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1148 default: assert(0 && "Unknown truncate!"); break;
1150 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1154 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1155 SDNode *Node = N.Val;
1156 MVT::ValueType NVT = Node->getValueType(0);
1158 unsigned Opcode = Node->getOpcode();
1161 DOUT << std::string(Indent, ' ') << "Selecting: ";
1162 DEBUG(Node->dump(CurDAG));
1167 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1169 DOUT << std::string(Indent-2, ' ') << "== ";
1170 DEBUG(Node->dump(CurDAG));
1174 return NULL; // Already selected.
1179 case X86ISD::GlobalBaseReg:
1180 return getGlobalBaseReg();
1182 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1183 case X86ISD::RET_FLAG:
1184 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1185 if (Amt->getSignExtended() != 0) break;
1187 // Match (X86retflag 0).
1188 SDOperand Chain = N.getOperand(0);
1189 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1191 SmallVector<SDOperand, 8> Ops0;
1192 AddToISelQueue(Chain);
1193 SDOperand InFlag(0, 0);
1195 InFlag = N.getOperand(N.getNumOperands()-1);
1196 AddToISelQueue(InFlag);
1198 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1200 AddToISelQueue(N.getOperand(i));
1201 Ops0.push_back(N.getOperand(i));
1203 Ops0.push_back(Chain);
1205 Ops0.push_back(InFlag);
1206 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1207 &Ops0[0], Ops0.size());
1212 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1213 // code and is matched first so to prevent it from being turned into
1215 // In 64-bit small code size mode, use LEA to take advantage of
1216 // RIP-relative addressing.
1217 if (TM.getCodeModel() != CodeModel::Small)
1219 MVT::ValueType PtrVT = TLI.getPointerTy();
1220 SDOperand N0 = N.getOperand(0);
1221 SDOperand N1 = N.getOperand(1);
1222 if (N.Val->getValueType(0) == PtrVT &&
1223 N0.getOpcode() == X86ISD::Wrapper &&
1224 N1.getOpcode() == ISD::Constant) {
1225 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1227 // TODO: handle ExternalSymbolSDNode.
1228 if (GlobalAddressSDNode *G =
1229 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1230 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1231 G->getOffset() + Offset);
1232 } else if (ConstantPoolSDNode *CP =
1233 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1234 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1236 CP->getOffset()+Offset);
1240 if (Subtarget->is64Bit()) {
1241 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1242 CurDAG->getRegister(0, PtrVT), C };
1243 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1245 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1249 // Other cases are handled by auto-generated code.
1253 case ISD::SMUL_LOHI:
1254 case ISD::UMUL_LOHI: {
1255 SDOperand N0 = Node->getOperand(0);
1256 SDOperand N1 = Node->getOperand(1);
1258 bool isSigned = Opcode == ISD::SMUL_LOHI;
1261 default: assert(0 && "Unsupported VT!");
1262 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1263 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1264 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1265 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1269 default: assert(0 && "Unsupported VT!");
1270 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1271 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1272 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1273 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1276 unsigned LoReg, HiReg;
1278 default: assert(0 && "Unsupported VT!");
1279 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1280 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1281 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1282 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1285 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1286 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1287 // multiplty is commmutative
1289 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1295 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1296 N0, SDOperand()).getValue(1);
1299 AddToISelQueue(N1.getOperand(0));
1300 AddToISelQueue(Tmp0);
1301 AddToISelQueue(Tmp1);
1302 AddToISelQueue(Tmp2);
1303 AddToISelQueue(Tmp3);
1304 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1306 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1307 InFlag = SDOperand(CNode, 1);
1308 // Update the chain.
1309 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1313 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1316 // Copy the low half of the result, if it is needed.
1317 if (!N.getValue(0).use_empty()) {
1318 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1319 LoReg, NVT, InFlag);
1320 InFlag = Result.getValue(2);
1321 ReplaceUses(N.getValue(0), Result);
1323 DOUT << std::string(Indent-2, ' ') << "=> ";
1324 DEBUG(Result.Val->dump(CurDAG));
1328 // Copy the high half of the result, if it is needed.
1329 if (!N.getValue(1).use_empty()) {
1331 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1332 // Prevent use of AH in a REX instruction by referencing AX instead.
1333 // Shift it down 8 bits.
1334 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1335 X86::AX, MVT::i16, InFlag);
1336 InFlag = Result.getValue(2);
1337 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1338 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1339 // Then truncate it down to i8.
1340 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1341 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1342 MVT::i8, Result, SRIdx), 0);
1344 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1345 HiReg, NVT, InFlag);
1346 InFlag = Result.getValue(2);
1348 ReplaceUses(N.getValue(1), Result);
1350 DOUT << std::string(Indent-2, ' ') << "=> ";
1351 DEBUG(Result.Val->dump(CurDAG));
1364 case ISD::UDIVREM: {
1365 SDOperand N0 = Node->getOperand(0);
1366 SDOperand N1 = Node->getOperand(1);
1368 bool isSigned = Opcode == ISD::SDIVREM;
1371 default: assert(0 && "Unsupported VT!");
1372 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1373 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1374 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1375 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1379 default: assert(0 && "Unsupported VT!");
1380 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1381 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1382 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1383 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1386 unsigned LoReg, HiReg;
1387 unsigned ClrOpcode, SExtOpcode;
1389 default: assert(0 && "Unsupported VT!");
1391 LoReg = X86::AL; HiReg = X86::AH;
1393 SExtOpcode = X86::CBW;
1396 LoReg = X86::AX; HiReg = X86::DX;
1397 ClrOpcode = X86::MOV16r0;
1398 SExtOpcode = X86::CWD;
1401 LoReg = X86::EAX; HiReg = X86::EDX;
1402 ClrOpcode = X86::MOV32r0;
1403 SExtOpcode = X86::CDQ;
1406 LoReg = X86::RAX; HiReg = X86::RDX;
1407 ClrOpcode = X86::MOV64r0;
1408 SExtOpcode = X86::CQO;
1412 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1413 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1416 if (NVT == MVT::i8 && !isSigned) {
1417 // Special case for div8, just use a move with zero extension to AX to
1418 // clear the upper 8 bits (AH).
1419 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1420 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1421 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1422 AddToISelQueue(N0.getOperand(0));
1423 AddToISelQueue(Tmp0);
1424 AddToISelQueue(Tmp1);
1425 AddToISelQueue(Tmp2);
1426 AddToISelQueue(Tmp3);
1428 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1430 Chain = Move.getValue(1);
1431 ReplaceUses(N0.getValue(1), Chain);
1435 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1436 Chain = CurDAG->getEntryNode();
1438 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1439 InFlag = Chain.getValue(1);
1443 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1444 LoReg, N0, SDOperand()).getValue(1);
1446 // Sign extend the low part into the high part.
1448 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1450 // Zero out the high part, effectively zero extending the input.
1451 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1452 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1453 ClrNode, InFlag).getValue(1);
1458 AddToISelQueue(N1.getOperand(0));
1459 AddToISelQueue(Tmp0);
1460 AddToISelQueue(Tmp1);
1461 AddToISelQueue(Tmp2);
1462 AddToISelQueue(Tmp3);
1463 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1465 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1466 InFlag = SDOperand(CNode, 1);
1467 // Update the chain.
1468 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1472 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1475 // Copy the division (low) result, if it is needed.
1476 if (!N.getValue(0).use_empty()) {
1477 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1478 LoReg, NVT, InFlag);
1479 InFlag = Result.getValue(2);
1480 ReplaceUses(N.getValue(0), Result);
1482 DOUT << std::string(Indent-2, ' ') << "=> ";
1483 DEBUG(Result.Val->dump(CurDAG));
1487 // Copy the remainder (high) result, if it is needed.
1488 if (!N.getValue(1).use_empty()) {
1490 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1491 // Prevent use of AH in a REX instruction by referencing AX instead.
1492 // Shift it down 8 bits.
1493 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1494 X86::AX, MVT::i16, InFlag);
1495 InFlag = Result.getValue(2);
1496 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1497 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1498 // Then truncate it down to i8.
1499 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1500 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1501 MVT::i8, Result, SRIdx), 0);
1503 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1504 HiReg, NVT, InFlag);
1505 InFlag = Result.getValue(2);
1507 ReplaceUses(N.getValue(1), Result);
1509 DOUT << std::string(Indent-2, ' ') << "=> ";
1510 DEBUG(Result.Val->dump(CurDAG));
1522 case ISD::ANY_EXTEND: {
1523 // Check if the type extended to supports subregs.
1527 SDOperand N0 = Node->getOperand(0);
1528 // Get the subregsiter index for the type to extend.
1529 MVT::ValueType N0VT = N0.getValueType();
1530 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1531 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1532 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1534 // If we don't have a subreg Idx, let generated ISel have a try.
1538 // If we have an index, generate an insert_subreg into undef.
1541 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
1542 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1543 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1544 NVT, Undef, N0, SRIdx);
1547 DOUT << std::string(Indent-2, ' ') << "=> ";
1548 DEBUG(ResNode->dump(CurDAG));
1555 case ISD::SIGN_EXTEND_INREG: {
1556 SDOperand N0 = Node->getOperand(0);
1559 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1560 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1564 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1565 else assert(0 && "Unknown sign_extend_inreg!");
1569 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1570 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1571 default: assert(0 && "Unknown sign_extend_inreg!");
1576 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1577 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1578 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1579 default: assert(0 && "Unknown sign_extend_inreg!");
1582 default: assert(0 && "Unknown sign_extend_inreg!");
1585 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1588 DOUT << std::string(Indent-2, ' ') << "=> ";
1589 DEBUG(TruncOp.Val->dump(CurDAG));
1591 DOUT << std::string(Indent-2, ' ') << "=> ";
1592 DEBUG(ResNode->dump(CurDAG));
1600 case ISD::TRUNCATE: {
1601 SDOperand Input = Node->getOperand(0);
1602 AddToISelQueue(Node->getOperand(0));
1603 SDNode *ResNode = getTruncate(Input, NVT);
1606 DOUT << std::string(Indent-2, ' ') << "=> ";
1607 DEBUG(ResNode->dump(CurDAG));
1616 SDNode *ResNode = SelectCode(N);
1619 DOUT << std::string(Indent-2, ' ') << "=> ";
1620 if (ResNode == NULL || ResNode == N.Val)
1621 DEBUG(N.Val->dump(CurDAG));
1623 DEBUG(ResNode->dump(CurDAG));
1631 bool X86DAGToDAGISel::
1632 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1633 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1634 SDOperand Op0, Op1, Op2, Op3;
1635 switch (ConstraintCode) {
1636 case 'o': // offsetable ??
1637 case 'v': // not offsetable ??
1638 default: return true;
1640 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1645 OutOps.push_back(Op0);
1646 OutOps.push_back(Op1);
1647 OutOps.push_back(Op2);
1648 OutOps.push_back(Op3);
1649 AddToISelQueue(Op0);
1650 AddToISelQueue(Op1);
1651 AddToISelQueue(Op2);
1652 AddToISelQueue(Op3);
1656 /// createX86ISelDag - This pass converts a legalized DAG into a
1657 /// X86-specific DAG, ready for instruction scheduling.
1659 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1660 return new X86DAGToDAGISel(TM, Fast);