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!
76 unsigned Align; // CP alignment.
77 unsigned char SymbolFlags; // X86II::MO_*
80 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
81 Segment(), GV(0), CP(0), ES(0), JT(-1), Align(0), SymbolFlags(0) {
84 bool hasSymbolicDisplacement() const {
85 return GV != 0 || CP != 0 || ES != 0 || JT != -1;
88 bool hasBaseOrIndexReg() const {
89 return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
92 /// isRIPRelative - Return true if this addressing mode is already RIP
94 bool isRIPRelative() const {
95 if (BaseType != RegBase) return false;
96 if (RegisterSDNode *RegNode =
97 dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
98 return RegNode->getReg() == X86::RIP;
102 void setBaseReg(SDValue Reg) {
108 cerr << "X86ISelAddressMode " << this << "\n";
110 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
112 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
113 cerr << " Scale" << Scale << "\n";
115 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
117 cerr << " Disp " << Disp << "\n";
118 cerr << "GV "; if (GV) GV->dump();
120 cerr << " CP "; if (CP) CP->dump();
123 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
124 cerr << " JT" << JT << " Align" << Align << "\n";
130 //===--------------------------------------------------------------------===//
131 /// ISel - X86 specific code to select X86 machine instructions for
132 /// SelectionDAG operations.
134 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
135 /// X86Lowering - This object fully describes how to lower LLVM code to an
136 /// X86-specific SelectionDAG.
137 X86TargetLowering &X86Lowering;
139 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
140 /// make the right decision when generating code for different targets.
141 const X86Subtarget *Subtarget;
143 /// CurBB - Current BB being isel'd.
145 MachineBasicBlock *CurBB;
147 /// OptForSize - If true, selector should try to optimize for code size
148 /// instead of performance.
152 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
153 : SelectionDAGISel(tm, OptLevel),
154 X86Lowering(*tm.getTargetLowering()),
155 Subtarget(&tm.getSubtarget<X86Subtarget>()),
158 virtual const char *getPassName() const {
159 return "X86 DAG->DAG Instruction Selection";
162 /// InstructionSelect - This callback is invoked by
163 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
164 virtual void InstructionSelect();
166 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
169 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
171 // Include the pieces autogenerated from the target description.
172 #include "X86GenDAGISel.inc"
175 SDNode *Select(SDValue N);
176 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
178 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
179 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
180 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
181 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
183 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
184 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
185 SDValue &Scale, SDValue &Index, SDValue &Disp,
187 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
188 SDValue &Scale, SDValue &Index, SDValue &Disp);
189 bool SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
190 SDValue &Scale, SDValue &Index, SDValue &Disp);
191 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
192 SDValue N, SDValue &Base, SDValue &Scale,
193 SDValue &Index, SDValue &Disp,
195 SDValue &InChain, SDValue &OutChain);
196 bool TryFoldLoad(SDValue P, SDValue N,
197 SDValue &Base, SDValue &Scale,
198 SDValue &Index, SDValue &Disp,
200 void PreprocessForRMW();
201 void PreprocessForFPConvert();
203 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
204 /// inline asm expressions.
205 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
207 std::vector<SDValue> &OutOps);
209 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
211 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
212 SDValue &Scale, SDValue &Index,
213 SDValue &Disp, SDValue &Segment) {
214 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
215 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
217 Scale = getI8Imm(AM.Scale);
219 // These are 32-bit even in 64-bit mode since RIP relative offset
222 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
225 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
226 AM.Align, AM.Disp, AM.SymbolFlags);
228 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
229 else if (AM.JT != -1)
230 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
232 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
234 if (AM.Segment.getNode())
235 Segment = AM.Segment;
237 Segment = CurDAG->getRegister(0, MVT::i32);
240 /// getI8Imm - Return a target constant with the specified value, of type
242 inline SDValue getI8Imm(unsigned Imm) {
243 return CurDAG->getTargetConstant(Imm, MVT::i8);
246 /// getI16Imm - Return a target constant with the specified value, of type
248 inline SDValue getI16Imm(unsigned Imm) {
249 return CurDAG->getTargetConstant(Imm, MVT::i16);
252 /// getI32Imm - Return a target constant with the specified value, of type
254 inline SDValue getI32Imm(unsigned Imm) {
255 return CurDAG->getTargetConstant(Imm, MVT::i32);
258 /// getGlobalBaseReg - Return an SDNode that returns the value of
259 /// the global base register. Output instructions required to
260 /// initialize the global base register, if necessary.
262 SDNode *getGlobalBaseReg();
264 /// getTargetMachine - Return a reference to the TargetMachine, casted
265 /// to the target-specific type.
266 const X86TargetMachine &getTargetMachine() {
267 return static_cast<const X86TargetMachine &>(TM);
270 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
271 /// to the target-specific type.
272 const X86InstrInfo *getInstrInfo() {
273 return getTargetMachine().getInstrInfo();
283 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
284 SDNode *Root) const {
285 if (OptLevel == CodeGenOpt::None) return false;
288 switch (U->getOpcode()) {
296 SDValue Op1 = U->getOperand(1);
298 // If the other operand is a 8-bit immediate we should fold the immediate
299 // instead. This reduces code size.
301 // movl 4(%esp), %eax
305 // addl 4(%esp), %eax
306 // The former is 2 bytes shorter. In case where the increment is 1, then
307 // the saving can be 4 bytes (by using incl %eax).
308 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
309 if (Imm->getAPIntValue().isSignedIntN(8))
312 // If the other operand is a TLS address, we should fold it instead.
315 // leal i@NTPOFF(%eax), %eax
317 // movl $i@NTPOFF, %eax
319 // if the block also has an access to a second TLS address this will save
321 // FIXME: This is probably also true for non TLS addresses.
322 if (Op1.getOpcode() == X86ISD::Wrapper) {
323 SDValue Val = Op1.getOperand(0);
324 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
330 // Proceed to 'generic' cycle finder code
331 return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
334 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
335 /// and move load below the TokenFactor. Replace store's chain operand with
336 /// load's chain result.
337 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
338 SDValue Store, SDValue TF) {
339 SmallVector<SDValue, 4> Ops;
340 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
341 if (Load.getNode() == TF.getOperand(i).getNode())
342 Ops.push_back(Load.getOperand(0));
344 Ops.push_back(TF.getOperand(i));
345 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
346 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
347 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
348 Store.getOperand(2), Store.getOperand(3));
351 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
353 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
355 if (N.getOpcode() == ISD::BIT_CONVERT)
358 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
359 if (!LD || LD->isVolatile())
361 if (LD->getAddressingMode() != ISD::UNINDEXED)
364 ISD::LoadExtType ExtType = LD->getExtensionType();
365 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
369 N.getOperand(1) == Address &&
370 N.getNode()->isOperandOf(Chain.getNode())) {
377 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
378 /// operand and move load below the call's chain operand.
379 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
380 SDValue Call, SDValue CallSeqStart) {
381 SmallVector<SDValue, 8> Ops;
382 SDValue Chain = CallSeqStart.getOperand(0);
383 if (Chain.getNode() == Load.getNode())
384 Ops.push_back(Load.getOperand(0));
386 assert(Chain.getOpcode() == ISD::TokenFactor &&
387 "Unexpected CallSeqStart chain operand");
388 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
389 if (Chain.getOperand(i).getNode() == Load.getNode())
390 Ops.push_back(Load.getOperand(0));
392 Ops.push_back(Chain.getOperand(i));
394 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
395 MVT::Other, &Ops[0], Ops.size());
397 Ops.push_back(NewChain);
399 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
400 Ops.push_back(CallSeqStart.getOperand(i));
401 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
402 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
403 Load.getOperand(1), Load.getOperand(2));
405 Ops.push_back(SDValue(Load.getNode(), 1));
406 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
407 Ops.push_back(Call.getOperand(i));
408 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
411 /// isCalleeLoad - Return true if call address is a load and it can be
412 /// moved below CALLSEQ_START and the chains leading up to the call.
413 /// Return the CALLSEQ_START by reference as a second output.
414 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
415 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
417 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
420 LD->getAddressingMode() != ISD::UNINDEXED ||
421 LD->getExtensionType() != ISD::NON_EXTLOAD)
424 // Now let's find the callseq_start.
425 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
426 if (!Chain.hasOneUse())
428 Chain = Chain.getOperand(0);
431 if (Chain.getOperand(0).getNode() == Callee.getNode())
433 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
434 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
440 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
441 /// This is only run if not in -O0 mode.
442 /// This allows the instruction selector to pick more read-modify-write
443 /// instructions. This is a common case:
453 /// [TokenFactor] [Op]
460 /// The fact the store's chain operand != load's chain will prevent the
461 /// (store (op (load))) instruction from being selected. We can transform it to:
480 void X86DAGToDAGISel::PreprocessForRMW() {
481 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
482 E = CurDAG->allnodes_end(); I != E; ++I) {
483 if (I->getOpcode() == X86ISD::CALL) {
484 /// Also try moving call address load from outside callseq_start to just
485 /// before the call to allow it to be folded.
503 SDValue Chain = I->getOperand(0);
504 SDValue Load = I->getOperand(1);
505 if (!isCalleeLoad(Load, Chain))
507 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
512 if (!ISD::isNON_TRUNCStore(I))
514 SDValue Chain = I->getOperand(0);
516 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
519 SDValue N1 = I->getOperand(1);
520 SDValue N2 = I->getOperand(2);
521 if ((N1.getValueType().isFloatingPoint() &&
522 !N1.getValueType().isVector()) ||
528 unsigned Opcode = N1.getNode()->getOpcode();
537 case ISD::VECTOR_SHUFFLE: {
538 SDValue N10 = N1.getOperand(0);
539 SDValue N11 = N1.getOperand(1);
540 RModW = isRMWLoad(N10, Chain, N2, Load);
542 RModW = isRMWLoad(N11, Chain, N2, Load);
555 SDValue N10 = N1.getOperand(0);
556 RModW = isRMWLoad(N10, Chain, N2, Load);
562 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
569 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
570 /// nodes that target the FP stack to be store and load to the stack. This is a
571 /// gross hack. We would like to simply mark these as being illegal, but when
572 /// we do that, legalize produces these when it expands calls, then expands
573 /// these in the same legalize pass. We would like dag combine to be able to
574 /// hack on these between the call expansion and the node legalization. As such
575 /// this pass basically does "really late" legalization of these inline with the
577 void X86DAGToDAGISel::PreprocessForFPConvert() {
578 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
579 E = CurDAG->allnodes_end(); I != E; ) {
580 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
581 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
584 // If the source and destination are SSE registers, then this is a legal
585 // conversion that should not be lowered.
586 MVT SrcVT = N->getOperand(0).getValueType();
587 MVT DstVT = N->getValueType(0);
588 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
589 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
590 if (SrcIsSSE && DstIsSSE)
593 if (!SrcIsSSE && !DstIsSSE) {
594 // If this is an FPStack extension, it is a noop.
595 if (N->getOpcode() == ISD::FP_EXTEND)
597 // If this is a value-preserving FPStack truncation, it is a noop.
598 if (N->getConstantOperandVal(1))
602 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
603 // FPStack has extload and truncstore. SSE can fold direct loads into other
604 // operations. Based on this, decide what we want to do.
606 if (N->getOpcode() == ISD::FP_ROUND)
607 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
609 MemVT = SrcIsSSE ? SrcVT : DstVT;
611 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
612 DebugLoc dl = N->getDebugLoc();
614 // FIXME: optimize the case where the src/dest is a load or store?
615 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
617 MemTmp, NULL, 0, MemVT);
618 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
621 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
622 // extload we created. This will cause general havok on the dag because
623 // anything below the conversion could be folded into other existing nodes.
624 // To avoid invalidating 'I', back it up to the convert node.
626 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
628 // Now that we did that, the node is dead. Increment the iterator to the
629 // next node to process, then delete N.
631 CurDAG->DeleteNode(N);
635 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
636 /// when it has created a SelectionDAG for us to codegen.
637 void X86DAGToDAGISel::InstructionSelect() {
638 CurBB = BB; // BB can change as result of isel.
639 const Function *F = CurDAG->getMachineFunction().getFunction();
640 OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
643 if (OptLevel != CodeGenOpt::None)
646 // FIXME: This should only happen when not compiled with -O0.
647 PreprocessForFPConvert();
649 // Codegen the basic block.
651 DOUT << "===== Instruction selection begins:\n";
656 DOUT << "===== Instruction selection ends:\n";
659 CurDAG->RemoveDeadNodes();
662 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
663 /// the main function.
664 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
665 MachineFrameInfo *MFI) {
666 const TargetInstrInfo *TII = TM.getInstrInfo();
667 if (Subtarget->isTargetCygMing())
668 BuildMI(BB, DebugLoc::getUnknownLoc(),
669 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
672 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
673 // If this is main, emit special code for main.
674 MachineBasicBlock *BB = MF.begin();
675 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
676 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
680 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
681 X86ISelAddressMode &AM) {
682 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
683 SDValue Segment = N.getOperand(0);
685 if (AM.Segment.getNode() == 0) {
686 AM.Segment = Segment;
693 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
694 // This optimization is valid because the GNU TLS model defines that
695 // gs:0 (or fs:0 on X86-64) contains its own address.
696 // For more information see http://people.redhat.com/drepper/tls.pdf
698 SDValue Address = N.getOperand(1);
699 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
700 !MatchSegmentBaseAddress (Address, AM))
706 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
707 /// into an addressing mode. These wrap things that will resolve down into a
708 /// symbol reference. If no match is possible, this returns true, otherwise it
710 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
711 // If the addressing mode already has a symbol as the displacement, we can
712 // never match another symbol.
713 if (AM.hasSymbolicDisplacement())
716 SDValue N0 = N.getOperand(0);
718 // Handle X86-64 rip-relative addresses. We check this before checking direct
719 // folding because RIP is preferable to non-RIP accesses.
720 if (Subtarget->is64Bit() &&
721 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
722 // they cannot be folded into immediate fields.
723 // FIXME: This can be improved for kernel and other models?
724 TM.getCodeModel() == CodeModel::Small &&
726 // Base and index reg must be 0 in order to use %rip as base and lowering
728 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
730 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
731 int64_t Offset = AM.Disp + G->getOffset();
732 if (!isInt32(Offset)) return true;
733 AM.GV = G->getGlobal();
735 AM.SymbolFlags = G->getTargetFlags();
736 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
737 int64_t Offset = AM.Disp + CP->getOffset();
738 if (!isInt32(Offset)) return true;
739 AM.CP = CP->getConstVal();
740 AM.Align = CP->getAlignment();
742 AM.SymbolFlags = CP->getTargetFlags();
743 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
744 AM.ES = S->getSymbol();
745 AM.SymbolFlags = S->getTargetFlags();
747 JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
748 AM.JT = J->getIndex();
749 AM.SymbolFlags = J->getTargetFlags();
752 if (N.getOpcode() == X86ISD::WrapperRIP)
753 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
757 // Handle the case when globals fit in our immediate field: This is true for
758 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
759 // mode, this results in a non-RIP-relative computation.
760 if (!Subtarget->is64Bit() ||
761 (TM.getCodeModel() == CodeModel::Small &&
762 TM.getRelocationModel() == Reloc::Static)) {
763 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
764 AM.GV = G->getGlobal();
765 AM.Disp += G->getOffset();
766 AM.SymbolFlags = G->getTargetFlags();
767 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
768 AM.CP = CP->getConstVal();
769 AM.Align = CP->getAlignment();
770 AM.Disp += CP->getOffset();
771 AM.SymbolFlags = CP->getTargetFlags();
772 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
773 AM.ES = S->getSymbol();
774 AM.SymbolFlags = S->getTargetFlags();
776 JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
777 AM.JT = J->getIndex();
778 AM.SymbolFlags = J->getTargetFlags();
786 /// MatchAddress - Add the specified node to the specified addressing mode,
787 /// returning true if it cannot be done. This just pattern matches for the
789 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
791 bool is64Bit = Subtarget->is64Bit();
792 DebugLoc dl = N.getDebugLoc();
793 DOUT << "MatchAddress: "; DEBUG(AM.dump());
796 return MatchAddressBase(N, AM);
798 // If this is already a %rip relative address, we can only merge immediates
799 // into it. Instead of handling this in every case, we handle it here.
800 // RIP relative addressing: %rip + 32-bit displacement!
801 if (AM.isRIPRelative()) {
802 // FIXME: JumpTable and ExternalSymbol address currently don't like
803 // displacements. It isn't very important, but this should be fixed for
805 if (!AM.ES && AM.JT != -1) return true;
807 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
808 int64_t Val = AM.Disp + Cst->getSExtValue();
817 switch (N.getOpcode()) {
819 case ISD::Constant: {
820 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
821 if (!is64Bit || isInt32(AM.Disp + Val)) {
828 case X86ISD::SegmentBaseAddress:
829 if (!MatchSegmentBaseAddress(N, AM))
833 case X86ISD::Wrapper:
834 case X86ISD::WrapperRIP:
835 if (!MatchWrapper(N, AM))
840 if (!MatchLoad(N, AM))
844 case ISD::FrameIndex:
845 if (AM.BaseType == X86ISelAddressMode::RegBase
846 && AM.Base.Reg.getNode() == 0) {
847 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
848 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
854 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
858 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
859 unsigned Val = CN->getZExtValue();
860 if (Val == 1 || Val == 2 || Val == 3) {
862 SDValue ShVal = N.getNode()->getOperand(0);
864 // Okay, we know that we have a scale by now. However, if the scaled
865 // value is an add of something and a constant, we can fold the
866 // constant into the disp field here.
867 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
868 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
869 AM.IndexReg = ShVal.getNode()->getOperand(0);
870 ConstantSDNode *AddVal =
871 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
872 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
873 if (!is64Bit || isInt32(Disp))
887 // A mul_lohi where we need the low part can be folded as a plain multiply.
888 if (N.getResNo() != 0) break;
891 case X86ISD::MUL_IMM:
892 // X*[3,5,9] -> X+X*[2,4,8]
893 if (AM.BaseType == X86ISelAddressMode::RegBase &&
894 AM.Base.Reg.getNode() == 0 &&
895 AM.IndexReg.getNode() == 0) {
897 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
898 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
899 CN->getZExtValue() == 9) {
900 AM.Scale = unsigned(CN->getZExtValue())-1;
902 SDValue MulVal = N.getNode()->getOperand(0);
905 // Okay, we know that we have a scale by now. However, if the scaled
906 // value is an add of something and a constant, we can fold the
907 // constant into the disp field here.
908 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
909 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
910 Reg = MulVal.getNode()->getOperand(0);
911 ConstantSDNode *AddVal =
912 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
913 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
915 if (!is64Bit || isInt32(Disp))
918 Reg = N.getNode()->getOperand(0);
920 Reg = N.getNode()->getOperand(0);
923 AM.IndexReg = AM.Base.Reg = Reg;
930 // Given A-B, if A can be completely folded into the address and
931 // the index field with the index field unused, use -B as the index.
932 // This is a win if a has multiple parts that can be folded into
933 // the address. Also, this saves a mov if the base register has
934 // other uses, since it avoids a two-address sub instruction, however
935 // it costs an additional mov if the index register has other uses.
937 // Test if the LHS of the sub can be folded.
938 X86ISelAddressMode Backup = AM;
939 if (MatchAddress(N.getNode()->getOperand(0), AM, Depth+1)) {
943 // Test if the index field is free for use.
944 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
949 SDValue RHS = N.getNode()->getOperand(1);
950 // If the RHS involves a register with multiple uses, this
951 // transformation incurs an extra mov, due to the neg instruction
952 // clobbering its operand.
953 if (!RHS.getNode()->hasOneUse() ||
954 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
955 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
956 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
957 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
958 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
960 // If the base is a register with multiple uses, this
961 // transformation may save a mov.
962 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
963 AM.Base.Reg.getNode() &&
964 !AM.Base.Reg.getNode()->hasOneUse()) ||
965 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
967 // If the folded LHS was interesting, this transformation saves
968 // address arithmetic.
969 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
970 ((AM.Disp != 0) && (Backup.Disp == 0)) +
971 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
973 // If it doesn't look like it may be an overall win, don't do it.
979 // Ok, the transformation is legal and appears profitable. Go for it.
980 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
981 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
985 // Insert the new nodes into the topological ordering.
986 if (Zero.getNode()->getNodeId() == -1 ||
987 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
988 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
989 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
991 if (Neg.getNode()->getNodeId() == -1 ||
992 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
993 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
994 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
1000 X86ISelAddressMode Backup = AM;
1001 if (!MatchAddress(N.getNode()->getOperand(0), AM, Depth+1) &&
1002 !MatchAddress(N.getNode()->getOperand(1), AM, Depth+1))
1005 if (!MatchAddress(N.getNode()->getOperand(1), AM, Depth+1) &&
1006 !MatchAddress(N.getNode()->getOperand(0), AM, Depth+1))
1010 // If we couldn't fold both operands into the address at the same time,
1011 // see if we can just put each operand into a register and fold at least
1013 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1014 !AM.Base.Reg.getNode() &&
1015 !AM.IndexReg.getNode()) {
1016 AM.Base.Reg = N.getNode()->getOperand(0);
1017 AM.IndexReg = N.getNode()->getOperand(1);
1025 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1026 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1027 X86ISelAddressMode Backup = AM;
1028 uint64_t Offset = CN->getSExtValue();
1029 // Start with the LHS as an addr mode.
1030 if (!MatchAddress(N.getOperand(0), AM, Depth+1) &&
1031 // Address could not have picked a GV address for the displacement.
1033 // On x86-64, the resultant disp must fit in 32-bits.
1034 (!is64Bit || isInt32(AM.Disp + Offset)) &&
1035 // Check to see if the LHS & C is zero.
1036 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
1045 // Perform some heroic transforms on an and of a constant-count shift
1046 // with a constant to enable use of the scaled offset field.
1048 SDValue Shift = N.getOperand(0);
1049 if (Shift.getNumOperands() != 2) break;
1051 // Scale must not be used already.
1052 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1054 SDValue X = Shift.getOperand(0);
1055 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1056 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1057 if (!C1 || !C2) break;
1059 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1060 // allows us to convert the shift and and into an h-register extract and
1062 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1063 unsigned ScaleLog = 8 - C1->getZExtValue();
1064 if (ScaleLog > 0 && ScaleLog < 4 &&
1065 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1066 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1067 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1068 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1070 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1072 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1073 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1076 // Insert the new nodes into the topological ordering.
1077 if (Eight.getNode()->getNodeId() == -1 ||
1078 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1079 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1080 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1082 if (Mask.getNode()->getNodeId() == -1 ||
1083 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1084 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1085 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1087 if (Srl.getNode()->getNodeId() == -1 ||
1088 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1089 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1090 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1092 if (And.getNode()->getNodeId() == -1 ||
1093 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1094 CurDAG->RepositionNode(N.getNode(), And.getNode());
1095 And.getNode()->setNodeId(N.getNode()->getNodeId());
1097 if (ShlCount.getNode()->getNodeId() == -1 ||
1098 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1099 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1100 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1102 if (Shl.getNode()->getNodeId() == -1 ||
1103 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1104 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1105 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1107 CurDAG->ReplaceAllUsesWith(N, Shl);
1109 AM.Scale = (1 << ScaleLog);
1114 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1115 // allows us to fold the shift into this addressing mode.
1116 if (Shift.getOpcode() != ISD::SHL) break;
1118 // Not likely to be profitable if either the AND or SHIFT node has more
1119 // than one use (unless all uses are for address computation). Besides,
1120 // isel mechanism requires their node ids to be reused.
1121 if (!N.hasOneUse() || !Shift.hasOneUse())
1124 // Verify that the shift amount is something we can fold.
1125 unsigned ShiftCst = C1->getZExtValue();
1126 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1129 // Get the new AND mask, this folds to a constant.
1130 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1131 SDValue(C2, 0), SDValue(C1, 0));
1132 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1134 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1135 NewAND, SDValue(C1, 0));
1137 // Insert the new nodes into the topological ordering.
1138 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1139 CurDAG->RepositionNode(X.getNode(), C1);
1140 C1->setNodeId(X.getNode()->getNodeId());
1142 if (NewANDMask.getNode()->getNodeId() == -1 ||
1143 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1144 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1145 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1147 if (NewAND.getNode()->getNodeId() == -1 ||
1148 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1149 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1150 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1152 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1153 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1154 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1155 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1158 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1160 AM.Scale = 1 << ShiftCst;
1161 AM.IndexReg = NewAND;
1166 return MatchAddressBase(N, AM);
1169 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1170 /// specified addressing mode without any further recursion.
1171 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1172 // Is the base register already occupied?
1173 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1174 // If so, check to see if the scale index register is set.
1175 if (AM.IndexReg.getNode() == 0) {
1181 // Otherwise, we cannot select it.
1185 // Default, generate it as a register.
1186 AM.BaseType = X86ISelAddressMode::RegBase;
1191 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1192 /// It returns the operands which make up the maximal addressing mode it can
1193 /// match by reference.
1194 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1195 SDValue &Scale, SDValue &Index,
1196 SDValue &Disp, SDValue &Segment) {
1197 X86ISelAddressMode AM;
1199 if (AvoidDupAddrCompute && !N.hasOneUse()) {
1200 unsigned Opcode = N.getOpcode();
1201 if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1202 Opcode != X86ISD::Wrapper && Opcode != X86ISD::WrapperRIP) {
1203 // If we are able to fold N into addressing mode, then we'll allow it even
1204 // if N has multiple uses. In general, addressing computation is used as
1205 // addresses by all of its uses. But watch out for CopyToReg uses, that
1206 // means the address computation is liveout. It will be computed by a LEA
1207 // so we want to avoid computing the address twice.
1208 for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1209 UE = N.getNode()->use_end(); UI != UE; ++UI) {
1210 if (UI->getOpcode() == ISD::CopyToReg) {
1211 MatchAddressBase(N, AM);
1219 if (!Done && MatchAddress(N, AM))
1222 MVT VT = N.getValueType();
1223 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1224 if (!AM.Base.Reg.getNode())
1225 AM.Base.Reg = CurDAG->getRegister(0, VT);
1228 if (!AM.IndexReg.getNode())
1229 AM.IndexReg = CurDAG->getRegister(0, VT);
1231 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1235 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1236 /// match a load whose top elements are either undef or zeros. The load flavor
1237 /// is derived from the type of N, which is either v4f32 or v2f64.
1238 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1239 SDValue N, SDValue &Base,
1240 SDValue &Scale, SDValue &Index,
1241 SDValue &Disp, SDValue &Segment,
1243 SDValue &OutChain) {
1244 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1245 InChain = N.getOperand(0).getValue(1);
1246 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1247 InChain.getValue(0).hasOneUse() &&
1249 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1250 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1251 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1253 OutChain = LD->getChain();
1258 // Also handle the case where we explicitly require zeros in the top
1259 // elements. This is a vector shuffle from the zero vector.
1260 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1261 // Check to see if the top elements are all zeros (or bitcast of zeros).
1262 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1263 N.getOperand(0).getNode()->hasOneUse() &&
1264 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1265 N.getOperand(0).getOperand(0).hasOneUse()) {
1266 // Okay, this is a zero extending load. Fold it.
1267 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1268 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1270 OutChain = LD->getChain();
1271 InChain = SDValue(LD, 1);
1278 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1279 /// mode it matches can be cost effectively emitted as an LEA instruction.
1280 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1281 SDValue &Base, SDValue &Scale,
1282 SDValue &Index, SDValue &Disp) {
1283 X86ISelAddressMode AM;
1285 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1287 SDValue Copy = AM.Segment;
1288 SDValue T = CurDAG->getRegister(0, MVT::i32);
1290 if (MatchAddress(N, AM))
1292 assert (T == AM.Segment);
1295 MVT VT = N.getValueType();
1296 unsigned Complexity = 0;
1297 if (AM.BaseType == X86ISelAddressMode::RegBase)
1298 if (AM.Base.Reg.getNode())
1301 AM.Base.Reg = CurDAG->getRegister(0, VT);
1302 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1305 if (AM.IndexReg.getNode())
1308 AM.IndexReg = CurDAG->getRegister(0, VT);
1310 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1315 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1316 // to a LEA. This is determined with some expermentation but is by no means
1317 // optimal (especially for code size consideration). LEA is nice because of
1318 // its three-address nature. Tweak the cost function again when we can run
1319 // convertToThreeAddress() at register allocation time.
1320 if (AM.hasSymbolicDisplacement()) {
1321 // For X86-64, we should always use lea to materialize RIP relative
1323 if (Subtarget->is64Bit())
1329 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1332 if (Complexity > 2) {
1334 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1340 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1341 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
1342 SDValue &Scale, SDValue &Index,
1344 assert(Op.getOpcode() == X86ISD::TLSADDR);
1345 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1346 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1348 X86ISelAddressMode AM;
1349 AM.GV = GA->getGlobal();
1350 AM.Disp += GA->getOffset();
1351 AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1352 AM.SymbolFlags = GA->getTargetFlags();
1354 if (N.getValueType() == MVT::i32) {
1356 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1358 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1362 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1367 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1368 SDValue &Base, SDValue &Scale,
1369 SDValue &Index, SDValue &Disp,
1371 if (ISD::isNON_EXTLoad(N.getNode()) &&
1373 IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1374 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1378 /// getGlobalBaseReg - Return an SDNode that returns the value of
1379 /// the global base register. Output instructions required to
1380 /// initialize the global base register, if necessary.
1382 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1383 MachineFunction *MF = CurBB->getParent();
1384 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1385 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1388 static SDNode *FindCallStartFromCall(SDNode *Node) {
1389 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1390 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1391 "Node doesn't have a token chain argument!");
1392 return FindCallStartFromCall(Node->getOperand(0).getNode());
1395 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1396 SDValue Chain = Node->getOperand(0);
1397 SDValue In1 = Node->getOperand(1);
1398 SDValue In2L = Node->getOperand(2);
1399 SDValue In2H = Node->getOperand(3);
1400 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1401 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1403 SDValue LSI = Node->getOperand(4); // MemOperand
1404 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, LSI, Chain};
1405 return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1406 MVT::i32, MVT::i32, MVT::Other, Ops,
1407 array_lengthof(Ops));
1410 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1411 SDNode *Node = N.getNode();
1412 MVT NVT = Node->getValueType(0);
1414 unsigned Opcode = Node->getOpcode();
1415 DebugLoc dl = Node->getDebugLoc();
1418 DOUT << std::string(Indent, ' ') << "Selecting: ";
1419 DEBUG(Node->dump(CurDAG));
1424 if (Node->isMachineOpcode()) {
1426 DOUT << std::string(Indent-2, ' ') << "== ";
1427 DEBUG(Node->dump(CurDAG));
1431 return NULL; // Already selected.
1436 case X86ISD::GlobalBaseReg:
1437 return getGlobalBaseReg();
1439 case X86ISD::ATOMOR64_DAG:
1440 return SelectAtomic64(Node, X86::ATOMOR6432);
1441 case X86ISD::ATOMXOR64_DAG:
1442 return SelectAtomic64(Node, X86::ATOMXOR6432);
1443 case X86ISD::ATOMADD64_DAG:
1444 return SelectAtomic64(Node, X86::ATOMADD6432);
1445 case X86ISD::ATOMSUB64_DAG:
1446 return SelectAtomic64(Node, X86::ATOMSUB6432);
1447 case X86ISD::ATOMNAND64_DAG:
1448 return SelectAtomic64(Node, X86::ATOMNAND6432);
1449 case X86ISD::ATOMAND64_DAG:
1450 return SelectAtomic64(Node, X86::ATOMAND6432);
1451 case X86ISD::ATOMSWAP64_DAG:
1452 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1454 case ISD::SMUL_LOHI:
1455 case ISD::UMUL_LOHI: {
1456 SDValue N0 = Node->getOperand(0);
1457 SDValue N1 = Node->getOperand(1);
1459 bool isSigned = Opcode == ISD::SMUL_LOHI;
1461 switch (NVT.getSimpleVT()) {
1462 default: assert(0 && "Unsupported VT!");
1463 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1464 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1465 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1466 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1469 switch (NVT.getSimpleVT()) {
1470 default: assert(0 && "Unsupported VT!");
1471 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1472 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1473 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1474 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1477 unsigned LoReg, HiReg;
1478 switch (NVT.getSimpleVT()) {
1479 default: assert(0 && "Unsupported VT!");
1480 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1481 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1482 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1483 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1486 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1487 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1488 // multiplty is commmutative
1490 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1495 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1496 N0, SDValue()).getValue(1);
1499 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1502 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1503 array_lengthof(Ops));
1504 InFlag = SDValue(CNode, 1);
1505 // Update the chain.
1506 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1509 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1512 // Copy the low half of the result, if it is needed.
1513 if (!N.getValue(0).use_empty()) {
1514 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1515 LoReg, NVT, InFlag);
1516 InFlag = Result.getValue(2);
1517 ReplaceUses(N.getValue(0), Result);
1519 DOUT << std::string(Indent-2, ' ') << "=> ";
1520 DEBUG(Result.getNode()->dump(CurDAG));
1524 // Copy the high half of the result, if it is needed.
1525 if (!N.getValue(1).use_empty()) {
1527 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1528 // Prevent use of AH in a REX instruction by referencing AX instead.
1529 // Shift it down 8 bits.
1530 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1531 X86::AX, MVT::i16, InFlag);
1532 InFlag = Result.getValue(2);
1533 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1535 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1536 // Then truncate it down to i8.
1537 SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1538 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1539 MVT::i8, Result, SRIdx), 0);
1541 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1542 HiReg, NVT, InFlag);
1543 InFlag = Result.getValue(2);
1545 ReplaceUses(N.getValue(1), Result);
1547 DOUT << std::string(Indent-2, ' ') << "=> ";
1548 DEBUG(Result.getNode()->dump(CurDAG));
1561 case ISD::UDIVREM: {
1562 SDValue N0 = Node->getOperand(0);
1563 SDValue N1 = Node->getOperand(1);
1565 bool isSigned = Opcode == ISD::SDIVREM;
1567 switch (NVT.getSimpleVT()) {
1568 default: assert(0 && "Unsupported VT!");
1569 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1570 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1571 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1572 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1575 switch (NVT.getSimpleVT()) {
1576 default: assert(0 && "Unsupported VT!");
1577 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1578 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1579 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1580 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1583 unsigned LoReg, HiReg;
1584 unsigned ClrOpcode, SExtOpcode;
1585 switch (NVT.getSimpleVT()) {
1586 default: assert(0 && "Unsupported VT!");
1588 LoReg = X86::AL; HiReg = X86::AH;
1590 SExtOpcode = X86::CBW;
1593 LoReg = X86::AX; HiReg = X86::DX;
1594 ClrOpcode = X86::MOV16r0;
1595 SExtOpcode = X86::CWD;
1598 LoReg = X86::EAX; HiReg = X86::EDX;
1599 ClrOpcode = X86::MOV32r0;
1600 SExtOpcode = X86::CDQ;
1603 LoReg = X86::RAX; HiReg = X86::RDX;
1604 ClrOpcode = X86::MOV64r0;
1605 SExtOpcode = X86::CQO;
1609 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1610 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1611 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1614 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1615 // Special case for div8, just use a move with zero extension to AX to
1616 // clear the upper 8 bits (AH).
1617 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1618 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1619 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1621 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16,
1623 array_lengthof(Ops)), 0);
1624 Chain = Move.getValue(1);
1625 ReplaceUses(N0.getValue(1), Chain);
1628 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1629 Chain = CurDAG->getEntryNode();
1631 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1632 InFlag = Chain.getValue(1);
1635 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1636 LoReg, N0, SDValue()).getValue(1);
1637 if (isSigned && !signBitIsZero) {
1638 // Sign extend the low part into the high part.
1640 SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1642 // Zero out the high part, effectively zero extending the input.
1643 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT),
1645 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1646 ClrNode, InFlag).getValue(1);
1651 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1654 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1655 array_lengthof(Ops));
1656 InFlag = SDValue(CNode, 1);
1657 // Update the chain.
1658 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1661 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1664 // Copy the division (low) result, if it is needed.
1665 if (!N.getValue(0).use_empty()) {
1666 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1667 LoReg, NVT, InFlag);
1668 InFlag = Result.getValue(2);
1669 ReplaceUses(N.getValue(0), Result);
1671 DOUT << std::string(Indent-2, ' ') << "=> ";
1672 DEBUG(Result.getNode()->dump(CurDAG));
1676 // Copy the remainder (high) result, if it is needed.
1677 if (!N.getValue(1).use_empty()) {
1679 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1680 // Prevent use of AH in a REX instruction by referencing AX instead.
1681 // Shift it down 8 bits.
1682 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1683 X86::AX, MVT::i16, InFlag);
1684 InFlag = Result.getValue(2);
1685 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1687 CurDAG->getTargetConstant(8, MVT::i8)),
1689 // Then truncate it down to i8.
1690 SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1691 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1692 MVT::i8, Result, SRIdx), 0);
1694 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1695 HiReg, NVT, InFlag);
1696 InFlag = Result.getValue(2);
1698 ReplaceUses(N.getValue(1), Result);
1700 DOUT << std::string(Indent-2, ' ') << "=> ";
1701 DEBUG(Result.getNode()->dump(CurDAG));
1713 case ISD::DECLARE: {
1714 // Handle DECLARE nodes here because the second operand may have been
1715 // wrapped in X86ISD::Wrapper.
1716 SDValue Chain = Node->getOperand(0);
1717 SDValue N1 = Node->getOperand(1);
1718 SDValue N2 = Node->getOperand(2);
1719 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1721 // FIXME: We need to handle this for VLAs.
1723 ReplaceUses(N.getValue(0), Chain);
1727 if (N2.getOpcode() == ISD::ADD &&
1728 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1729 N2 = N2.getOperand(1);
1731 // If N2 is not Wrapper(decriptor) then the llvm.declare is mangled
1732 // somehow, just ignore it.
1733 if (N2.getOpcode() != X86ISD::Wrapper &&
1734 N2.getOpcode() != X86ISD::WrapperRIP) {
1735 ReplaceUses(N.getValue(0), Chain);
1738 GlobalAddressSDNode *GVNode =
1739 dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1741 ReplaceUses(N.getValue(0), Chain);
1744 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1745 TLI.getPointerTy());
1746 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1747 TLI.getPointerTy());
1748 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1749 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE, dl,
1751 array_lengthof(Ops));
1755 SDNode *ResNode = SelectCode(N);
1758 DOUT << std::string(Indent-2, ' ') << "=> ";
1759 if (ResNode == NULL || ResNode == N.getNode())
1760 DEBUG(N.getNode()->dump(CurDAG));
1762 DEBUG(ResNode->dump(CurDAG));
1770 bool X86DAGToDAGISel::
1771 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1772 std::vector<SDValue> &OutOps) {
1773 SDValue Op0, Op1, Op2, Op3, Op4;
1774 switch (ConstraintCode) {
1775 case 'o': // offsetable ??
1776 case 'v': // not offsetable ??
1777 default: return true;
1779 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3, Op4))
1784 OutOps.push_back(Op0);
1785 OutOps.push_back(Op1);
1786 OutOps.push_back(Op2);
1787 OutOps.push_back(Op3);
1788 OutOps.push_back(Op4);
1792 /// createX86ISelDag - This pass converts a legalized DAG into a
1793 /// X86-specific DAG, ready for instruction scheduling.
1795 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1796 llvm::CodeGenOpt::Level OptLevel) {
1797 return new X86DAGToDAGISel(TM, OptLevel);