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";
83 cerr << "Base.Reg "; if (Base.Reg.Val!=0) Base.Reg.Val->dump();
85 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
86 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
87 cerr << "IndexReg "; if (IndexReg.Val!=0) IndexReg.Val->dump();
89 cerr << " Disp " << Disp << "\n";
90 cerr << "GV "; if (GV) GV->dump();
92 cerr << " CP "; if (CP) CP->dump();
95 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
96 cerr << " JT" << JT << " Align" << Align << "\n";
102 //===--------------------------------------------------------------------===//
103 /// ISel - X86 specific code to select X86 machine instructions for
104 /// SelectionDAG operations.
106 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
107 /// ContainsFPCode - Every instruction we select that uses or defines a FP
108 /// register should set this to true.
111 /// TM - Keep a reference to X86TargetMachine.
113 X86TargetMachine &TM;
115 /// X86Lowering - This object fully describes how to lower LLVM code to an
116 /// X86-specific SelectionDAG.
117 X86TargetLowering X86Lowering;
119 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
120 /// make the right decision when generating code for different targets.
121 const X86Subtarget *Subtarget;
123 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
125 unsigned GlobalBaseReg;
127 /// CurBB - Current BB being isel'd.
129 MachineBasicBlock *CurBB;
132 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
133 : SelectionDAGISel(X86Lowering, fast),
134 ContainsFPCode(false), TM(tm),
135 X86Lowering(*TM.getTargetLowering()),
136 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
138 virtual bool runOnFunction(Function &Fn) {
139 // Make sure we re-emit a set of the global base reg if necessary
141 return SelectionDAGISel::runOnFunction(Fn);
144 virtual const char *getPassName() const {
145 return "X86 DAG->DAG Instruction Selection";
148 /// InstructionSelect - This callback is invoked by
149 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
150 virtual void InstructionSelect();
152 /// InstructionSelectPostProcessing - Post processing of selected and
153 /// scheduled basic blocks.
154 virtual void InstructionSelectPostProcessing();
156 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
158 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
160 // Include the pieces autogenerated from the target description.
161 #include "X86GenDAGISel.inc"
164 SDNode *Select(SDValue N);
166 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
167 bool isRoot = true, unsigned Depth = 0);
168 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
169 bool isRoot, unsigned Depth);
170 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
171 SDValue &Scale, SDValue &Index, SDValue &Disp);
172 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
173 SDValue &Scale, SDValue &Index, SDValue &Disp);
174 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
175 SDValue N, SDValue &Base, SDValue &Scale,
176 SDValue &Index, SDValue &Disp,
177 SDValue &InChain, SDValue &OutChain);
178 bool TryFoldLoad(SDValue P, SDValue N,
179 SDValue &Base, SDValue &Scale,
180 SDValue &Index, SDValue &Disp);
181 void PreprocessForRMW();
182 void PreprocessForFPConvert();
184 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
185 /// inline asm expressions.
186 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
188 std::vector<SDValue> &OutOps);
190 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
192 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
193 SDValue &Scale, SDValue &Index,
195 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
196 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
198 Scale = getI8Imm(AM.Scale);
200 // These are 32-bit even in 64-bit mode since RIP relative offset
203 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
205 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
207 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
208 else if (AM.JT != -1)
209 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
211 Disp = getI32Imm(AM.Disp);
214 /// getI8Imm - Return a target constant with the specified value, of type
216 inline SDValue getI8Imm(unsigned Imm) {
217 return CurDAG->getTargetConstant(Imm, MVT::i8);
220 /// getI16Imm - Return a target constant with the specified value, of type
222 inline SDValue getI16Imm(unsigned Imm) {
223 return CurDAG->getTargetConstant(Imm, MVT::i16);
226 /// getI32Imm - Return a target constant with the specified value, of type
228 inline SDValue getI32Imm(unsigned Imm) {
229 return CurDAG->getTargetConstant(Imm, MVT::i32);
232 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
233 /// base register. Return the virtual register that holds this value.
234 SDNode *getGlobalBaseReg();
236 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
237 /// truncate of the specified operand to i8. This can be done with tablegen,
238 /// except that this code uses MVT::Flag in a tricky way that happens to
239 /// improve scheduling in some cases.
240 SDNode *getTruncateTo8Bit(SDValue N0);
248 /// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
250 static SDNode *findFlagUse(SDNode *N) {
251 unsigned FlagResNo = N->getNumValues()-1;
252 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
254 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
255 SDValue Op = User->getOperand(i);
256 if (Op.Val == N && Op.ResNo == FlagResNo)
263 /// findNonImmUse - Return true by reference in "found" if "Use" is an
264 /// non-immediate use of "Def". This function recursively traversing
265 /// up the operand chain ignoring certain nodes.
266 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
267 SDNode *Root, SDNode *Skip, bool &found,
268 SmallPtrSet<SDNode*, 16> &Visited) {
270 Use->getNodeId() > Def->getNodeId() ||
271 !Visited.insert(Use))
274 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
275 SDNode *N = Use->getOperand(i).Val;
280 continue; // We are not looking for immediate use.
282 // Must be a chain reading node where it is possible to reach its own
283 // chain operand through a path started from another operand.
284 assert(Use->getOpcode() == ISD::STORE ||
285 Use->getOpcode() == X86ISD::CMP ||
286 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
287 Use->getOpcode() == ISD::INTRINSIC_VOID);
294 // Traverse up the operand chain.
295 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
299 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
300 /// be reached. Return true if that's the case. However, ignore direct uses
301 /// by ImmedUse (which would be U in the example illustrated in
302 /// CanBeFoldedBy) and by Root (which can happen in the store case).
303 /// FIXME: to be really generic, we should allow direct use by any node
304 /// that is being folded. But realisticly since we only fold loads which
305 /// have one non-chain use, we only need to watch out for load/op/store
306 /// and load/op/cmp case where the root (store / cmp) may reach the load via
307 /// its chain operand.
308 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
309 SDNode *Skip = NULL) {
310 SmallPtrSet<SDNode*, 16> Visited;
312 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
317 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
318 if (Fast) return false;
320 // If U use can somehow reach N through another path then U can't fold N or
321 // it will create a cycle. e.g. In the following diagram, U can reach N
322 // through X. If N is folded into into U, then X is both a predecessor and
333 if (isNonImmUse(Root, N, U))
336 // If U produces a flag, then it gets (even more) interesting. Since it
337 // would have been "glued" together with its flag use, we need to check if
350 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
351 // NU), then TF is a predecessor of FU and a successor of NU. But since
352 // NU and FU are flagged together, this effectively creates a cycle.
353 bool HasFlagUse = false;
354 MVT VT = Root->getValueType(Root->getNumValues()-1);
355 while ((VT == MVT::Flag && !Root->use_empty())) {
356 SDNode *FU = findFlagUse(Root);
363 VT = Root->getValueType(Root->getNumValues()-1);
367 return !isNonImmUse(Root, N, Root, U);
371 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
372 /// and move load below the TokenFactor. Replace store's chain operand with
373 /// load's chain result.
374 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
375 SDValue Store, SDValue TF) {
376 SmallVector<SDValue, 4> Ops;
377 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
378 if (Load.Val == TF.getOperand(i).Val)
379 Ops.push_back(Load.getOperand(0));
381 Ops.push_back(TF.getOperand(i));
382 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
383 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
384 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
385 Store.getOperand(2), Store.getOperand(3));
388 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
390 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
392 if (N.getOpcode() == ISD::BIT_CONVERT)
395 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
396 if (!LD || LD->isVolatile())
398 if (LD->getAddressingMode() != ISD::UNINDEXED)
401 ISD::LoadExtType ExtType = LD->getExtensionType();
402 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
406 N.getOperand(1) == Address &&
407 N.Val->isOperandOf(Chain.Val)) {
414 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
415 /// operand and move load below the call's chain operand.
416 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
417 SDValue Call, SDValue Chain) {
418 SmallVector<SDValue, 8> Ops;
419 for (unsigned i = 0, e = Chain.Val->getNumOperands(); i != e; ++i)
420 if (Load.Val == Chain.getOperand(i).Val)
421 Ops.push_back(Load.getOperand(0));
423 Ops.push_back(Chain.getOperand(i));
424 CurDAG->UpdateNodeOperands(Chain, &Ops[0], Ops.size());
425 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
426 Load.getOperand(1), Load.getOperand(2));
428 Ops.push_back(SDValue(Load.Val, 1));
429 for (unsigned i = 1, e = Call.Val->getNumOperands(); i != e; ++i)
430 Ops.push_back(Call.getOperand(i));
431 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
434 /// isCalleeLoad - Return true if call address is a load and it can be
435 /// moved below CALLSEQ_START and the chains leading up to the call.
436 /// Return the CALLSEQ_START by reference as a second output.
437 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
438 if (Callee.Val == Chain.Val || !Callee.hasOneUse())
440 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.Val);
443 LD->getAddressingMode() != ISD::UNINDEXED ||
444 LD->getExtensionType() != ISD::NON_EXTLOAD)
447 // Now let's find the callseq_start.
448 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
449 if (!Chain.hasOneUse())
451 Chain = Chain.getOperand(0);
453 return Chain.getOperand(0).Val == Callee.Val;
457 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
458 /// This is only run if not in -fast mode (aka -O0).
459 /// This allows the instruction selector to pick more read-modify-write
460 /// instructions. This is a common case:
470 /// [TokenFactor] [Op]
477 /// The fact the store's chain operand != load's chain will prevent the
478 /// (store (op (load))) instruction from being selected. We can transform it to:
497 void X86DAGToDAGISel::PreprocessForRMW() {
498 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
499 E = CurDAG->allnodes_end(); I != E; ++I) {
500 if (I->getOpcode() == X86ISD::CALL) {
501 /// Also try moving call address load from outside callseq_start to just
502 /// before the call to allow it to be folded.
520 SDValue Chain = I->getOperand(0);
521 SDValue Load = I->getOperand(1);
522 if (!isCalleeLoad(Load, Chain))
524 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
529 if (!ISD::isNON_TRUNCStore(I))
531 SDValue Chain = I->getOperand(0);
533 if (Chain.Val->getOpcode() != ISD::TokenFactor)
536 SDValue N1 = I->getOperand(1);
537 SDValue N2 = I->getOperand(2);
538 if ((N1.getValueType().isFloatingPoint() &&
539 !N1.getValueType().isVector()) ||
545 unsigned Opcode = N1.Val->getOpcode();
554 case ISD::VECTOR_SHUFFLE: {
555 SDValue N10 = N1.getOperand(0);
556 SDValue N11 = N1.getOperand(1);
557 RModW = isRMWLoad(N10, Chain, N2, Load);
559 RModW = isRMWLoad(N11, Chain, N2, Load);
572 SDValue N10 = N1.getOperand(0);
573 RModW = isRMWLoad(N10, Chain, N2, Load);
579 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
586 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
587 /// nodes that target the FP stack to be store and load to the stack. This is a
588 /// gross hack. We would like to simply mark these as being illegal, but when
589 /// we do that, legalize produces these when it expands calls, then expands
590 /// these in the same legalize pass. We would like dag combine to be able to
591 /// hack on these between the call expansion and the node legalization. As such
592 /// this pass basically does "really late" legalization of these inline with the
594 void X86DAGToDAGISel::PreprocessForFPConvert() {
595 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
596 E = CurDAG->allnodes_end(); I != E; ) {
597 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
598 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
601 // If the source and destination are SSE registers, then this is a legal
602 // conversion that should not be lowered.
603 MVT SrcVT = N->getOperand(0).getValueType();
604 MVT DstVT = N->getValueType(0);
605 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
606 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
607 if (SrcIsSSE && DstIsSSE)
610 if (!SrcIsSSE && !DstIsSSE) {
611 // If this is an FPStack extension, it is a noop.
612 if (N->getOpcode() == ISD::FP_EXTEND)
614 // If this is a value-preserving FPStack truncation, it is a noop.
615 if (N->getConstantOperandVal(1))
619 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
620 // FPStack has extload and truncstore. SSE can fold direct loads into other
621 // operations. Based on this, decide what we want to do.
623 if (N->getOpcode() == ISD::FP_ROUND)
624 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
626 MemVT = SrcIsSSE ? SrcVT : DstVT;
628 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
630 // FIXME: optimize the case where the src/dest is a load or store?
631 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(),
633 MemTmp, NULL, 0, MemVT);
634 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
637 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
638 // extload we created. This will cause general havok on the dag because
639 // anything below the conversion could be folded into other existing nodes.
640 // To avoid invalidating 'I', back it up to the convert node.
642 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
644 // Now that we did that, the node is dead. Increment the iterator to the
645 // next node to process, then delete N.
647 CurDAG->DeleteNode(N);
651 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
652 /// when it has created a SelectionDAG for us to codegen.
653 void X86DAGToDAGISel::InstructionSelect() {
654 CurBB = BB; // BB can change as result of isel.
660 // FIXME: This should only happen when not -fast.
661 PreprocessForFPConvert();
663 // Codegen the basic block.
665 DOUT << "===== Instruction selection begins:\n";
670 DOUT << "===== Instruction selection ends:\n";
673 CurDAG->RemoveDeadNodes();
676 void X86DAGToDAGISel::InstructionSelectPostProcessing() {
677 // If we are emitting FP stack code, scan the basic block to determine if this
678 // block defines any FP values. If so, put an FP_REG_KILL instruction before
679 // the terminator of the block.
681 // Note that FP stack instructions are used in all modes for long double,
682 // so we always need to do this check.
683 // Also note that it's possible for an FP stack register to be live across
684 // an instruction that produces multiple basic blocks (SSE CMOV) so we
685 // must check all the generated basic blocks.
687 // Scan all of the machine instructions in these MBBs, checking for FP
688 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
689 MachineFunction::iterator MBBI = CurBB;
690 MachineFunction::iterator EndMBB = BB; ++EndMBB;
691 for (; MBBI != EndMBB; ++MBBI) {
692 MachineBasicBlock *MBB = MBBI;
694 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
695 // before the return.
697 MachineBasicBlock::iterator EndI = MBB->end();
699 if (EndI->getDesc().isReturn())
703 bool ContainsFPCode = false;
704 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
705 !ContainsFPCode && I != E; ++I) {
706 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
707 const TargetRegisterClass *clas;
708 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
709 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
710 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
711 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
712 X86::RFP32RegisterClass ||
713 clas == X86::RFP64RegisterClass ||
714 clas == X86::RFP80RegisterClass)) {
715 ContainsFPCode = true;
721 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
722 // a copy of the input value in this block. In SSE mode, we only care about
724 if (!ContainsFPCode) {
725 // Final check, check LLVM BB's that are successors to the LLVM BB
726 // corresponding to BB for FP PHI nodes.
727 const BasicBlock *LLVMBB = BB->getBasicBlock();
729 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
730 !ContainsFPCode && SI != E; ++SI) {
731 for (BasicBlock::const_iterator II = SI->begin();
732 (PN = dyn_cast<PHINode>(II)); ++II) {
733 if (PN->getType()==Type::X86_FP80Ty ||
734 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
735 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
736 ContainsFPCode = true;
742 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
743 if (ContainsFPCode) {
744 BuildMI(*MBB, MBBI->getFirstTerminator(),
745 TM.getInstrInfo()->get(X86::FP_REG_KILL));
751 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
752 /// the main function.
753 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
754 MachineFrameInfo *MFI) {
755 const TargetInstrInfo *TII = TM.getInstrInfo();
756 if (Subtarget->isTargetCygMing())
757 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
760 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
761 // If this is main, emit special code for main.
762 MachineBasicBlock *BB = MF.begin();
763 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
764 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
767 /// MatchAddress - Add the specified node to the specified addressing mode,
768 /// returning true if it cannot be done. This just pattern matches for the
770 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
771 bool isRoot, unsigned Depth) {
772 DOUT << "MatchAddress: "; DEBUG(AM.dump());
775 return MatchAddressBase(N, AM, isRoot, Depth);
777 // RIP relative addressing: %rip + 32-bit displacement!
779 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
780 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
781 if (isInt32(AM.Disp + Val)) {
789 int id = N.Val->getNodeId();
790 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
792 switch (N.getOpcode()) {
794 case ISD::Constant: {
795 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
796 if (isInt32(AM.Disp + Val)) {
803 case X86ISD::Wrapper: {
804 DOUT << "Wrapper: 64bit " << Subtarget->is64Bit();
805 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
806 DOUT << "AlreadySelected " << AlreadySelected << "\n";
807 bool is64Bit = Subtarget->is64Bit();
808 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
809 // Also, base and index reg must be 0 in order to use rip as base.
810 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
811 AM.Base.Reg.Val || AM.IndexReg.Val))
813 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
815 // If value is available in a register both base and index components have
816 // been picked, we can't fit the result available in the register in the
817 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
818 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
819 SDValue N0 = N.getOperand(0);
820 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
821 GlobalValue *GV = G->getGlobal();
823 AM.Disp += G->getOffset();
824 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
825 Subtarget->isPICStyleRIPRel();
827 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
828 AM.CP = CP->getConstVal();
829 AM.Align = CP->getAlignment();
830 AM.Disp += CP->getOffset();
831 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
832 Subtarget->isPICStyleRIPRel();
834 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
835 AM.ES = S->getSymbol();
836 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
837 Subtarget->isPICStyleRIPRel();
839 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
840 AM.JT = J->getIndex();
841 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
842 Subtarget->isPICStyleRIPRel();
849 case ISD::FrameIndex:
850 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
851 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
852 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
858 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
861 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
862 unsigned Val = CN->getValue();
863 if (Val == 1 || Val == 2 || Val == 3) {
865 SDValue ShVal = N.Val->getOperand(0);
867 // Okay, we know that we have a scale by now. However, if the scaled
868 // value is an add of something and a constant, we can fold the
869 // constant into the disp field here.
870 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
871 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
872 AM.IndexReg = ShVal.Val->getOperand(0);
873 ConstantSDNode *AddVal =
874 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
875 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
890 // A mul_lohi where we need the low part can be folded as a plain multiply.
891 if (N.ResNo != 0) break;
894 // X*[3,5,9] -> X+X*[2,4,8]
895 if (!AlreadySelected &&
896 AM.BaseType == X86ISelAddressMode::RegBase &&
897 AM.Base.Reg.Val == 0 &&
898 AM.IndexReg.Val == 0 &&
900 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
901 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
902 AM.Scale = unsigned(CN->getValue())-1;
904 SDValue MulVal = N.Val->getOperand(0);
907 // Okay, we know that we have a scale by now. However, if the scaled
908 // value is an add of something and a constant, we can fold the
909 // constant into the disp field here.
910 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
911 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
912 Reg = MulVal.Val->getOperand(0);
913 ConstantSDNode *AddVal =
914 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
915 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
919 Reg = N.Val->getOperand(0);
921 Reg = N.Val->getOperand(0);
924 AM.IndexReg = AM.Base.Reg = Reg;
931 if (!AlreadySelected) {
932 X86ISelAddressMode Backup = AM;
933 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
934 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
937 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
938 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
945 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
946 if (AlreadySelected) break;
948 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
949 X86ISelAddressMode Backup = AM;
950 // Start with the LHS as an addr mode.
951 if (!MatchAddress(N.getOperand(0), AM, false) &&
952 // Address could not have picked a GV address for the displacement.
954 // On x86-64, the resultant disp must fit in 32-bits.
955 isInt32(AM.Disp + CN->getSignExtended()) &&
956 // Check to see if the LHS & C is zero.
957 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
958 AM.Disp += CN->getValue();
966 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
967 // allows us to fold the shift into this addressing mode.
968 if (AlreadySelected) break;
969 SDValue Shift = N.getOperand(0);
970 if (Shift.getOpcode() != ISD::SHL) break;
972 // Scale must not be used already.
973 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
975 // Not when RIP is used as the base.
976 if (AM.isRIPRel) break;
978 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
979 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
980 if (!C1 || !C2) break;
982 // Not likely to be profitable if either the AND or SHIFT node has more
983 // than one use (unless all uses are for address computation). Besides,
984 // isel mechanism requires their node ids to be reused.
985 if (!N.hasOneUse() || !Shift.hasOneUse())
988 // Verify that the shift amount is something we can fold.
989 unsigned ShiftCst = C1->getValue();
990 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
993 // Get the new AND mask, this folds to a constant.
994 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
995 SDValue(C2, 0), SDValue(C1, 0));
996 SDValue NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
997 Shift.getOperand(0), NewANDMask);
998 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
999 NewAND.Val->setNodeId(N.Val->getNodeId());
1001 AM.Scale = 1 << ShiftCst;
1002 AM.IndexReg = NewAND;
1007 return MatchAddressBase(N, AM, isRoot, Depth);
1010 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1011 /// specified addressing mode without any further recursion.
1012 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
1013 bool isRoot, unsigned Depth) {
1014 // Is the base register already occupied?
1015 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
1016 // If so, check to see if the scale index register is set.
1017 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
1023 // Otherwise, we cannot select it.
1027 // Default, generate it as a register.
1028 AM.BaseType = X86ISelAddressMode::RegBase;
1033 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1034 /// It returns the operands which make up the maximal addressing mode it can
1035 /// match by reference.
1036 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1037 SDValue &Scale, SDValue &Index,
1039 X86ISelAddressMode AM;
1040 if (MatchAddress(N, AM))
1043 MVT VT = N.getValueType();
1044 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1045 if (!AM.Base.Reg.Val)
1046 AM.Base.Reg = CurDAG->getRegister(0, VT);
1049 if (!AM.IndexReg.Val)
1050 AM.IndexReg = CurDAG->getRegister(0, VT);
1052 getAddressOperands(AM, Base, Scale, Index, Disp);
1056 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
1058 static inline bool isZeroNode(SDValue Elt) {
1059 return ((isa<ConstantSDNode>(Elt) &&
1060 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
1061 (isa<ConstantFPSDNode>(Elt) &&
1062 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
1066 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1067 /// match a load whose top elements are either undef or zeros. The load flavor
1068 /// is derived from the type of N, which is either v4f32 or v2f64.
1069 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1070 SDValue N, SDValue &Base,
1071 SDValue &Scale, SDValue &Index,
1072 SDValue &Disp, SDValue &InChain,
1073 SDValue &OutChain) {
1074 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1075 InChain = N.getOperand(0).getValue(1);
1076 if (ISD::isNON_EXTLoad(InChain.Val) &&
1077 InChain.getValue(0).hasOneUse() &&
1079 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
1080 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1081 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1083 OutChain = LD->getChain();
1088 // Also handle the case where we explicitly require zeros in the top
1089 // elements. This is a vector shuffle from the zero vector.
1090 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
1091 // Check to see if the top elements are all zeros (or bitcast of zeros).
1092 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1093 N.getOperand(0).Val->hasOneUse() &&
1094 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
1095 N.getOperand(0).getOperand(0).hasOneUse()) {
1096 // Okay, this is a zero extending load. Fold it.
1097 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1098 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1100 OutChain = LD->getChain();
1101 InChain = SDValue(LD, 1);
1108 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1109 /// mode it matches can be cost effectively emitted as an LEA instruction.
1110 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1111 SDValue &Base, SDValue &Scale,
1112 SDValue &Index, SDValue &Disp) {
1113 X86ISelAddressMode AM;
1114 if (MatchAddress(N, AM))
1117 MVT VT = N.getValueType();
1118 unsigned Complexity = 0;
1119 if (AM.BaseType == X86ISelAddressMode::RegBase)
1120 if (AM.Base.Reg.Val)
1123 AM.Base.Reg = CurDAG->getRegister(0, VT);
1124 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1127 if (AM.IndexReg.Val)
1130 AM.IndexReg = CurDAG->getRegister(0, VT);
1132 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1137 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1138 // to a LEA. This is determined with some expermentation but is by no means
1139 // optimal (especially for code size consideration). LEA is nice because of
1140 // its three-address nature. Tweak the cost function again when we can run
1141 // convertToThreeAddress() at register allocation time.
1142 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1143 // For X86-64, we should always use lea to materialize RIP relative
1145 if (Subtarget->is64Bit())
1151 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1154 if (Complexity > 2) {
1155 getAddressOperands(AM, Base, Scale, Index, Disp);
1161 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1162 SDValue &Base, SDValue &Scale,
1163 SDValue &Index, SDValue &Disp) {
1164 if (ISD::isNON_EXTLoad(N.Val) &&
1166 CanBeFoldedBy(N.Val, P.Val, P.Val))
1167 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1171 /// getGlobalBaseReg - Output the instructions required to put the
1172 /// base address to use for accessing globals into a register.
1174 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1175 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1176 if (!GlobalBaseReg) {
1177 // Insert the set of GlobalBaseReg into the first MBB of the function
1178 MachineFunction *MF = BB->getParent();
1179 MachineBasicBlock &FirstMBB = MF->front();
1180 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1181 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1182 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1184 const TargetInstrInfo *TII = TM.getInstrInfo();
1185 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1186 // only used in JIT code emission as displacement to pc.
1187 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1189 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1190 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1191 if (TM.getRelocationModel() == Reloc::PIC_ &&
1192 Subtarget->isPICStyleGOT()) {
1193 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1194 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1195 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1201 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1204 static SDNode *FindCallStartFromCall(SDNode *Node) {
1205 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1206 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1207 "Node doesn't have a token chain argument!");
1208 return FindCallStartFromCall(Node->getOperand(0).Val);
1211 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1212 /// truncate of the specified operand to i8. This can be done with tablegen,
1213 /// except that this code uses MVT::Flag in a tricky way that happens to
1214 /// improve scheduling in some cases.
1215 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1216 assert(!Subtarget->is64Bit() &&
1217 "getTruncateTo8Bit is only needed on x86-32!");
1218 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1220 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1222 MVT N0VT = N0.getValueType();
1223 switch (N0VT.getSimpleVT()) {
1224 default: assert(0 && "Unknown truncate!");
1226 Opc = X86::MOV16to16_;
1229 Opc = X86::MOV32to32_;
1233 // The use of MVT::Flag here is not strictly accurate, but it helps
1234 // scheduling in some cases.
1235 N0 = SDValue(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1236 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1237 MVT::i8, N0, SRIdx, N0.getValue(1));
1241 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1242 SDNode *Node = N.Val;
1243 MVT NVT = Node->getValueType(0);
1245 unsigned Opcode = Node->getOpcode();
1248 DOUT << std::string(Indent, ' ') << "Selecting: ";
1249 DEBUG(Node->dump(CurDAG));
1254 if (Node->isMachineOpcode()) {
1256 DOUT << std::string(Indent-2, ' ') << "== ";
1257 DEBUG(Node->dump(CurDAG));
1261 return NULL; // Already selected.
1266 case X86ISD::GlobalBaseReg:
1267 return getGlobalBaseReg();
1270 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1271 // code and is matched first so to prevent it from being turned into
1273 // In 64-bit small code size mode, use LEA to take advantage of
1274 // RIP-relative addressing.
1275 if (TM.getCodeModel() != CodeModel::Small)
1277 MVT PtrVT = TLI.getPointerTy();
1278 SDValue N0 = N.getOperand(0);
1279 SDValue N1 = N.getOperand(1);
1280 if (N.Val->getValueType(0) == PtrVT &&
1281 N0.getOpcode() == X86ISD::Wrapper &&
1282 N1.getOpcode() == ISD::Constant) {
1283 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1285 // TODO: handle ExternalSymbolSDNode.
1286 if (GlobalAddressSDNode *G =
1287 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1288 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1289 G->getOffset() + Offset);
1290 } else if (ConstantPoolSDNode *CP =
1291 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1292 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1294 CP->getOffset()+Offset);
1298 if (Subtarget->is64Bit()) {
1299 SDValue Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1300 CurDAG->getRegister(0, PtrVT), C };
1301 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1303 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1307 // Other cases are handled by auto-generated code.
1311 case ISD::SMUL_LOHI:
1312 case ISD::UMUL_LOHI: {
1313 SDValue N0 = Node->getOperand(0);
1314 SDValue N1 = Node->getOperand(1);
1316 bool isSigned = Opcode == ISD::SMUL_LOHI;
1318 switch (NVT.getSimpleVT()) {
1319 default: assert(0 && "Unsupported VT!");
1320 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1321 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1322 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1323 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1326 switch (NVT.getSimpleVT()) {
1327 default: assert(0 && "Unsupported VT!");
1328 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1329 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1330 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1331 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1334 unsigned LoReg, HiReg;
1335 switch (NVT.getSimpleVT()) {
1336 default: assert(0 && "Unsupported VT!");
1337 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1338 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1339 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1340 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1343 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1344 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1345 // multiplty is commmutative
1347 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1353 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1354 N0, SDValue()).getValue(1);
1357 AddToISelQueue(N1.getOperand(0));
1358 AddToISelQueue(Tmp0);
1359 AddToISelQueue(Tmp1);
1360 AddToISelQueue(Tmp2);
1361 AddToISelQueue(Tmp3);
1362 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1364 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1365 InFlag = SDValue(CNode, 1);
1366 // Update the chain.
1367 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1371 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1374 // Copy the low half of the result, if it is needed.
1375 if (!N.getValue(0).use_empty()) {
1376 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1377 LoReg, NVT, InFlag);
1378 InFlag = Result.getValue(2);
1379 ReplaceUses(N.getValue(0), Result);
1381 DOUT << std::string(Indent-2, ' ') << "=> ";
1382 DEBUG(Result.Val->dump(CurDAG));
1386 // Copy the high half of the result, if it is needed.
1387 if (!N.getValue(1).use_empty()) {
1389 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1390 // Prevent use of AH in a REX instruction by referencing AX instead.
1391 // Shift it down 8 bits.
1392 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1393 X86::AX, MVT::i16, InFlag);
1394 InFlag = Result.getValue(2);
1395 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1396 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1397 // Then truncate it down to i8.
1398 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1399 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1400 MVT::i8, Result, SRIdx), 0);
1402 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1403 HiReg, NVT, InFlag);
1404 InFlag = Result.getValue(2);
1406 ReplaceUses(N.getValue(1), Result);
1408 DOUT << std::string(Indent-2, ' ') << "=> ";
1409 DEBUG(Result.Val->dump(CurDAG));
1422 case ISD::UDIVREM: {
1423 SDValue N0 = Node->getOperand(0);
1424 SDValue N1 = Node->getOperand(1);
1426 bool isSigned = Opcode == ISD::SDIVREM;
1428 switch (NVT.getSimpleVT()) {
1429 default: assert(0 && "Unsupported VT!");
1430 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1431 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1432 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1433 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1436 switch (NVT.getSimpleVT()) {
1437 default: assert(0 && "Unsupported VT!");
1438 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1439 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1440 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1441 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1444 unsigned LoReg, HiReg;
1445 unsigned ClrOpcode, SExtOpcode;
1446 switch (NVT.getSimpleVT()) {
1447 default: assert(0 && "Unsupported VT!");
1449 LoReg = X86::AL; HiReg = X86::AH;
1451 SExtOpcode = X86::CBW;
1454 LoReg = X86::AX; HiReg = X86::DX;
1455 ClrOpcode = X86::MOV16r0;
1456 SExtOpcode = X86::CWD;
1459 LoReg = X86::EAX; HiReg = X86::EDX;
1460 ClrOpcode = X86::MOV32r0;
1461 SExtOpcode = X86::CDQ;
1464 LoReg = X86::RAX; HiReg = X86::RDX;
1465 ClrOpcode = X86::MOV64r0;
1466 SExtOpcode = X86::CQO;
1470 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1471 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1474 if (NVT == MVT::i8 && !isSigned) {
1475 // Special case for div8, just use a move with zero extension to AX to
1476 // clear the upper 8 bits (AH).
1477 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1478 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1479 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1480 AddToISelQueue(N0.getOperand(0));
1481 AddToISelQueue(Tmp0);
1482 AddToISelQueue(Tmp1);
1483 AddToISelQueue(Tmp2);
1484 AddToISelQueue(Tmp3);
1486 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1488 Chain = Move.getValue(1);
1489 ReplaceUses(N0.getValue(1), Chain);
1493 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1494 Chain = CurDAG->getEntryNode();
1496 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDValue());
1497 InFlag = Chain.getValue(1);
1501 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1502 LoReg, N0, SDValue()).getValue(1);
1504 // Sign extend the low part into the high part.
1506 SDValue(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1508 // Zero out the high part, effectively zero extending the input.
1509 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1510 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1511 ClrNode, InFlag).getValue(1);
1516 AddToISelQueue(N1.getOperand(0));
1517 AddToISelQueue(Tmp0);
1518 AddToISelQueue(Tmp1);
1519 AddToISelQueue(Tmp2);
1520 AddToISelQueue(Tmp3);
1521 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1523 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1524 InFlag = SDValue(CNode, 1);
1525 // Update the chain.
1526 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1530 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1533 // Copy the division (low) result, if it is needed.
1534 if (!N.getValue(0).use_empty()) {
1535 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1536 LoReg, NVT, InFlag);
1537 InFlag = Result.getValue(2);
1538 ReplaceUses(N.getValue(0), Result);
1540 DOUT << std::string(Indent-2, ' ') << "=> ";
1541 DEBUG(Result.Val->dump(CurDAG));
1545 // Copy the remainder (high) result, if it is needed.
1546 if (!N.getValue(1).use_empty()) {
1548 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1549 // Prevent use of AH in a REX instruction by referencing AX instead.
1550 // Shift it down 8 bits.
1551 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1552 X86::AX, MVT::i16, InFlag);
1553 InFlag = Result.getValue(2);
1554 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1555 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1556 // Then truncate it down to i8.
1557 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1558 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1559 MVT::i8, Result, SRIdx), 0);
1561 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1562 HiReg, NVT, InFlag);
1563 InFlag = Result.getValue(2);
1565 ReplaceUses(N.getValue(1), Result);
1567 DOUT << std::string(Indent-2, ' ') << "=> ";
1568 DEBUG(Result.Val->dump(CurDAG));
1580 case ISD::SIGN_EXTEND_INREG: {
1581 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1582 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1583 SDValue N0 = Node->getOperand(0);
1586 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1588 switch (NVT.getSimpleVT()) {
1589 default: assert(0 && "Unknown sign_extend_inreg!");
1591 Opc = X86::MOVSX16rr8;
1594 Opc = X86::MOVSX32rr8;
1598 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1601 DOUT << std::string(Indent-2, ' ') << "=> ";
1602 DEBUG(TruncOp.Val->dump(CurDAG));
1604 DOUT << std::string(Indent-2, ' ') << "=> ";
1605 DEBUG(ResNode->dump(CurDAG));
1614 case ISD::TRUNCATE: {
1615 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1616 SDValue Input = Node->getOperand(0);
1617 AddToISelQueue(Node->getOperand(0));
1618 SDNode *ResNode = getTruncateTo8Bit(Input);
1621 DOUT << std::string(Indent-2, ' ') << "=> ";
1622 DEBUG(ResNode->dump(CurDAG));
1631 case ISD::DECLARE: {
1632 // Handle DECLARE nodes here because the second operand may have been
1633 // wrapped in X86ISD::Wrapper.
1634 SDValue Chain = Node->getOperand(0);
1635 SDValue N1 = Node->getOperand(1);
1636 SDValue N2 = Node->getOperand(2);
1637 if (!isa<FrameIndexSDNode>(N1))
1639 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1640 if (N2.getOpcode() == ISD::ADD &&
1641 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1642 N2 = N2.getOperand(1);
1643 if (N2.getOpcode() == X86ISD::Wrapper &&
1644 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
1646 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1647 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1648 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1649 AddToISelQueue(Chain);
1650 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1651 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1652 MVT::Other, Ops, 3);
1658 SDNode *ResNode = SelectCode(N);
1661 DOUT << std::string(Indent-2, ' ') << "=> ";
1662 if (ResNode == NULL || ResNode == N.Val)
1663 DEBUG(N.Val->dump(CurDAG));
1665 DEBUG(ResNode->dump(CurDAG));
1673 bool X86DAGToDAGISel::
1674 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1675 std::vector<SDValue> &OutOps) {
1676 SDValue Op0, Op1, Op2, Op3;
1677 switch (ConstraintCode) {
1678 case 'o': // offsetable ??
1679 case 'v': // not offsetable ??
1680 default: return true;
1682 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1687 OutOps.push_back(Op0);
1688 OutOps.push_back(Op1);
1689 OutOps.push_back(Op2);
1690 OutOps.push_back(Op3);
1691 AddToISelQueue(Op0);
1692 AddToISelQueue(Op1);
1693 AddToISelQueue(Op2);
1694 AddToISelQueue(Op3);
1698 /// createX86ISelDag - This pass converts a legalized DAG into a
1699 /// X86-specific DAG, ready for instruction scheduling.
1701 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1702 return new X86DAGToDAGISel(TM, Fast);