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/Target/TargetOptions.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Streams.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Support/CommandLine.h"
45 static cl::opt<bool> AvoidDupAddrCompute("x86-avoid-dup-address", cl::Hidden);
47 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
49 //===----------------------------------------------------------------------===//
50 // Pattern Matcher Implementation
51 //===----------------------------------------------------------------------===//
54 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
55 /// SDValue's instead of register numbers for the leaves of the matched
57 struct X86ISelAddressMode {
63 struct { // This is really a union, discriminated by BaseType!
68 bool isRIPRel; // RIP as base?
77 unsigned Align; // CP alignment.
80 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
81 Segment(), GV(0), CP(0), ES(0), JT(-1), Align(0) {
84 bool hasSymbolicDisplacement() const {
85 return GV != 0 || CP != 0 || ES != 0 || JT != -1;
89 cerr << "X86ISelAddressMode " << this << "\n";
91 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
93 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
94 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
96 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
98 cerr << " Disp " << Disp << "\n";
99 cerr << "GV "; if (GV) GV->dump();
101 cerr << " CP "; if (CP) CP->dump();
104 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
105 cerr << " JT" << JT << " Align" << Align << "\n";
111 //===--------------------------------------------------------------------===//
112 /// ISel - X86 specific code to select X86 machine instructions for
113 /// SelectionDAG operations.
115 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
116 /// TM - Keep a reference to X86TargetMachine.
118 X86TargetMachine &TM;
120 /// X86Lowering - This object fully describes how to lower LLVM code to an
121 /// X86-specific SelectionDAG.
122 X86TargetLowering &X86Lowering;
124 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
125 /// make the right decision when generating code for different targets.
126 const X86Subtarget *Subtarget;
128 /// CurBB - Current BB being isel'd.
130 MachineBasicBlock *CurBB;
132 /// OptForSize - If true, selector should try to optimize for code size
133 /// instead of performance.
137 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
138 : SelectionDAGISel(tm, fast),
139 TM(tm), X86Lowering(*TM.getTargetLowering()),
140 Subtarget(&TM.getSubtarget<X86Subtarget>()),
143 virtual const char *getPassName() const {
144 return "X86 DAG->DAG Instruction Selection";
147 /// InstructionSelect - This callback is invoked by
148 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
149 virtual void InstructionSelect();
151 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
154 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
156 // Include the pieces autogenerated from the target description.
157 #include "X86GenDAGISel.inc"
160 SDNode *Select(SDValue N);
161 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
163 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
164 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
165 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
167 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
168 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
169 SDValue &Scale, SDValue &Index, SDValue &Disp,
171 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
172 SDValue &Scale, SDValue &Index, SDValue &Disp);
173 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
174 SDValue N, SDValue &Base, SDValue &Scale,
175 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,
182 void PreprocessForRMW();
183 void PreprocessForFPConvert();
185 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
186 /// inline asm expressions.
187 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
189 std::vector<SDValue> &OutOps);
191 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
193 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
194 SDValue &Scale, SDValue &Index,
195 SDValue &Disp, SDValue &Segment) {
196 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
197 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
199 Scale = getI8Imm(AM.Scale);
201 // These are 32-bit even in 64-bit mode since RIP relative offset
204 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
206 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
209 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
210 else if (AM.JT != -1)
211 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
213 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
215 if (AM.Segment.getNode())
216 Segment = AM.Segment;
218 Segment = CurDAG->getRegister(0, MVT::i32);
221 /// getI8Imm - Return a target constant with the specified value, of type
223 inline SDValue getI8Imm(unsigned Imm) {
224 return CurDAG->getTargetConstant(Imm, MVT::i8);
227 /// getI16Imm - Return a target constant with the specified value, of type
229 inline SDValue getI16Imm(unsigned Imm) {
230 return CurDAG->getTargetConstant(Imm, MVT::i16);
233 /// getI32Imm - Return a target constant with the specified value, of type
235 inline SDValue getI32Imm(unsigned Imm) {
236 return CurDAG->getTargetConstant(Imm, MVT::i32);
239 /// getGlobalBaseReg - Return an SDNode that returns the value of
240 /// the global base register. Output instructions required to
241 /// initialize the global base register, if necessary.
243 SDNode *getGlobalBaseReg();
245 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
246 /// truncate of the specified operand to i8. This can be done with tablegen,
247 /// except that this code uses MVT::Flag in a tricky way that happens to
248 /// improve scheduling in some cases.
249 SDNode *getTruncateTo8Bit(SDValue N0);
257 /// findFlagUse - Return use of MVT::Flag value produced by the specified
260 static SDNode *findFlagUse(SDNode *N) {
261 unsigned FlagResNo = N->getNumValues()-1;
262 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
263 SDUse &Use = I.getUse();
264 if (Use.getResNo() == FlagResNo)
265 return Use.getUser();
270 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
271 /// This function recursively traverses up the operand chain, ignoring
273 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
275 SmallPtrSet<SDNode*, 16> &Visited) {
276 if (Use->getNodeId() < Def->getNodeId() ||
277 !Visited.insert(Use))
280 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
281 SDNode *N = Use->getOperand(i).getNode();
283 if (Use == ImmedUse || Use == Root)
284 continue; // We are not looking for immediate use.
289 // Traverse up the operand chain.
290 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
296 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
297 /// be reached. Return true if that's the case. However, ignore direct uses
298 /// by ImmedUse (which would be U in the example illustrated in
299 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
301 /// FIXME: to be really generic, we should allow direct use by any node
302 /// that is being folded. But realisticly since we only fold loads which
303 /// have one non-chain use, we only need to watch out for load/op/store
304 /// and load/op/cmp case where the root (store / cmp) may reach the load via
305 /// its chain operand.
306 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
307 SmallPtrSet<SDNode*, 16> Visited;
308 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
312 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
313 SDNode *Root) const {
314 if (Fast) return false;
317 switch (U->getOpcode()) {
325 // If the other operand is a 8-bit immediate we should fold the immediate
326 // instead. This reduces code size.
328 // movl 4(%esp), %eax
332 // addl 4(%esp), %eax
333 // The former is 2 bytes shorter. In case where the increment is 1, then
334 // the saving can be 4 bytes (by using incl %eax).
335 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(U->getOperand(1)))
336 if (Imm->getAPIntValue().isSignedIntN(8))
341 // If Root use can somehow reach N through a path that that doesn't contain
342 // U then folding N would create a cycle. e.g. In the following
343 // diagram, Root can reach N through X. If N is folded into into Root, then
344 // X is both a predecessor and a successor of U.
355 // * indicates nodes to be folded together.
357 // If Root produces a flag, then it gets (even more) interesting. Since it
358 // will be "glued" together with its flag use in the scheduler, we need to
359 // check if it might reach N.
378 // If FU (flag use) indirectly reaches N (the load), and Root folds N
379 // (call it Fold), then X is a predecessor of FU and a successor of
380 // Fold. But since Fold and FU are flagged together, this will create
381 // a cycle in the scheduling graph.
383 MVT VT = Root->getValueType(Root->getNumValues()-1);
384 while (VT == MVT::Flag) {
385 SDNode *FU = findFlagUse(Root);
389 VT = Root->getValueType(Root->getNumValues()-1);
392 return !isNonImmUse(Root, N, U);
395 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
396 /// and move load below the TokenFactor. Replace store's chain operand with
397 /// load's chain result.
398 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
399 SDValue Store, SDValue TF) {
400 SmallVector<SDValue, 4> Ops;
401 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
402 if (Load.getNode() == TF.getOperand(i).getNode())
403 Ops.push_back(Load.getOperand(0));
405 Ops.push_back(TF.getOperand(i));
406 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
407 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
408 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
409 Store.getOperand(2), Store.getOperand(3));
412 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
414 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
416 if (N.getOpcode() == ISD::BIT_CONVERT)
419 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
420 if (!LD || LD->isVolatile())
422 if (LD->getAddressingMode() != ISD::UNINDEXED)
425 ISD::LoadExtType ExtType = LD->getExtensionType();
426 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
430 N.getOperand(1) == Address &&
431 N.getNode()->isOperandOf(Chain.getNode())) {
438 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
439 /// operand and move load below the call's chain operand.
440 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
441 SDValue Call, SDValue CallSeqStart) {
442 SmallVector<SDValue, 8> Ops;
443 SDValue Chain = CallSeqStart.getOperand(0);
444 if (Chain.getNode() == Load.getNode())
445 Ops.push_back(Load.getOperand(0));
447 assert(Chain.getOpcode() == ISD::TokenFactor &&
448 "Unexpected CallSeqStart chain operand");
449 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
450 if (Chain.getOperand(i).getNode() == Load.getNode())
451 Ops.push_back(Load.getOperand(0));
453 Ops.push_back(Chain.getOperand(i));
455 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
456 MVT::Other, &Ops[0], Ops.size());
458 Ops.push_back(NewChain);
460 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
461 Ops.push_back(CallSeqStart.getOperand(i));
462 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
463 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
464 Load.getOperand(1), Load.getOperand(2));
466 Ops.push_back(SDValue(Load.getNode(), 1));
467 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
468 Ops.push_back(Call.getOperand(i));
469 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
472 /// isCalleeLoad - Return true if call address is a load and it can be
473 /// moved below CALLSEQ_START and the chains leading up to the call.
474 /// Return the CALLSEQ_START by reference as a second output.
475 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
476 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
478 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
481 LD->getAddressingMode() != ISD::UNINDEXED ||
482 LD->getExtensionType() != ISD::NON_EXTLOAD)
485 // Now let's find the callseq_start.
486 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
487 if (!Chain.hasOneUse())
489 Chain = Chain.getOperand(0);
492 if (Chain.getOperand(0).getNode() == Callee.getNode())
494 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
495 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
501 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
502 /// This is only run if not in -fast mode (aka -O0).
503 /// This allows the instruction selector to pick more read-modify-write
504 /// instructions. This is a common case:
514 /// [TokenFactor] [Op]
521 /// The fact the store's chain operand != load's chain will prevent the
522 /// (store (op (load))) instruction from being selected. We can transform it to:
541 void X86DAGToDAGISel::PreprocessForRMW() {
542 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
543 E = CurDAG->allnodes_end(); I != E; ++I) {
544 if (I->getOpcode() == X86ISD::CALL) {
545 /// Also try moving call address load from outside callseq_start to just
546 /// before the call to allow it to be folded.
564 SDValue Chain = I->getOperand(0);
565 SDValue Load = I->getOperand(1);
566 if (!isCalleeLoad(Load, Chain))
568 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
573 if (!ISD::isNON_TRUNCStore(I))
575 SDValue Chain = I->getOperand(0);
577 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
580 SDValue N1 = I->getOperand(1);
581 SDValue N2 = I->getOperand(2);
582 if ((N1.getValueType().isFloatingPoint() &&
583 !N1.getValueType().isVector()) ||
589 unsigned Opcode = N1.getNode()->getOpcode();
598 case ISD::VECTOR_SHUFFLE: {
599 SDValue N10 = N1.getOperand(0);
600 SDValue N11 = N1.getOperand(1);
601 RModW = isRMWLoad(N10, Chain, N2, Load);
603 RModW = isRMWLoad(N11, Chain, N2, Load);
616 SDValue N10 = N1.getOperand(0);
617 RModW = isRMWLoad(N10, Chain, N2, Load);
623 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
630 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
631 /// nodes that target the FP stack to be store and load to the stack. This is a
632 /// gross hack. We would like to simply mark these as being illegal, but when
633 /// we do that, legalize produces these when it expands calls, then expands
634 /// these in the same legalize pass. We would like dag combine to be able to
635 /// hack on these between the call expansion and the node legalization. As such
636 /// this pass basically does "really late" legalization of these inline with the
638 void X86DAGToDAGISel::PreprocessForFPConvert() {
639 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
640 E = CurDAG->allnodes_end(); I != E; ) {
641 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
642 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
645 // If the source and destination are SSE registers, then this is a legal
646 // conversion that should not be lowered.
647 MVT SrcVT = N->getOperand(0).getValueType();
648 MVT DstVT = N->getValueType(0);
649 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
650 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
651 if (SrcIsSSE && DstIsSSE)
654 if (!SrcIsSSE && !DstIsSSE) {
655 // If this is an FPStack extension, it is a noop.
656 if (N->getOpcode() == ISD::FP_EXTEND)
658 // If this is a value-preserving FPStack truncation, it is a noop.
659 if (N->getConstantOperandVal(1))
663 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
664 // FPStack has extload and truncstore. SSE can fold direct loads into other
665 // operations. Based on this, decide what we want to do.
667 if (N->getOpcode() == ISD::FP_ROUND)
668 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
670 MemVT = SrcIsSSE ? SrcVT : DstVT;
672 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
673 DebugLoc dl = N->getDebugLoc();
675 // FIXME: optimize the case where the src/dest is a load or store?
676 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
678 MemTmp, NULL, 0, MemVT);
679 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
682 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
683 // extload we created. This will cause general havok on the dag because
684 // anything below the conversion could be folded into other existing nodes.
685 // To avoid invalidating 'I', back it up to the convert node.
687 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
689 // Now that we did that, the node is dead. Increment the iterator to the
690 // next node to process, then delete N.
692 CurDAG->DeleteNode(N);
696 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
697 /// when it has created a SelectionDAG for us to codegen.
698 void X86DAGToDAGISel::InstructionSelect() {
699 CurBB = BB; // BB can change as result of isel.
700 const Function *F = CurDAG->getMachineFunction().getFunction();
701 OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
707 // FIXME: This should only happen when not -fast.
708 PreprocessForFPConvert();
710 // Codegen the basic block.
712 DOUT << "===== Instruction selection begins:\n";
717 DOUT << "===== Instruction selection ends:\n";
720 CurDAG->RemoveDeadNodes();
723 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
724 /// the main function.
725 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
726 MachineFrameInfo *MFI) {
727 const TargetInstrInfo *TII = TM.getInstrInfo();
728 if (Subtarget->isTargetCygMing())
729 BuildMI(BB, DebugLoc::getUnknownLoc(),
730 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
733 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
734 // If this is main, emit special code for main.
735 MachineBasicBlock *BB = MF.begin();
736 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
737 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
741 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
742 X86ISelAddressMode &AM) {
743 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
744 SDValue Segment = N.getOperand(0);
746 if (AM.Segment.getNode() == 0) {
747 AM.Segment = Segment;
754 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
755 // This optimization is valid because the GNU TLS model defines that
756 // gs:0 (or fs:0 on X86-64) contains its own address.
757 // For more information see http://people.redhat.com/drepper/tls.pdf
759 SDValue Address = N.getOperand(1);
760 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
761 !MatchSegmentBaseAddress (Address, AM))
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,
772 bool is64Bit = Subtarget->is64Bit();
773 DebugLoc dl = N.getDebugLoc();
774 DOUT << "MatchAddress: "; DEBUG(AM.dump());
777 return MatchAddressBase(N, AM);
779 // RIP relative addressing: %rip + 32-bit displacement!
781 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
782 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
783 if (!is64Bit || isInt32(AM.Disp + Val)) {
791 switch (N.getOpcode()) {
793 case ISD::Constant: {
794 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
795 if (!is64Bit || isInt32(AM.Disp + Val)) {
802 case X86ISD::SegmentBaseAddress:
803 if (!MatchSegmentBaseAddress(N, AM))
807 case X86ISD::Wrapper: {
808 DOUT << "Wrapper: 64bit " << is64Bit;
809 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
810 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
811 // Also, base and index reg must be 0 in order to use rip as base.
812 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
813 AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
815 if (AM.hasSymbolicDisplacement())
817 // If value is available in a register both base and index components have
818 // been picked, we can't fit the result available in the register in the
819 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
821 SDValue N0 = N.getOperand(0);
822 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
823 uint64_t Offset = G->getOffset();
824 if (!is64Bit || isInt32(AM.Disp + Offset)) {
825 GlobalValue *GV = G->getGlobal();
828 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
831 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
832 uint64_t Offset = CP->getOffset();
833 if (!is64Bit || isInt32(AM.Disp + Offset)) {
834 AM.CP = CP->getConstVal();
835 AM.Align = CP->getAlignment();
837 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
840 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
841 AM.ES = S->getSymbol();
842 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
844 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
845 AM.JT = J->getIndex();
846 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
854 if (!MatchLoad(N, AM))
858 case ISD::FrameIndex:
859 if (AM.BaseType == X86ISelAddressMode::RegBase
860 && AM.Base.Reg.getNode() == 0) {
861 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
862 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
868 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1 || AM.isRIPRel)
872 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
873 unsigned Val = CN->getZExtValue();
874 if (Val == 1 || Val == 2 || Val == 3) {
876 SDValue ShVal = N.getNode()->getOperand(0);
878 // Okay, we know that we have a scale by now. However, if the scaled
879 // value is an add of something and a constant, we can fold the
880 // constant into the disp field here.
881 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
882 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
883 AM.IndexReg = ShVal.getNode()->getOperand(0);
884 ConstantSDNode *AddVal =
885 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
886 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
887 if (!is64Bit || isInt32(Disp))
901 // A mul_lohi where we need the low part can be folded as a plain multiply.
902 if (N.getResNo() != 0) break;
905 case X86ISD::MUL_IMM:
906 // X*[3,5,9] -> X+X*[2,4,8]
907 if (AM.BaseType == X86ISelAddressMode::RegBase &&
908 AM.Base.Reg.getNode() == 0 &&
909 AM.IndexReg.getNode() == 0 &&
912 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
913 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
914 CN->getZExtValue() == 9) {
915 AM.Scale = unsigned(CN->getZExtValue())-1;
917 SDValue MulVal = N.getNode()->getOperand(0);
920 // Okay, we know that we have a scale by now. However, if the scaled
921 // value is an add of something and a constant, we can fold the
922 // constant into the disp field here.
923 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
924 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
925 Reg = MulVal.getNode()->getOperand(0);
926 ConstantSDNode *AddVal =
927 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
928 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
930 if (!is64Bit || isInt32(Disp))
933 Reg = N.getNode()->getOperand(0);
935 Reg = N.getNode()->getOperand(0);
938 AM.IndexReg = AM.Base.Reg = Reg;
945 X86ISelAddressMode Backup = AM;
946 if (!MatchAddress(N.getNode()->getOperand(0), AM, Depth+1) &&
947 !MatchAddress(N.getNode()->getOperand(1), AM, Depth+1))
950 if (!MatchAddress(N.getNode()->getOperand(1), AM, Depth+1) &&
951 !MatchAddress(N.getNode()->getOperand(0), AM, Depth+1))
955 // If we couldn't fold both operands into the address at the same time,
956 // see if we can just put each operand into a register and fold at least
958 if (AM.BaseType == X86ISelAddressMode::RegBase &&
959 !AM.Base.Reg.getNode() &&
960 !AM.IndexReg.getNode() &&
962 AM.Base.Reg = N.getNode()->getOperand(0);
963 AM.IndexReg = N.getNode()->getOperand(1);
971 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
972 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
973 X86ISelAddressMode Backup = AM;
974 uint64_t Offset = CN->getSExtValue();
975 // Start with the LHS as an addr mode.
976 if (!MatchAddress(N.getOperand(0), AM, Depth+1) &&
977 // Address could not have picked a GV address for the displacement.
979 // On x86-64, the resultant disp must fit in 32-bits.
980 (!is64Bit || isInt32(AM.Disp + Offset)) &&
981 // Check to see if the LHS & C is zero.
982 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
991 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
992 // allows us to fold the shift into this addressing mode.
993 SDValue Shift = N.getOperand(0);
994 if (Shift.getOpcode() != ISD::SHL) break;
996 // Scale must not be used already.
997 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
999 // Not when RIP is used as the base.
1000 if (AM.isRIPRel) break;
1002 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1003 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1004 if (!C1 || !C2) break;
1006 // Not likely to be profitable if either the AND or SHIFT node has more
1007 // than one use (unless all uses are for address computation). Besides,
1008 // isel mechanism requires their node ids to be reused.
1009 if (!N.hasOneUse() || !Shift.hasOneUse())
1012 // Verify that the shift amount is something we can fold.
1013 unsigned ShiftCst = C1->getZExtValue();
1014 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1017 // Get the new AND mask, this folds to a constant.
1018 SDValue X = Shift.getOperand(0);
1019 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1020 SDValue(C2, 0), SDValue(C1, 0));
1021 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1023 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1024 NewAND, SDValue(C1, 0));
1026 // Insert the new nodes into the topological ordering.
1027 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1028 CurDAG->RepositionNode(X.getNode(), C1);
1029 C1->setNodeId(X.getNode()->getNodeId());
1031 if (NewANDMask.getNode()->getNodeId() == -1 ||
1032 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1033 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1034 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1036 if (NewAND.getNode()->getNodeId() == -1 ||
1037 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1038 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1039 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1041 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1042 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1043 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1044 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1047 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1049 AM.Scale = 1 << ShiftCst;
1050 AM.IndexReg = NewAND;
1055 return MatchAddressBase(N, AM);
1058 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1059 /// specified addressing mode without any further recursion.
1060 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1061 // Is the base register already occupied?
1062 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1063 // If so, check to see if the scale index register is set.
1064 if (AM.IndexReg.getNode() == 0 && !AM.isRIPRel) {
1070 // Otherwise, we cannot select it.
1074 // Default, generate it as a register.
1075 AM.BaseType = X86ISelAddressMode::RegBase;
1080 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1081 /// It returns the operands which make up the maximal addressing mode it can
1082 /// match by reference.
1083 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1084 SDValue &Scale, SDValue &Index,
1085 SDValue &Disp, SDValue &Segment) {
1086 X86ISelAddressMode AM;
1088 if (AvoidDupAddrCompute && !N.hasOneUse()) {
1089 unsigned Opcode = N.getOpcode();
1090 if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1091 Opcode != X86ISD::Wrapper) {
1092 // If we are able to fold N into addressing mode, then we'll allow it even
1093 // if N has multiple uses. In general, addressing computation is used as
1094 // addresses by all of its uses. But watch out for CopyToReg uses, that
1095 // means the address computation is liveout. It will be computed by a LEA
1096 // so we want to avoid computing the address twice.
1097 for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1098 UE = N.getNode()->use_end(); UI != UE; ++UI) {
1099 if (UI->getOpcode() == ISD::CopyToReg) {
1100 MatchAddressBase(N, AM);
1108 if (!Done && MatchAddress(N, AM))
1111 MVT VT = N.getValueType();
1112 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1113 if (!AM.Base.Reg.getNode())
1114 AM.Base.Reg = CurDAG->getRegister(0, VT);
1117 if (!AM.IndexReg.getNode())
1118 AM.IndexReg = CurDAG->getRegister(0, VT);
1120 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1124 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1125 /// match a load whose top elements are either undef or zeros. The load flavor
1126 /// is derived from the type of N, which is either v4f32 or v2f64.
1127 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1128 SDValue N, SDValue &Base,
1129 SDValue &Scale, SDValue &Index,
1130 SDValue &Disp, SDValue &Segment,
1132 SDValue &OutChain) {
1133 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1134 InChain = N.getOperand(0).getValue(1);
1135 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1136 InChain.getValue(0).hasOneUse() &&
1138 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1139 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1140 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1142 OutChain = LD->getChain();
1147 // Also handle the case where we explicitly require zeros in the top
1148 // elements. This is a vector shuffle from the zero vector.
1149 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1150 // Check to see if the top elements are all zeros (or bitcast of zeros).
1151 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1152 N.getOperand(0).getNode()->hasOneUse() &&
1153 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1154 N.getOperand(0).getOperand(0).hasOneUse()) {
1155 // Okay, this is a zero extending load. Fold it.
1156 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1157 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1159 OutChain = LD->getChain();
1160 InChain = SDValue(LD, 1);
1167 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1168 /// mode it matches can be cost effectively emitted as an LEA instruction.
1169 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1170 SDValue &Base, SDValue &Scale,
1171 SDValue &Index, SDValue &Disp) {
1172 X86ISelAddressMode AM;
1173 if (MatchAddress(N, AM))
1176 //Is it better to set AM.Segment before calling MatchAddress to
1177 //prevent it from adding a segment?
1178 if (AM.Segment.getNode())
1181 MVT VT = N.getValueType();
1182 unsigned Complexity = 0;
1183 if (AM.BaseType == X86ISelAddressMode::RegBase)
1184 if (AM.Base.Reg.getNode())
1187 AM.Base.Reg = CurDAG->getRegister(0, VT);
1188 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1191 if (AM.IndexReg.getNode())
1194 AM.IndexReg = CurDAG->getRegister(0, VT);
1196 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1201 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1202 // to a LEA. This is determined with some expermentation but is by no means
1203 // optimal (especially for code size consideration). LEA is nice because of
1204 // its three-address nature. Tweak the cost function again when we can run
1205 // convertToThreeAddress() at register allocation time.
1206 if (AM.hasSymbolicDisplacement()) {
1207 // For X86-64, we should always use lea to materialize RIP relative
1209 if (Subtarget->is64Bit())
1215 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1218 if (Complexity > 2) {
1220 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1226 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1227 SDValue &Base, SDValue &Scale,
1228 SDValue &Index, SDValue &Disp,
1230 if (ISD::isNON_EXTLoad(N.getNode()) &&
1232 IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1233 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1237 /// getGlobalBaseReg - Return an SDNode that returns the value of
1238 /// the global base register. Output instructions required to
1239 /// initialize the global base register, if necessary.
1241 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1242 MachineFunction *MF = CurBB->getParent();
1243 unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF);
1244 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1247 static SDNode *FindCallStartFromCall(SDNode *Node) {
1248 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1249 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1250 "Node doesn't have a token chain argument!");
1251 return FindCallStartFromCall(Node->getOperand(0).getNode());
1254 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1255 /// truncate of the specified operand to i8. This can be done with tablegen,
1256 /// except that this code uses MVT::Flag in a tricky way that happens to
1257 /// improve scheduling in some cases.
1258 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1259 assert(!Subtarget->is64Bit() &&
1260 "getTruncateTo8Bit is only needed on x86-32!");
1261 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1262 DebugLoc dl = N0.getDebugLoc();
1264 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1266 MVT N0VT = N0.getValueType();
1267 switch (N0VT.getSimpleVT()) {
1268 default: assert(0 && "Unknown truncate!");
1270 Opc = X86::MOV16to16_;
1273 Opc = X86::MOV32to32_;
1277 // The use of MVT::Flag here is not strictly accurate, but it helps
1278 // scheduling in some cases.
1279 N0 = SDValue(CurDAG->getTargetNode(Opc, dl, N0VT, MVT::Flag, N0), 0);
1280 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1281 MVT::i8, N0, SRIdx, N0.getValue(1));
1284 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1285 SDValue Chain = Node->getOperand(0);
1286 SDValue In1 = Node->getOperand(1);
1287 SDValue In2L = Node->getOperand(2);
1288 SDValue In2H = Node->getOperand(3);
1289 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1290 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1292 SDValue LSI = Node->getOperand(4); // MemOperand
1293 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, LSI, Chain};
1294 return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1295 MVT::i32, MVT::i32, MVT::Other, Ops,
1296 array_lengthof(Ops));
1299 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1300 SDNode *Node = N.getNode();
1301 MVT NVT = Node->getValueType(0);
1303 unsigned Opcode = Node->getOpcode();
1304 DebugLoc dl = Node->getDebugLoc();
1307 DOUT << std::string(Indent, ' ') << "Selecting: ";
1308 DEBUG(Node->dump(CurDAG));
1313 if (Node->isMachineOpcode()) {
1315 DOUT << std::string(Indent-2, ' ') << "== ";
1316 DEBUG(Node->dump(CurDAG));
1320 return NULL; // Already selected.
1325 case X86ISD::GlobalBaseReg:
1326 return getGlobalBaseReg();
1328 case X86ISD::ATOMOR64_DAG:
1329 return SelectAtomic64(Node, X86::ATOMOR6432);
1330 case X86ISD::ATOMXOR64_DAG:
1331 return SelectAtomic64(Node, X86::ATOMXOR6432);
1332 case X86ISD::ATOMADD64_DAG:
1333 return SelectAtomic64(Node, X86::ATOMADD6432);
1334 case X86ISD::ATOMSUB64_DAG:
1335 return SelectAtomic64(Node, X86::ATOMSUB6432);
1336 case X86ISD::ATOMNAND64_DAG:
1337 return SelectAtomic64(Node, X86::ATOMNAND6432);
1338 case X86ISD::ATOMAND64_DAG:
1339 return SelectAtomic64(Node, X86::ATOMAND6432);
1340 case X86ISD::ATOMSWAP64_DAG:
1341 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1343 case ISD::SMUL_LOHI:
1344 case ISD::UMUL_LOHI: {
1345 SDValue N0 = Node->getOperand(0);
1346 SDValue N1 = Node->getOperand(1);
1348 bool isSigned = Opcode == ISD::SMUL_LOHI;
1350 switch (NVT.getSimpleVT()) {
1351 default: assert(0 && "Unsupported VT!");
1352 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1353 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1354 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1355 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1358 switch (NVT.getSimpleVT()) {
1359 default: assert(0 && "Unsupported VT!");
1360 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1361 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1362 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1363 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1366 unsigned LoReg, HiReg;
1367 switch (NVT.getSimpleVT()) {
1368 default: assert(0 && "Unsupported VT!");
1369 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1370 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1371 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1372 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1375 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1376 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1377 // multiplty is commmutative
1379 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1384 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1385 N0, SDValue()).getValue(1);
1388 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1391 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1392 array_lengthof(Ops));
1393 InFlag = SDValue(CNode, 1);
1394 // Update the chain.
1395 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1398 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1401 // Copy the low half of the result, if it is needed.
1402 if (!N.getValue(0).use_empty()) {
1403 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1404 LoReg, NVT, InFlag);
1405 InFlag = Result.getValue(2);
1406 ReplaceUses(N.getValue(0), Result);
1408 DOUT << std::string(Indent-2, ' ') << "=> ";
1409 DEBUG(Result.getNode()->dump(CurDAG));
1413 // Copy the high half of the result, if it is needed.
1414 if (!N.getValue(1).use_empty()) {
1416 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1417 // Prevent use of AH in a REX instruction by referencing AX instead.
1418 // Shift it down 8 bits.
1419 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1420 X86::AX, MVT::i16, InFlag);
1421 InFlag = Result.getValue(2);
1422 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1424 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1425 // Then truncate it down to i8.
1426 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1427 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1428 MVT::i8, Result, SRIdx), 0);
1430 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1431 HiReg, NVT, InFlag);
1432 InFlag = Result.getValue(2);
1434 ReplaceUses(N.getValue(1), Result);
1436 DOUT << std::string(Indent-2, ' ') << "=> ";
1437 DEBUG(Result.getNode()->dump(CurDAG));
1450 case ISD::UDIVREM: {
1451 SDValue N0 = Node->getOperand(0);
1452 SDValue N1 = Node->getOperand(1);
1454 bool isSigned = Opcode == ISD::SDIVREM;
1456 switch (NVT.getSimpleVT()) {
1457 default: assert(0 && "Unsupported VT!");
1458 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1459 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1460 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1461 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1464 switch (NVT.getSimpleVT()) {
1465 default: assert(0 && "Unsupported VT!");
1466 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1467 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1468 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1469 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1472 unsigned LoReg, HiReg;
1473 unsigned ClrOpcode, SExtOpcode;
1474 switch (NVT.getSimpleVT()) {
1475 default: assert(0 && "Unsupported VT!");
1477 LoReg = X86::AL; HiReg = X86::AH;
1479 SExtOpcode = X86::CBW;
1482 LoReg = X86::AX; HiReg = X86::DX;
1483 ClrOpcode = X86::MOV16r0;
1484 SExtOpcode = X86::CWD;
1487 LoReg = X86::EAX; HiReg = X86::EDX;
1488 ClrOpcode = X86::MOV32r0;
1489 SExtOpcode = X86::CDQ;
1492 LoReg = X86::RAX; HiReg = X86::RDX;
1493 ClrOpcode = X86::MOV64r0;
1494 SExtOpcode = X86::CQO;
1498 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1499 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1500 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1503 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1504 // Special case for div8, just use a move with zero extension to AX to
1505 // clear the upper 8 bits (AH).
1506 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1507 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1508 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1510 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16,
1512 array_lengthof(Ops)), 0);
1513 Chain = Move.getValue(1);
1514 ReplaceUses(N0.getValue(1), Chain);
1517 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1518 Chain = CurDAG->getEntryNode();
1520 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1521 InFlag = Chain.getValue(1);
1524 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1525 LoReg, N0, SDValue()).getValue(1);
1526 if (isSigned && !signBitIsZero) {
1527 // Sign extend the low part into the high part.
1529 SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1531 // Zero out the high part, effectively zero extending the input.
1532 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT),
1534 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1535 ClrNode, InFlag).getValue(1);
1540 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1543 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1544 array_lengthof(Ops));
1545 InFlag = SDValue(CNode, 1);
1546 // Update the chain.
1547 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1550 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1553 // Copy the division (low) result, if it is needed.
1554 if (!N.getValue(0).use_empty()) {
1555 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1556 LoReg, NVT, InFlag);
1557 InFlag = Result.getValue(2);
1558 ReplaceUses(N.getValue(0), Result);
1560 DOUT << std::string(Indent-2, ' ') << "=> ";
1561 DEBUG(Result.getNode()->dump(CurDAG));
1565 // Copy the remainder (high) result, if it is needed.
1566 if (!N.getValue(1).use_empty()) {
1568 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1569 // Prevent use of AH in a REX instruction by referencing AX instead.
1570 // Shift it down 8 bits.
1571 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1572 X86::AX, MVT::i16, InFlag);
1573 InFlag = Result.getValue(2);
1574 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1576 CurDAG->getTargetConstant(8, MVT::i8)),
1578 // Then truncate it down to i8.
1579 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1580 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1581 MVT::i8, Result, SRIdx), 0);
1583 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1584 HiReg, NVT, InFlag);
1585 InFlag = Result.getValue(2);
1587 ReplaceUses(N.getValue(1), Result);
1589 DOUT << std::string(Indent-2, ' ') << "=> ";
1590 DEBUG(Result.getNode()->dump(CurDAG));
1602 case ISD::SIGN_EXTEND_INREG: {
1603 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1604 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1605 SDValue N0 = Node->getOperand(0);
1607 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1609 switch (NVT.getSimpleVT()) {
1610 default: assert(0 && "Unknown sign_extend_inreg!");
1612 Opc = X86::MOVSX16rr8;
1615 Opc = X86::MOVSX32rr8;
1619 SDNode *ResNode = CurDAG->getTargetNode(Opc, dl, NVT, TruncOp);
1622 DOUT << std::string(Indent-2, ' ') << "=> ";
1623 DEBUG(TruncOp.getNode()->dump(CurDAG));
1625 DOUT << std::string(Indent-2, ' ') << "=> ";
1626 DEBUG(ResNode->dump(CurDAG));
1635 case ISD::TRUNCATE: {
1636 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1637 SDValue Input = Node->getOperand(0);
1638 SDNode *ResNode = getTruncateTo8Bit(Input);
1641 DOUT << std::string(Indent-2, ' ') << "=> ";
1642 DEBUG(ResNode->dump(CurDAG));
1651 case ISD::DECLARE: {
1652 // Handle DECLARE nodes here because the second operand may have been
1653 // wrapped in X86ISD::Wrapper.
1654 SDValue Chain = Node->getOperand(0);
1655 SDValue N1 = Node->getOperand(1);
1656 SDValue N2 = Node->getOperand(2);
1657 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1659 // FIXME: We need to handle this for VLAs.
1661 ReplaceUses(N.getValue(0), Chain);
1665 if (N2.getOpcode() == ISD::ADD &&
1666 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1667 N2 = N2.getOperand(1);
1669 // If N2 is not Wrapper(decriptor) then the llvm.declare is mangled
1670 // somehow, just ignore it.
1671 if (N2.getOpcode() != X86ISD::Wrapper) {
1672 ReplaceUses(N.getValue(0), Chain);
1675 GlobalAddressSDNode *GVNode =
1676 dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1678 ReplaceUses(N.getValue(0), Chain);
1681 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1682 TLI.getPointerTy());
1683 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1684 TLI.getPointerTy());
1685 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1686 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE, dl,
1688 array_lengthof(Ops));
1692 SDNode *ResNode = SelectCode(N);
1695 DOUT << std::string(Indent-2, ' ') << "=> ";
1696 if (ResNode == NULL || ResNode == N.getNode())
1697 DEBUG(N.getNode()->dump(CurDAG));
1699 DEBUG(ResNode->dump(CurDAG));
1707 bool X86DAGToDAGISel::
1708 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1709 std::vector<SDValue> &OutOps) {
1710 SDValue Op0, Op1, Op2, Op3, Op4;
1711 switch (ConstraintCode) {
1712 case 'o': // offsetable ??
1713 case 'v': // not offsetable ??
1714 default: return true;
1716 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3, Op4))
1721 OutOps.push_back(Op0);
1722 OutOps.push_back(Op1);
1723 OutOps.push_back(Op2);
1724 OutOps.push_back(Op3);
1725 OutOps.push_back(Op4);
1729 /// createX86ISelDag - This pass converts a legalized DAG into a
1730 /// X86-specific DAG, ready for instruction scheduling.
1732 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1733 return new X86DAGToDAGISel(TM, Fast);