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/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Streams.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 /// SDValue'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) {
82 cerr << "X86ISelAddressMode " << this << "\n";
84 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
86 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
87 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
89 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
91 cerr << " Disp " << Disp << "\n";
92 cerr << "GV "; if (GV) GV->dump();
94 cerr << " CP "; if (CP) CP->dump();
97 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
98 cerr << " JT" << JT << " Align" << Align << "\n";
104 //===--------------------------------------------------------------------===//
105 /// ISel - X86 specific code to select X86 machine instructions for
106 /// SelectionDAG operations.
108 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
109 /// ContainsFPCode - Every instruction we select that uses or defines a FP
110 /// register should set this to true.
113 /// TM - Keep a reference to X86TargetMachine.
115 X86TargetMachine &TM;
117 /// X86Lowering - This object fully describes how to lower LLVM code to an
118 /// X86-specific SelectionDAG.
119 X86TargetLowering X86Lowering;
121 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
122 /// make the right decision when generating code for different targets.
123 const X86Subtarget *Subtarget;
125 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
127 unsigned GlobalBaseReg;
129 /// CurBB - Current BB being isel'd.
131 MachineBasicBlock *CurBB;
134 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
135 : SelectionDAGISel(X86Lowering, fast),
136 ContainsFPCode(false), TM(tm),
137 X86Lowering(*TM.getTargetLowering()),
138 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
140 virtual bool runOnFunction(Function &Fn) {
141 // Make sure we re-emit a set of the global base reg if necessary
143 return SelectionDAGISel::runOnFunction(Fn);
146 virtual const char *getPassName() const {
147 return "X86 DAG->DAG Instruction Selection";
150 /// InstructionSelect - This callback is invoked by
151 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
152 virtual void InstructionSelect();
154 /// InstructionSelectPostProcessing - Post processing of selected and
155 /// scheduled basic blocks.
156 virtual void InstructionSelectPostProcessing();
158 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
160 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
162 // Include the pieces autogenerated from the target description.
163 #include "X86GenDAGISel.inc"
166 SDNode *Select(SDValue N);
168 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
169 bool isRoot = true, unsigned Depth = 0);
170 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
171 bool isRoot, unsigned Depth);
172 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
173 SDValue &Scale, SDValue &Index, SDValue &Disp);
174 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
175 SDValue &Scale, SDValue &Index, SDValue &Disp);
176 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
177 SDValue N, SDValue &Base, SDValue &Scale,
178 SDValue &Index, SDValue &Disp,
179 SDValue &InChain, SDValue &OutChain);
180 bool TryFoldLoad(SDValue P, SDValue N,
181 SDValue &Base, SDValue &Scale,
182 SDValue &Index, SDValue &Disp);
183 void PreprocessForRMW();
184 void PreprocessForFPConvert();
186 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
187 /// inline asm expressions.
188 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
190 std::vector<SDValue> &OutOps);
192 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
194 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
195 SDValue &Scale, SDValue &Index,
197 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
198 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
200 Scale = getI8Imm(AM.Scale);
202 // These are 32-bit even in 64-bit mode since RIP relative offset
205 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
207 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
210 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
211 else if (AM.JT != -1)
212 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
214 Disp = getI32Imm(AM.Disp);
217 /// getI8Imm - Return a target constant with the specified value, of type
219 inline SDValue getI8Imm(unsigned Imm) {
220 return CurDAG->getTargetConstant(Imm, MVT::i8);
223 /// getI16Imm - Return a target constant with the specified value, of type
225 inline SDValue getI16Imm(unsigned Imm) {
226 return CurDAG->getTargetConstant(Imm, MVT::i16);
229 /// getI32Imm - Return a target constant with the specified value, of type
231 inline SDValue getI32Imm(unsigned Imm) {
232 return CurDAG->getTargetConstant(Imm, MVT::i32);
235 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
236 /// base register. Return the virtual register that holds this value.
237 SDNode *getGlobalBaseReg();
239 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
240 /// truncate of the specified operand to i8. This can be done with tablegen,
241 /// except that this code uses MVT::Flag in a tricky way that happens to
242 /// improve scheduling in some cases.
243 SDNode *getTruncateTo8Bit(SDValue N0);
251 /// findFlagUse - Return use of MVT::Flag value produced by the specified
254 static SDNode *findFlagUse(SDNode *N) {
255 unsigned FlagResNo = N->getNumValues()-1;
256 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
258 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
259 SDValue Op = User->getOperand(i);
260 if (Op.getNode() == N && Op.getResNo() == FlagResNo)
267 /// findNonImmUse - Return true by reference in "found" if "Use" is an
268 /// non-immediate use of "Def". This function recursively traversing
269 /// up the operand chain ignoring certain nodes.
270 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
271 SDNode *Root, SDNode *Skip, bool &found,
272 SmallPtrSet<SDNode*, 16> &Visited) {
274 Use->getNodeId() > Def->getNodeId() ||
275 !Visited.insert(Use))
278 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
279 SDNode *N = Use->getOperand(i).getNode();
284 continue; // We are not looking for immediate use.
286 // Must be a chain reading node where it is possible to reach its own
287 // chain operand through a path started from another operand.
288 assert(Use->getOpcode() == ISD::STORE ||
289 Use->getOpcode() == X86ISD::CMP ||
290 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
291 Use->getOpcode() == ISD::INTRINSIC_VOID);
298 // Traverse up the operand chain.
299 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
303 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
304 /// be reached. Return true if that's the case. However, ignore direct uses
305 /// by ImmedUse (which would be U in the example illustrated in
306 /// CanBeFoldedBy) and by Root (which can happen in the store case).
307 /// FIXME: to be really generic, we should allow direct use by any node
308 /// that is being folded. But realisticly since we only fold loads which
309 /// have one non-chain use, we only need to watch out for load/op/store
310 /// and load/op/cmp case where the root (store / cmp) may reach the load via
311 /// its chain operand.
312 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
313 SDNode *Skip = NULL) {
314 SmallPtrSet<SDNode*, 16> Visited;
316 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
321 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
322 if (Fast) return false;
324 // If U use can somehow reach N through another path then U can't fold N or
325 // it will create a cycle. e.g. In the following diagram, U can reach N
326 // through X. If N is folded into into U, then X is both a predecessor and
337 if (isNonImmUse(Root, N, U))
340 // If U produces a flag, then it gets (even more) interesting. Since it
341 // would have been "glued" together with its flag use, we need to check if
354 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
355 // NU), then TF is a predecessor of FU and a successor of NU. But since
356 // NU and FU are flagged together, this effectively creates a cycle.
357 bool HasFlagUse = false;
358 MVT VT = Root->getValueType(Root->getNumValues()-1);
359 while ((VT == MVT::Flag && !Root->use_empty())) {
360 SDNode *FU = findFlagUse(Root);
367 VT = Root->getValueType(Root->getNumValues()-1);
371 return !isNonImmUse(Root, N, Root, U);
375 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
376 /// and move load below the TokenFactor. Replace store's chain operand with
377 /// load's chain result.
378 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
379 SDValue Store, SDValue TF) {
380 SmallVector<SDValue, 4> Ops;
381 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
382 if (Load.getNode() == TF.getOperand(i).getNode())
383 Ops.push_back(Load.getOperand(0));
385 Ops.push_back(TF.getOperand(i));
386 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
387 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
388 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
389 Store.getOperand(2), Store.getOperand(3));
392 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
394 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
396 if (N.getOpcode() == ISD::BIT_CONVERT)
399 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
400 if (!LD || LD->isVolatile())
402 if (LD->getAddressingMode() != ISD::UNINDEXED)
405 ISD::LoadExtType ExtType = LD->getExtensionType();
406 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
410 N.getOperand(1) == Address &&
411 N.getNode()->isOperandOf(Chain.getNode())) {
418 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
419 /// operand and move load below the call's chain operand.
420 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
421 SDValue Call, SDValue Chain) {
422 SmallVector<SDValue, 8> Ops;
423 for (unsigned i = 0, e = Chain.getNode()->getNumOperands(); i != e; ++i)
424 if (Load.getNode() == Chain.getOperand(i).getNode())
425 Ops.push_back(Load.getOperand(0));
427 Ops.push_back(Chain.getOperand(i));
428 CurDAG->UpdateNodeOperands(Chain, &Ops[0], Ops.size());
429 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
430 Load.getOperand(1), Load.getOperand(2));
432 Ops.push_back(SDValue(Load.getNode(), 1));
433 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
434 Ops.push_back(Call.getOperand(i));
435 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
438 /// isCalleeLoad - Return true if call address is a load and it can be
439 /// moved below CALLSEQ_START and the chains leading up to the call.
440 /// Return the CALLSEQ_START by reference as a second output.
441 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
442 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
444 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
447 LD->getAddressingMode() != ISD::UNINDEXED ||
448 LD->getExtensionType() != ISD::NON_EXTLOAD)
451 // Now let's find the callseq_start.
452 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
453 if (!Chain.hasOneUse())
455 Chain = Chain.getOperand(0);
457 return Chain.getOperand(0).getNode() == Callee.getNode();
461 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
462 /// This is only run if not in -fast mode (aka -O0).
463 /// This allows the instruction selector to pick more read-modify-write
464 /// instructions. This is a common case:
474 /// [TokenFactor] [Op]
481 /// The fact the store's chain operand != load's chain will prevent the
482 /// (store (op (load))) instruction from being selected. We can transform it to:
501 void X86DAGToDAGISel::PreprocessForRMW() {
502 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
503 E = CurDAG->allnodes_end(); I != E; ++I) {
504 if (I->getOpcode() == X86ISD::CALL) {
505 /// Also try moving call address load from outside callseq_start to just
506 /// before the call to allow it to be folded.
524 SDValue Chain = I->getOperand(0);
525 SDValue Load = I->getOperand(1);
526 if (!isCalleeLoad(Load, Chain))
528 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
533 if (!ISD::isNON_TRUNCStore(I))
535 SDValue Chain = I->getOperand(0);
537 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
540 SDValue N1 = I->getOperand(1);
541 SDValue N2 = I->getOperand(2);
542 if ((N1.getValueType().isFloatingPoint() &&
543 !N1.getValueType().isVector()) ||
549 unsigned Opcode = N1.getNode()->getOpcode();
558 case ISD::VECTOR_SHUFFLE: {
559 SDValue N10 = N1.getOperand(0);
560 SDValue N11 = N1.getOperand(1);
561 RModW = isRMWLoad(N10, Chain, N2, Load);
563 RModW = isRMWLoad(N11, Chain, N2, Load);
576 SDValue N10 = N1.getOperand(0);
577 RModW = isRMWLoad(N10, Chain, N2, Load);
583 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
590 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
591 /// nodes that target the FP stack to be store and load to the stack. This is a
592 /// gross hack. We would like to simply mark these as being illegal, but when
593 /// we do that, legalize produces these when it expands calls, then expands
594 /// these in the same legalize pass. We would like dag combine to be able to
595 /// hack on these between the call expansion and the node legalization. As such
596 /// this pass basically does "really late" legalization of these inline with the
598 void X86DAGToDAGISel::PreprocessForFPConvert() {
599 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
600 E = CurDAG->allnodes_end(); I != E; ) {
601 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
602 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
605 // If the source and destination are SSE registers, then this is a legal
606 // conversion that should not be lowered.
607 MVT SrcVT = N->getOperand(0).getValueType();
608 MVT DstVT = N->getValueType(0);
609 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
610 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
611 if (SrcIsSSE && DstIsSSE)
614 if (!SrcIsSSE && !DstIsSSE) {
615 // If this is an FPStack extension, it is a noop.
616 if (N->getOpcode() == ISD::FP_EXTEND)
618 // If this is a value-preserving FPStack truncation, it is a noop.
619 if (N->getConstantOperandVal(1))
623 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
624 // FPStack has extload and truncstore. SSE can fold direct loads into other
625 // operations. Based on this, decide what we want to do.
627 if (N->getOpcode() == ISD::FP_ROUND)
628 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
630 MemVT = SrcIsSSE ? SrcVT : DstVT;
632 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
634 // FIXME: optimize the case where the src/dest is a load or store?
635 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(),
637 MemTmp, NULL, 0, MemVT);
638 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
641 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
642 // extload we created. This will cause general havok on the dag because
643 // anything below the conversion could be folded into other existing nodes.
644 // To avoid invalidating 'I', back it up to the convert node.
646 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
648 // Now that we did that, the node is dead. Increment the iterator to the
649 // next node to process, then delete N.
651 CurDAG->DeleteNode(N);
655 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
656 /// when it has created a SelectionDAG for us to codegen.
657 void X86DAGToDAGISel::InstructionSelect() {
658 CurBB = BB; // BB can change as result of isel.
664 // FIXME: This should only happen when not -fast.
665 PreprocessForFPConvert();
667 // Codegen the basic block.
669 DOUT << "===== Instruction selection begins:\n";
674 DOUT << "===== Instruction selection ends:\n";
677 CurDAG->RemoveDeadNodes();
680 void X86DAGToDAGISel::InstructionSelectPostProcessing() {
681 // If we are emitting FP stack code, scan the basic block to determine if this
682 // block defines any FP values. If so, put an FP_REG_KILL instruction before
683 // the terminator of the block.
685 // Note that FP stack instructions are used in all modes for long double,
686 // so we always need to do this check.
687 // Also note that it's possible for an FP stack register to be live across
688 // an instruction that produces multiple basic blocks (SSE CMOV) so we
689 // must check all the generated basic blocks.
691 // Scan all of the machine instructions in these MBBs, checking for FP
692 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
693 MachineFunction::iterator MBBI = CurBB;
694 MachineFunction::iterator EndMBB = BB; ++EndMBB;
695 for (; MBBI != EndMBB; ++MBBI) {
696 MachineBasicBlock *MBB = MBBI;
698 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
699 // before the return.
701 MachineBasicBlock::iterator EndI = MBB->end();
703 if (EndI->getDesc().isReturn())
707 bool ContainsFPCode = false;
708 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
709 !ContainsFPCode && I != E; ++I) {
710 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
711 const TargetRegisterClass *clas;
712 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
713 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
714 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
715 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
716 X86::RFP32RegisterClass ||
717 clas == X86::RFP64RegisterClass ||
718 clas == X86::RFP80RegisterClass)) {
719 ContainsFPCode = true;
725 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
726 // a copy of the input value in this block. In SSE mode, we only care about
728 if (!ContainsFPCode) {
729 // Final check, check LLVM BB's that are successors to the LLVM BB
730 // corresponding to BB for FP PHI nodes.
731 const BasicBlock *LLVMBB = BB->getBasicBlock();
733 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
734 !ContainsFPCode && SI != E; ++SI) {
735 for (BasicBlock::const_iterator II = SI->begin();
736 (PN = dyn_cast<PHINode>(II)); ++II) {
737 if (PN->getType()==Type::X86_FP80Ty ||
738 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
739 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
740 ContainsFPCode = true;
746 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
747 if (ContainsFPCode) {
748 BuildMI(*MBB, MBBI->getFirstTerminator(),
749 TM.getInstrInfo()->get(X86::FP_REG_KILL));
755 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
756 /// the main function.
757 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
758 MachineFrameInfo *MFI) {
759 const TargetInstrInfo *TII = TM.getInstrInfo();
760 if (Subtarget->isTargetCygMing())
761 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
764 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
765 // If this is main, emit special code for main.
766 MachineBasicBlock *BB = MF.begin();
767 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
768 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
771 /// MatchAddress - Add the specified node to the specified addressing mode,
772 /// returning true if it cannot be done. This just pattern matches for the
774 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
775 bool isRoot, unsigned Depth) {
776 DOUT << "MatchAddress: "; DEBUG(AM.dump());
779 return MatchAddressBase(N, AM, isRoot, Depth);
781 // RIP relative addressing: %rip + 32-bit displacement!
783 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
784 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
785 if (isInt32(AM.Disp + Val)) {
793 int id = N.getNode()->getNodeId();
794 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
796 switch (N.getOpcode()) {
798 case ISD::Constant: {
799 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
800 if (isInt32(AM.Disp + Val)) {
807 case X86ISD::Wrapper: {
808 DOUT << "Wrapper: 64bit " << Subtarget->is64Bit();
809 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
810 DOUT << "AlreadySelected " << AlreadySelected << "\n";
811 bool is64Bit = Subtarget->is64Bit();
812 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
813 // Also, base and index reg must be 0 in order to use rip as base.
814 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
815 AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
817 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
819 // If value is available in a register both base and index components have
820 // been picked, we can't fit the result available in the register in the
821 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
822 if (!AlreadySelected || (AM.Base.Reg.getNode() && AM.IndexReg.getNode())) {
823 SDValue N0 = N.getOperand(0);
824 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
825 GlobalValue *GV = G->getGlobal();
827 AM.Disp += G->getOffset();
828 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
829 Subtarget->isPICStyleRIPRel();
831 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
832 AM.CP = CP->getConstVal();
833 AM.Align = CP->getAlignment();
834 AM.Disp += CP->getOffset();
835 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
836 Subtarget->isPICStyleRIPRel();
838 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
839 AM.ES = S->getSymbol();
840 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
841 Subtarget->isPICStyleRIPRel();
843 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
844 AM.JT = J->getIndex();
845 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
846 Subtarget->isPICStyleRIPRel();
853 case ISD::FrameIndex:
854 if (AM.BaseType == X86ISelAddressMode::RegBase
855 && AM.Base.Reg.getNode() == 0) {
856 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
857 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
863 if (AlreadySelected || AM.IndexReg.getNode() != 0
864 || AM.Scale != 1 || AM.isRIPRel)
868 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
869 unsigned Val = CN->getZExtValue();
870 if (Val == 1 || Val == 2 || Val == 3) {
872 SDValue ShVal = N.getNode()->getOperand(0);
874 // Okay, we know that we have a scale by now. However, if the scaled
875 // value is an add of something and a constant, we can fold the
876 // constant into the disp field here.
877 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
878 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
879 AM.IndexReg = ShVal.getNode()->getOperand(0);
880 ConstantSDNode *AddVal =
881 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
882 uint64_t Disp = AM.Disp + (AddVal->getZExtValue() << Val);
897 // A mul_lohi where we need the low part can be folded as a plain multiply.
898 if (N.getResNo() != 0) break;
901 // X*[3,5,9] -> X+X*[2,4,8]
902 if (!AlreadySelected &&
903 AM.BaseType == X86ISelAddressMode::RegBase &&
904 AM.Base.Reg.getNode() == 0 &&
905 AM.IndexReg.getNode() == 0 &&
908 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
909 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
910 CN->getZExtValue() == 9) {
911 AM.Scale = unsigned(CN->getZExtValue())-1;
913 SDValue MulVal = N.getNode()->getOperand(0);
916 // Okay, we know that we have a scale by now. However, if the scaled
917 // value is an add of something and a constant, we can fold the
918 // constant into the disp field here.
919 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
920 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
921 Reg = MulVal.getNode()->getOperand(0);
922 ConstantSDNode *AddVal =
923 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
924 uint64_t Disp = AM.Disp + AddVal->getZExtValue() *
929 Reg = N.getNode()->getOperand(0);
931 Reg = N.getNode()->getOperand(0);
934 AM.IndexReg = AM.Base.Reg = Reg;
941 if (!AlreadySelected) {
942 X86ISelAddressMode Backup = AM;
943 if (!MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1) &&
944 !MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1))
947 if (!MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1) &&
948 !MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1))
955 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
956 if (AlreadySelected) break;
958 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
959 X86ISelAddressMode Backup = AM;
960 // Start with the LHS as an addr mode.
961 if (!MatchAddress(N.getOperand(0), AM, false) &&
962 // Address could not have picked a GV address for the displacement.
964 // On x86-64, the resultant disp must fit in 32-bits.
965 isInt32(AM.Disp + CN->getSignExtended()) &&
966 // Check to see if the LHS & C is zero.
967 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
968 AM.Disp += CN->getZExtValue();
976 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
977 // allows us to fold the shift into this addressing mode.
978 if (AlreadySelected) break;
979 SDValue Shift = N.getOperand(0);
980 if (Shift.getOpcode() != ISD::SHL) break;
982 // Scale must not be used already.
983 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
985 // Not when RIP is used as the base.
986 if (AM.isRIPRel) break;
988 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
989 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
990 if (!C1 || !C2) break;
992 // Not likely to be profitable if either the AND or SHIFT node has more
993 // than one use (unless all uses are for address computation). Besides,
994 // isel mechanism requires their node ids to be reused.
995 if (!N.hasOneUse() || !Shift.hasOneUse())
998 // Verify that the shift amount is something we can fold.
999 unsigned ShiftCst = C1->getZExtValue();
1000 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1003 // Get the new AND mask, this folds to a constant.
1004 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
1005 SDValue(C2, 0), SDValue(C1, 0));
1006 SDValue NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
1007 Shift.getOperand(0), NewANDMask);
1008 NewANDMask.getNode()->setNodeId(Shift.getNode()->getNodeId());
1009 NewAND.getNode()->setNodeId(N.getNode()->getNodeId());
1011 AM.Scale = 1 << ShiftCst;
1012 AM.IndexReg = NewAND;
1017 return MatchAddressBase(N, AM, isRoot, Depth);
1020 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1021 /// specified addressing mode without any further recursion.
1022 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
1023 bool isRoot, unsigned Depth) {
1024 // Is the base register already occupied?
1025 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1026 // If so, check to see if the scale index register is set.
1027 if (AM.IndexReg.getNode() == 0 && !AM.isRIPRel) {
1033 // Otherwise, we cannot select it.
1037 // Default, generate it as a register.
1038 AM.BaseType = X86ISelAddressMode::RegBase;
1043 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1044 /// It returns the operands which make up the maximal addressing mode it can
1045 /// match by reference.
1046 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1047 SDValue &Scale, SDValue &Index,
1049 X86ISelAddressMode AM;
1050 if (MatchAddress(N, AM))
1053 MVT VT = N.getValueType();
1054 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1055 if (!AM.Base.Reg.getNode())
1056 AM.Base.Reg = CurDAG->getRegister(0, VT);
1059 if (!AM.IndexReg.getNode())
1060 AM.IndexReg = CurDAG->getRegister(0, VT);
1062 getAddressOperands(AM, Base, Scale, Index, Disp);
1066 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
1068 static inline bool isZeroNode(SDValue Elt) {
1069 return ((isa<ConstantSDNode>(Elt) &&
1070 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
1071 (isa<ConstantFPSDNode>(Elt) &&
1072 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
1076 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1077 /// match a load whose top elements are either undef or zeros. The load flavor
1078 /// is derived from the type of N, which is either v4f32 or v2f64.
1079 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1080 SDValue N, SDValue &Base,
1081 SDValue &Scale, SDValue &Index,
1082 SDValue &Disp, SDValue &InChain,
1083 SDValue &OutChain) {
1084 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1085 InChain = N.getOperand(0).getValue(1);
1086 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1087 InChain.getValue(0).hasOneUse() &&
1089 CanBeFoldedBy(N.getNode(), Pred.getNode(), Op.getNode())) {
1090 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1091 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1093 OutChain = LD->getChain();
1098 // Also handle the case where we explicitly require zeros in the top
1099 // elements. This is a vector shuffle from the zero vector.
1100 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1101 // Check to see if the top elements are all zeros (or bitcast of zeros).
1102 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1103 N.getOperand(0).getNode()->hasOneUse() &&
1104 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1105 N.getOperand(0).getOperand(0).hasOneUse()) {
1106 // Okay, this is a zero extending load. Fold it.
1107 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1108 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1110 OutChain = LD->getChain();
1111 InChain = SDValue(LD, 1);
1118 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1119 /// mode it matches can be cost effectively emitted as an LEA instruction.
1120 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1121 SDValue &Base, SDValue &Scale,
1122 SDValue &Index, SDValue &Disp) {
1123 X86ISelAddressMode AM;
1124 if (MatchAddress(N, AM))
1127 MVT VT = N.getValueType();
1128 unsigned Complexity = 0;
1129 if (AM.BaseType == X86ISelAddressMode::RegBase)
1130 if (AM.Base.Reg.getNode())
1133 AM.Base.Reg = CurDAG->getRegister(0, VT);
1134 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1137 if (AM.IndexReg.getNode())
1140 AM.IndexReg = CurDAG->getRegister(0, VT);
1142 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1147 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1148 // to a LEA. This is determined with some expermentation but is by no means
1149 // optimal (especially for code size consideration). LEA is nice because of
1150 // its three-address nature. Tweak the cost function again when we can run
1151 // convertToThreeAddress() at register allocation time.
1152 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1153 // For X86-64, we should always use lea to materialize RIP relative
1155 if (Subtarget->is64Bit())
1161 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1164 if (Complexity > 2) {
1165 getAddressOperands(AM, Base, Scale, Index, Disp);
1171 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1172 SDValue &Base, SDValue &Scale,
1173 SDValue &Index, SDValue &Disp) {
1174 if (ISD::isNON_EXTLoad(N.getNode()) &&
1176 CanBeFoldedBy(N.getNode(), P.getNode(), P.getNode()))
1177 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1181 /// getGlobalBaseReg - Output the instructions required to put the
1182 /// base address to use for accessing globals into a register.
1184 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1185 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1186 if (!GlobalBaseReg) {
1187 // Insert the set of GlobalBaseReg into the first MBB of the function
1188 MachineFunction *MF = BB->getParent();
1189 MachineBasicBlock &FirstMBB = MF->front();
1190 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1191 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1192 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1194 const TargetInstrInfo *TII = TM.getInstrInfo();
1195 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1196 // only used in JIT code emission as displacement to pc.
1197 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1199 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1200 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1201 if (TM.getRelocationModel() == Reloc::PIC_ &&
1202 Subtarget->isPICStyleGOT()) {
1203 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1204 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1205 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1211 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1214 static SDNode *FindCallStartFromCall(SDNode *Node) {
1215 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1216 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1217 "Node doesn't have a token chain argument!");
1218 return FindCallStartFromCall(Node->getOperand(0).getNode());
1221 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1222 /// truncate of the specified operand to i8. This can be done with tablegen,
1223 /// except that this code uses MVT::Flag in a tricky way that happens to
1224 /// improve scheduling in some cases.
1225 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1226 assert(!Subtarget->is64Bit() &&
1227 "getTruncateTo8Bit is only needed on x86-32!");
1228 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1230 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1232 MVT N0VT = N0.getValueType();
1233 switch (N0VT.getSimpleVT()) {
1234 default: assert(0 && "Unknown truncate!");
1236 Opc = X86::MOV16to16_;
1239 Opc = X86::MOV32to32_;
1243 // The use of MVT::Flag here is not strictly accurate, but it helps
1244 // scheduling in some cases.
1245 N0 = SDValue(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1246 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1247 MVT::i8, N0, SRIdx, N0.getValue(1));
1251 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1252 SDNode *Node = N.getNode();
1253 MVT NVT = Node->getValueType(0);
1255 unsigned Opcode = Node->getOpcode();
1258 DOUT << std::string(Indent, ' ') << "Selecting: ";
1259 DEBUG(Node->dump(CurDAG));
1264 if (Node->isMachineOpcode()) {
1266 DOUT << std::string(Indent-2, ' ') << "== ";
1267 DEBUG(Node->dump(CurDAG));
1271 return NULL; // Already selected.
1276 case X86ISD::GlobalBaseReg:
1277 return getGlobalBaseReg();
1280 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1281 // code and is matched first so to prevent it from being turned into
1283 // In 64-bit small code size mode, use LEA to take advantage of
1284 // RIP-relative addressing.
1285 if (TM.getCodeModel() != CodeModel::Small)
1287 MVT PtrVT = TLI.getPointerTy();
1288 SDValue N0 = N.getOperand(0);
1289 SDValue N1 = N.getOperand(1);
1290 if (N.getNode()->getValueType(0) == PtrVT &&
1291 N0.getOpcode() == X86ISD::Wrapper &&
1292 N1.getOpcode() == ISD::Constant) {
1293 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getZExtValue();
1295 // TODO: handle ExternalSymbolSDNode.
1296 if (GlobalAddressSDNode *G =
1297 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1298 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1299 G->getOffset() + Offset);
1300 } else if (ConstantPoolSDNode *CP =
1301 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1302 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1304 CP->getOffset()+Offset);
1308 if (Subtarget->is64Bit()) {
1309 SDValue Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1310 CurDAG->getRegister(0, PtrVT), C };
1311 return CurDAG->SelectNodeTo(N.getNode(), X86::LEA64r,
1314 return CurDAG->SelectNodeTo(N.getNode(), X86::MOV32ri, PtrVT, C);
1318 // Other cases are handled by auto-generated code.
1322 case ISD::SMUL_LOHI:
1323 case ISD::UMUL_LOHI: {
1324 SDValue N0 = Node->getOperand(0);
1325 SDValue N1 = Node->getOperand(1);
1327 bool isSigned = Opcode == ISD::SMUL_LOHI;
1329 switch (NVT.getSimpleVT()) {
1330 default: assert(0 && "Unsupported VT!");
1331 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1332 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1333 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1334 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1337 switch (NVT.getSimpleVT()) {
1338 default: assert(0 && "Unsupported VT!");
1339 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1340 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1341 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1342 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1345 unsigned LoReg, HiReg;
1346 switch (NVT.getSimpleVT()) {
1347 default: assert(0 && "Unsupported VT!");
1348 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1349 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1350 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1351 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1354 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1355 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1356 // multiplty is commmutative
1358 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1364 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1365 N0, SDValue()).getValue(1);
1368 AddToISelQueue(N1.getOperand(0));
1369 AddToISelQueue(Tmp0);
1370 AddToISelQueue(Tmp1);
1371 AddToISelQueue(Tmp2);
1372 AddToISelQueue(Tmp3);
1373 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1375 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1376 InFlag = SDValue(CNode, 1);
1377 // Update the chain.
1378 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1382 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1385 // Copy the low half of the result, if it is needed.
1386 if (!N.getValue(0).use_empty()) {
1387 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1388 LoReg, NVT, InFlag);
1389 InFlag = Result.getValue(2);
1390 ReplaceUses(N.getValue(0), Result);
1392 DOUT << std::string(Indent-2, ' ') << "=> ";
1393 DEBUG(Result.getNode()->dump(CurDAG));
1397 // Copy the high half of the result, if it is needed.
1398 if (!N.getValue(1).use_empty()) {
1400 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1401 // Prevent use of AH in a REX instruction by referencing AX instead.
1402 // Shift it down 8 bits.
1403 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1404 X86::AX, MVT::i16, InFlag);
1405 InFlag = Result.getValue(2);
1406 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1407 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1408 // Then truncate it down to i8.
1409 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1410 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1411 MVT::i8, Result, SRIdx), 0);
1413 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1414 HiReg, NVT, InFlag);
1415 InFlag = Result.getValue(2);
1417 ReplaceUses(N.getValue(1), Result);
1419 DOUT << std::string(Indent-2, ' ') << "=> ";
1420 DEBUG(Result.getNode()->dump(CurDAG));
1433 case ISD::UDIVREM: {
1434 SDValue N0 = Node->getOperand(0);
1435 SDValue N1 = Node->getOperand(1);
1437 bool isSigned = Opcode == ISD::SDIVREM;
1439 switch (NVT.getSimpleVT()) {
1440 default: assert(0 && "Unsupported VT!");
1441 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1442 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1443 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1444 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1447 switch (NVT.getSimpleVT()) {
1448 default: assert(0 && "Unsupported VT!");
1449 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1450 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1451 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1452 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1455 unsigned LoReg, HiReg;
1456 unsigned ClrOpcode, SExtOpcode;
1457 switch (NVT.getSimpleVT()) {
1458 default: assert(0 && "Unsupported VT!");
1460 LoReg = X86::AL; HiReg = X86::AH;
1462 SExtOpcode = X86::CBW;
1465 LoReg = X86::AX; HiReg = X86::DX;
1466 ClrOpcode = X86::MOV16r0;
1467 SExtOpcode = X86::CWD;
1470 LoReg = X86::EAX; HiReg = X86::EDX;
1471 ClrOpcode = X86::MOV32r0;
1472 SExtOpcode = X86::CDQ;
1475 LoReg = X86::RAX; HiReg = X86::RDX;
1476 ClrOpcode = X86::MOV64r0;
1477 SExtOpcode = X86::CQO;
1481 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1482 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1485 if (NVT == MVT::i8 && !isSigned) {
1486 // Special case for div8, just use a move with zero extension to AX to
1487 // clear the upper 8 bits (AH).
1488 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1489 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1490 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1491 AddToISelQueue(N0.getOperand(0));
1492 AddToISelQueue(Tmp0);
1493 AddToISelQueue(Tmp1);
1494 AddToISelQueue(Tmp2);
1495 AddToISelQueue(Tmp3);
1497 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1499 Chain = Move.getValue(1);
1500 ReplaceUses(N0.getValue(1), Chain);
1504 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1505 Chain = CurDAG->getEntryNode();
1507 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDValue());
1508 InFlag = Chain.getValue(1);
1512 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1513 LoReg, N0, SDValue()).getValue(1);
1515 // Sign extend the low part into the high part.
1517 SDValue(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1519 // Zero out the high part, effectively zero extending the input.
1520 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1521 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1522 ClrNode, InFlag).getValue(1);
1527 AddToISelQueue(N1.getOperand(0));
1528 AddToISelQueue(Tmp0);
1529 AddToISelQueue(Tmp1);
1530 AddToISelQueue(Tmp2);
1531 AddToISelQueue(Tmp3);
1532 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1534 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1535 InFlag = SDValue(CNode, 1);
1536 // Update the chain.
1537 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1541 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1544 // Copy the division (low) result, if it is needed.
1545 if (!N.getValue(0).use_empty()) {
1546 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1547 LoReg, NVT, InFlag);
1548 InFlag = Result.getValue(2);
1549 ReplaceUses(N.getValue(0), Result);
1551 DOUT << std::string(Indent-2, ' ') << "=> ";
1552 DEBUG(Result.getNode()->dump(CurDAG));
1556 // Copy the remainder (high) result, if it is needed.
1557 if (!N.getValue(1).use_empty()) {
1559 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1560 // Prevent use of AH in a REX instruction by referencing AX instead.
1561 // Shift it down 8 bits.
1562 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1563 X86::AX, MVT::i16, InFlag);
1564 InFlag = Result.getValue(2);
1565 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1566 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1567 // Then truncate it down to i8.
1568 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1569 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1570 MVT::i8, Result, SRIdx), 0);
1572 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1573 HiReg, NVT, InFlag);
1574 InFlag = Result.getValue(2);
1576 ReplaceUses(N.getValue(1), Result);
1578 DOUT << std::string(Indent-2, ' ') << "=> ";
1579 DEBUG(Result.getNode()->dump(CurDAG));
1591 case ISD::SIGN_EXTEND_INREG: {
1592 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1593 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1594 SDValue N0 = Node->getOperand(0);
1597 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1599 switch (NVT.getSimpleVT()) {
1600 default: assert(0 && "Unknown sign_extend_inreg!");
1602 Opc = X86::MOVSX16rr8;
1605 Opc = X86::MOVSX32rr8;
1609 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1612 DOUT << std::string(Indent-2, ' ') << "=> ";
1613 DEBUG(TruncOp.getNode()->dump(CurDAG));
1615 DOUT << std::string(Indent-2, ' ') << "=> ";
1616 DEBUG(ResNode->dump(CurDAG));
1625 case ISD::TRUNCATE: {
1626 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1627 SDValue Input = Node->getOperand(0);
1628 AddToISelQueue(Node->getOperand(0));
1629 SDNode *ResNode = getTruncateTo8Bit(Input);
1632 DOUT << std::string(Indent-2, ' ') << "=> ";
1633 DEBUG(ResNode->dump(CurDAG));
1642 case ISD::DECLARE: {
1643 // Handle DECLARE nodes here because the second operand may have been
1644 // wrapped in X86ISD::Wrapper.
1645 SDValue Chain = Node->getOperand(0);
1646 SDValue N1 = Node->getOperand(1);
1647 SDValue N2 = Node->getOperand(2);
1648 if (!isa<FrameIndexSDNode>(N1))
1650 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1651 if (N2.getOpcode() == ISD::ADD &&
1652 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1653 N2 = N2.getOperand(1);
1654 if (N2.getOpcode() == X86ISD::Wrapper &&
1655 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
1657 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1658 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1659 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1660 AddToISelQueue(Chain);
1661 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1662 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1663 MVT::Other, Ops, 3);
1669 SDNode *ResNode = SelectCode(N);
1672 DOUT << std::string(Indent-2, ' ') << "=> ";
1673 if (ResNode == NULL || ResNode == N.getNode())
1674 DEBUG(N.getNode()->dump(CurDAG));
1676 DEBUG(ResNode->dump(CurDAG));
1684 bool X86DAGToDAGISel::
1685 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1686 std::vector<SDValue> &OutOps) {
1687 SDValue Op0, Op1, Op2, Op3;
1688 switch (ConstraintCode) {
1689 case 'o': // offsetable ??
1690 case 'v': // not offsetable ??
1691 default: return true;
1693 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1698 OutOps.push_back(Op0);
1699 OutOps.push_back(Op1);
1700 OutOps.push_back(Op2);
1701 OutOps.push_back(Op3);
1702 AddToISelQueue(Op0);
1703 AddToISelQueue(Op1);
1704 AddToISelQueue(Op2);
1705 AddToISelQueue(Op3);
1709 /// createX86ISelDag - This pass converts a legalized DAG into a
1710 /// X86-specific DAG, ready for instruction scheduling.
1712 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1713 return new X86DAGToDAGISel(TM, Fast);