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/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Streams.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/CommandLine.h"
47 static cl::opt<bool> AvoidDupAddrCompute("x86-avoid-dup-address", cl::Hidden);
49 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
51 //===----------------------------------------------------------------------===//
52 // Pattern Matcher Implementation
53 //===----------------------------------------------------------------------===//
56 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
57 /// SDValue's instead of register numbers for the leaves of the matched
59 struct X86ISelAddressMode {
65 struct { // This is really a union, discriminated by BaseType!
78 unsigned Align; // CP alignment.
79 unsigned char SymbolFlags; // X86II::MO_*
82 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
83 Segment(), GV(0), CP(0), ES(0), JT(-1), Align(0), SymbolFlags(0) {
86 bool hasSymbolicDisplacement() const {
87 return GV != 0 || CP != 0 || ES != 0 || JT != -1;
90 bool hasBaseOrIndexReg() const {
91 return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
94 /// isRIPRelative - Return true if this addressing mode is already RIP
96 bool isRIPRelative() const {
97 if (BaseType != RegBase) return false;
98 if (RegisterSDNode *RegNode =
99 dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
100 return RegNode->getReg() == X86::RIP;
104 void setBaseReg(SDValue Reg) {
110 cerr << "X86ISelAddressMode " << this << "\n";
112 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
114 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
115 cerr << " Scale" << Scale << "\n";
117 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
119 cerr << " Disp " << Disp << "\n";
120 cerr << "GV "; if (GV) GV->dump();
122 cerr << " CP "; if (CP) CP->dump();
125 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
126 cerr << " JT" << JT << " Align" << Align << "\n";
132 //===--------------------------------------------------------------------===//
133 /// ISel - X86 specific code to select X86 machine instructions for
134 /// SelectionDAG operations.
136 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
137 /// X86Lowering - This object fully describes how to lower LLVM code to an
138 /// X86-specific SelectionDAG.
139 X86TargetLowering &X86Lowering;
141 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
142 /// make the right decision when generating code for different targets.
143 const X86Subtarget *Subtarget;
145 /// CurBB - Current BB being isel'd.
147 MachineBasicBlock *CurBB;
149 /// OptForSize - If true, selector should try to optimize for code size
150 /// instead of performance.
154 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
155 : SelectionDAGISel(tm, OptLevel),
156 X86Lowering(*tm.getTargetLowering()),
157 Subtarget(&tm.getSubtarget<X86Subtarget>()),
160 virtual const char *getPassName() const {
161 return "X86 DAG->DAG Instruction Selection";
164 /// InstructionSelect - This callback is invoked by
165 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
166 virtual void InstructionSelect();
168 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
171 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
173 // Include the pieces autogenerated from the target description.
174 #include "X86GenDAGISel.inc"
177 SDNode *Select(SDValue N);
178 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
180 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
181 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
182 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
183 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
184 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
186 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
187 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
188 SDValue &Scale, SDValue &Index, SDValue &Disp,
190 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
191 SDValue &Scale, SDValue &Index, SDValue &Disp);
192 bool SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
193 SDValue &Scale, SDValue &Index, SDValue &Disp);
194 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
195 SDValue N, SDValue &Base, SDValue &Scale,
196 SDValue &Index, SDValue &Disp,
198 SDValue &InChain, SDValue &OutChain);
199 bool TryFoldLoad(SDValue P, SDValue N,
200 SDValue &Base, SDValue &Scale,
201 SDValue &Index, SDValue &Disp,
203 void PreprocessForRMW();
204 void PreprocessForFPConvert();
206 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
207 /// inline asm expressions.
208 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
210 std::vector<SDValue> &OutOps);
212 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
214 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
215 SDValue &Scale, SDValue &Index,
216 SDValue &Disp, SDValue &Segment) {
217 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
218 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
220 Scale = getI8Imm(AM.Scale);
222 // These are 32-bit even in 64-bit mode since RIP relative offset
225 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
228 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
229 AM.Align, AM.Disp, AM.SymbolFlags);
231 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
232 else if (AM.JT != -1)
233 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
235 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
237 if (AM.Segment.getNode())
238 Segment = AM.Segment;
240 Segment = CurDAG->getRegister(0, MVT::i32);
243 /// getI8Imm - Return a target constant with the specified value, of type
245 inline SDValue getI8Imm(unsigned Imm) {
246 return CurDAG->getTargetConstant(Imm, MVT::i8);
249 /// getI16Imm - Return a target constant with the specified value, of type
251 inline SDValue getI16Imm(unsigned Imm) {
252 return CurDAG->getTargetConstant(Imm, MVT::i16);
255 /// getI32Imm - Return a target constant with the specified value, of type
257 inline SDValue getI32Imm(unsigned Imm) {
258 return CurDAG->getTargetConstant(Imm, MVT::i32);
261 /// getGlobalBaseReg - Return an SDNode that returns the value of
262 /// the global base register. Output instructions required to
263 /// initialize the global base register, if necessary.
265 SDNode *getGlobalBaseReg();
267 /// getTargetMachine - Return a reference to the TargetMachine, casted
268 /// to the target-specific type.
269 const X86TargetMachine &getTargetMachine() {
270 return static_cast<const X86TargetMachine &>(TM);
273 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
274 /// to the target-specific type.
275 const X86InstrInfo *getInstrInfo() {
276 return getTargetMachine().getInstrInfo();
286 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
287 SDNode *Root) const {
288 if (OptLevel == CodeGenOpt::None) return false;
291 switch (U->getOpcode()) {
299 SDValue Op1 = U->getOperand(1);
301 // If the other operand is a 8-bit immediate we should fold the immediate
302 // instead. This reduces code size.
304 // movl 4(%esp), %eax
308 // addl 4(%esp), %eax
309 // The former is 2 bytes shorter. In case where the increment is 1, then
310 // the saving can be 4 bytes (by using incl %eax).
311 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
312 if (Imm->getAPIntValue().isSignedIntN(8))
315 // If the other operand is a TLS address, we should fold it instead.
318 // leal i@NTPOFF(%eax), %eax
320 // movl $i@NTPOFF, %eax
322 // if the block also has an access to a second TLS address this will save
324 // FIXME: This is probably also true for non TLS addresses.
325 if (Op1.getOpcode() == X86ISD::Wrapper) {
326 SDValue Val = Op1.getOperand(0);
327 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
333 // Proceed to 'generic' cycle finder code
334 return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
337 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
338 /// and move load below the TokenFactor. Replace store's chain operand with
339 /// load's chain result.
340 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
341 SDValue Store, SDValue TF) {
342 SmallVector<SDValue, 4> Ops;
343 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
344 if (Load.getNode() == TF.getOperand(i).getNode())
345 Ops.push_back(Load.getOperand(0));
347 Ops.push_back(TF.getOperand(i));
348 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
349 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
350 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
351 Store.getOperand(2), Store.getOperand(3));
354 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
356 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
358 if (N.getOpcode() == ISD::BIT_CONVERT)
361 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
362 if (!LD || LD->isVolatile())
364 if (LD->getAddressingMode() != ISD::UNINDEXED)
367 ISD::LoadExtType ExtType = LD->getExtensionType();
368 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
372 N.getOperand(1) == Address &&
373 N.getNode()->isOperandOf(Chain.getNode())) {
380 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
381 /// operand and move load below the call's chain operand.
382 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
383 SDValue Call, SDValue CallSeqStart) {
384 SmallVector<SDValue, 8> Ops;
385 SDValue Chain = CallSeqStart.getOperand(0);
386 if (Chain.getNode() == Load.getNode())
387 Ops.push_back(Load.getOperand(0));
389 assert(Chain.getOpcode() == ISD::TokenFactor &&
390 "Unexpected CallSeqStart chain operand");
391 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
392 if (Chain.getOperand(i).getNode() == Load.getNode())
393 Ops.push_back(Load.getOperand(0));
395 Ops.push_back(Chain.getOperand(i));
397 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
398 MVT::Other, &Ops[0], Ops.size());
400 Ops.push_back(NewChain);
402 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
403 Ops.push_back(CallSeqStart.getOperand(i));
404 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
405 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
406 Load.getOperand(1), Load.getOperand(2));
408 Ops.push_back(SDValue(Load.getNode(), 1));
409 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
410 Ops.push_back(Call.getOperand(i));
411 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
414 /// isCalleeLoad - Return true if call address is a load and it can be
415 /// moved below CALLSEQ_START and the chains leading up to the call.
416 /// Return the CALLSEQ_START by reference as a second output.
417 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
418 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
420 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
423 LD->getAddressingMode() != ISD::UNINDEXED ||
424 LD->getExtensionType() != ISD::NON_EXTLOAD)
427 // Now let's find the callseq_start.
428 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
429 if (!Chain.hasOneUse())
431 Chain = Chain.getOperand(0);
434 if (Chain.getOperand(0).getNode() == Callee.getNode())
436 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
437 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
443 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
444 /// This is only run if not in -O0 mode.
445 /// This allows the instruction selector to pick more read-modify-write
446 /// instructions. This is a common case:
456 /// [TokenFactor] [Op]
463 /// The fact the store's chain operand != load's chain will prevent the
464 /// (store (op (load))) instruction from being selected. We can transform it to:
483 void X86DAGToDAGISel::PreprocessForRMW() {
484 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
485 E = CurDAG->allnodes_end(); I != E; ++I) {
486 if (I->getOpcode() == X86ISD::CALL) {
487 /// Also try moving call address load from outside callseq_start to just
488 /// before the call to allow it to be folded.
506 SDValue Chain = I->getOperand(0);
507 SDValue Load = I->getOperand(1);
508 if (!isCalleeLoad(Load, Chain))
510 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
515 if (!ISD::isNON_TRUNCStore(I))
517 SDValue Chain = I->getOperand(0);
519 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
522 SDValue N1 = I->getOperand(1);
523 SDValue N2 = I->getOperand(2);
524 if ((N1.getValueType().isFloatingPoint() &&
525 !N1.getValueType().isVector()) ||
531 unsigned Opcode = N1.getNode()->getOpcode();
540 case ISD::VECTOR_SHUFFLE: {
541 SDValue N10 = N1.getOperand(0);
542 SDValue N11 = N1.getOperand(1);
543 RModW = isRMWLoad(N10, Chain, N2, Load);
545 RModW = isRMWLoad(N11, Chain, N2, Load);
558 SDValue N10 = N1.getOperand(0);
559 RModW = isRMWLoad(N10, Chain, N2, Load);
565 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
572 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
573 /// nodes that target the FP stack to be store and load to the stack. This is a
574 /// gross hack. We would like to simply mark these as being illegal, but when
575 /// we do that, legalize produces these when it expands calls, then expands
576 /// these in the same legalize pass. We would like dag combine to be able to
577 /// hack on these between the call expansion and the node legalization. As such
578 /// this pass basically does "really late" legalization of these inline with the
580 void X86DAGToDAGISel::PreprocessForFPConvert() {
581 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
582 E = CurDAG->allnodes_end(); I != E; ) {
583 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
584 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
587 // If the source and destination are SSE registers, then this is a legal
588 // conversion that should not be lowered.
589 MVT SrcVT = N->getOperand(0).getValueType();
590 MVT DstVT = N->getValueType(0);
591 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
592 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
593 if (SrcIsSSE && DstIsSSE)
596 if (!SrcIsSSE && !DstIsSSE) {
597 // If this is an FPStack extension, it is a noop.
598 if (N->getOpcode() == ISD::FP_EXTEND)
600 // If this is a value-preserving FPStack truncation, it is a noop.
601 if (N->getConstantOperandVal(1))
605 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
606 // FPStack has extload and truncstore. SSE can fold direct loads into other
607 // operations. Based on this, decide what we want to do.
609 if (N->getOpcode() == ISD::FP_ROUND)
610 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
612 MemVT = SrcIsSSE ? SrcVT : DstVT;
614 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
615 DebugLoc dl = N->getDebugLoc();
617 // FIXME: optimize the case where the src/dest is a load or store?
618 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
620 MemTmp, NULL, 0, MemVT);
621 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
624 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
625 // extload we created. This will cause general havok on the dag because
626 // anything below the conversion could be folded into other existing nodes.
627 // To avoid invalidating 'I', back it up to the convert node.
629 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
631 // Now that we did that, the node is dead. Increment the iterator to the
632 // next node to process, then delete N.
634 CurDAG->DeleteNode(N);
638 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
639 /// when it has created a SelectionDAG for us to codegen.
640 void X86DAGToDAGISel::InstructionSelect() {
641 CurBB = BB; // BB can change as result of isel.
642 const Function *F = CurDAG->getMachineFunction().getFunction();
643 OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
646 if (OptLevel != CodeGenOpt::None)
649 // FIXME: This should only happen when not compiled with -O0.
650 PreprocessForFPConvert();
652 // Codegen the basic block.
654 DOUT << "===== Instruction selection begins:\n";
659 DOUT << "===== Instruction selection ends:\n";
662 CurDAG->RemoveDeadNodes();
665 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
666 /// the main function.
667 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
668 MachineFrameInfo *MFI) {
669 const TargetInstrInfo *TII = TM.getInstrInfo();
670 if (Subtarget->isTargetCygMing())
671 BuildMI(BB, DebugLoc::getUnknownLoc(),
672 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
675 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
676 // If this is main, emit special code for main.
677 MachineBasicBlock *BB = MF.begin();
678 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
679 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
683 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
684 X86ISelAddressMode &AM) {
685 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
686 SDValue Segment = N.getOperand(0);
688 if (AM.Segment.getNode() == 0) {
689 AM.Segment = Segment;
696 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
697 // This optimization is valid because the GNU TLS model defines that
698 // gs:0 (or fs:0 on X86-64) contains its own address.
699 // For more information see http://people.redhat.com/drepper/tls.pdf
701 SDValue Address = N.getOperand(1);
702 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
703 !MatchSegmentBaseAddress (Address, AM))
709 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
710 /// into an addressing mode. These wrap things that will resolve down into a
711 /// symbol reference. If no match is possible, this returns true, otherwise it
713 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
714 // If the addressing mode already has a symbol as the displacement, we can
715 // never match another symbol.
716 if (AM.hasSymbolicDisplacement())
719 SDValue N0 = N.getOperand(0);
721 // Handle X86-64 rip-relative addresses. We check this before checking direct
722 // folding because RIP is preferable to non-RIP accesses.
723 if (Subtarget->is64Bit() &&
724 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
725 // they cannot be folded into immediate fields.
726 // FIXME: This can be improved for kernel and other models?
727 TM.getCodeModel() == CodeModel::Small &&
729 // Base and index reg must be 0 in order to use %rip as base and lowering
731 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
734 int64_t Offset = AM.Disp + G->getOffset();
735 if (!isInt32(Offset)) return true;
736 AM.GV = G->getGlobal();
738 AM.SymbolFlags = G->getTargetFlags();
739 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
740 int64_t Offset = AM.Disp + CP->getOffset();
741 if (!isInt32(Offset)) return true;
742 AM.CP = CP->getConstVal();
743 AM.Align = CP->getAlignment();
745 AM.SymbolFlags = CP->getTargetFlags();
746 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
747 AM.ES = S->getSymbol();
748 AM.SymbolFlags = S->getTargetFlags();
750 JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
751 AM.JT = J->getIndex();
752 AM.SymbolFlags = J->getTargetFlags();
755 if (N.getOpcode() == X86ISD::WrapperRIP)
756 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
760 // Handle the case when globals fit in our immediate field: This is true for
761 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
762 // mode, this results in a non-RIP-relative computation.
763 if (!Subtarget->is64Bit() ||
764 (TM.getCodeModel() == CodeModel::Small &&
765 TM.getRelocationModel() == Reloc::Static)) {
766 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
767 AM.GV = G->getGlobal();
768 AM.Disp += G->getOffset();
769 AM.SymbolFlags = G->getTargetFlags();
770 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
771 AM.CP = CP->getConstVal();
772 AM.Align = CP->getAlignment();
773 AM.Disp += CP->getOffset();
774 AM.SymbolFlags = CP->getTargetFlags();
775 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
776 AM.ES = S->getSymbol();
777 AM.SymbolFlags = S->getTargetFlags();
779 JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
780 AM.JT = J->getIndex();
781 AM.SymbolFlags = J->getTargetFlags();
789 /// MatchAddress - Add the specified node to the specified addressing mode,
790 /// returning true if it cannot be done. This just pattern matches for the
792 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
793 if (MatchAddressRecursively(N, AM, 0))
796 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
797 // a smaller encoding and avoids a scaled-index.
799 AM.BaseType == X86ISelAddressMode::RegBase &&
800 AM.Base.Reg.getNode() == 0) {
801 AM.Base.Reg = AM.IndexReg;
808 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
810 bool is64Bit = Subtarget->is64Bit();
811 DebugLoc dl = N.getDebugLoc();
812 DOUT << "MatchAddress: "; DEBUG(AM.dump());
815 return MatchAddressBase(N, AM);
817 // If this is already a %rip relative address, we can only merge immediates
818 // into it. Instead of handling this in every case, we handle it here.
819 // RIP relative addressing: %rip + 32-bit displacement!
820 if (AM.isRIPRelative()) {
821 // FIXME: JumpTable and ExternalSymbol address currently don't like
822 // displacements. It isn't very important, but this should be fixed for
824 if (!AM.ES && AM.JT != -1) return true;
826 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
827 int64_t Val = AM.Disp + Cst->getSExtValue();
836 switch (N.getOpcode()) {
838 case ISD::Constant: {
839 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
840 if (!is64Bit || isInt32(AM.Disp + Val)) {
847 case X86ISD::SegmentBaseAddress:
848 if (!MatchSegmentBaseAddress(N, AM))
852 case X86ISD::Wrapper:
853 case X86ISD::WrapperRIP:
854 if (!MatchWrapper(N, AM))
859 if (!MatchLoad(N, AM))
863 case ISD::FrameIndex:
864 if (AM.BaseType == X86ISelAddressMode::RegBase
865 && AM.Base.Reg.getNode() == 0) {
866 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
867 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
873 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
877 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
878 unsigned Val = CN->getZExtValue();
879 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
880 // that the base operand remains free for further matching. If
881 // the base doesn't end up getting used, a post-processing step
882 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
883 if (Val == 1 || Val == 2 || Val == 3) {
885 SDValue ShVal = N.getNode()->getOperand(0);
887 // Okay, we know that we have a scale by now. However, if the scaled
888 // value is an add of something and a constant, we can fold the
889 // constant into the disp field here.
890 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
891 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
892 AM.IndexReg = ShVal.getNode()->getOperand(0);
893 ConstantSDNode *AddVal =
894 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
895 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
896 if (!is64Bit || isInt32(Disp))
910 // A mul_lohi where we need the low part can be folded as a plain multiply.
911 if (N.getResNo() != 0) break;
914 case X86ISD::MUL_IMM:
915 // X*[3,5,9] -> X+X*[2,4,8]
916 if (AM.BaseType == X86ISelAddressMode::RegBase &&
917 AM.Base.Reg.getNode() == 0 &&
918 AM.IndexReg.getNode() == 0) {
920 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
921 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
922 CN->getZExtValue() == 9) {
923 AM.Scale = unsigned(CN->getZExtValue())-1;
925 SDValue MulVal = N.getNode()->getOperand(0);
928 // Okay, we know that we have a scale by now. However, if the scaled
929 // value is an add of something and a constant, we can fold the
930 // constant into the disp field here.
931 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
932 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
933 Reg = MulVal.getNode()->getOperand(0);
934 ConstantSDNode *AddVal =
935 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
936 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
938 if (!is64Bit || isInt32(Disp))
941 Reg = N.getNode()->getOperand(0);
943 Reg = N.getNode()->getOperand(0);
946 AM.IndexReg = AM.Base.Reg = Reg;
953 // Given A-B, if A can be completely folded into the address and
954 // the index field with the index field unused, use -B as the index.
955 // This is a win if a has multiple parts that can be folded into
956 // the address. Also, this saves a mov if the base register has
957 // other uses, since it avoids a two-address sub instruction, however
958 // it costs an additional mov if the index register has other uses.
960 // Test if the LHS of the sub can be folded.
961 X86ISelAddressMode Backup = AM;
962 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
966 // Test if the index field is free for use.
967 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
972 SDValue RHS = N.getNode()->getOperand(1);
973 // If the RHS involves a register with multiple uses, this
974 // transformation incurs an extra mov, due to the neg instruction
975 // clobbering its operand.
976 if (!RHS.getNode()->hasOneUse() ||
977 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
978 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
979 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
980 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
981 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
983 // If the base is a register with multiple uses, this
984 // transformation may save a mov.
985 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
986 AM.Base.Reg.getNode() &&
987 !AM.Base.Reg.getNode()->hasOneUse()) ||
988 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
990 // If the folded LHS was interesting, this transformation saves
991 // address arithmetic.
992 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
993 ((AM.Disp != 0) && (Backup.Disp == 0)) +
994 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
996 // If it doesn't look like it may be an overall win, don't do it.
1002 // Ok, the transformation is legal and appears profitable. Go for it.
1003 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
1004 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1008 // Insert the new nodes into the topological ordering.
1009 if (Zero.getNode()->getNodeId() == -1 ||
1010 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1011 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
1012 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
1014 if (Neg.getNode()->getNodeId() == -1 ||
1015 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1016 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
1017 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
1023 X86ISelAddressMode Backup = AM;
1024 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1) &&
1025 !MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1))
1028 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1) &&
1029 !MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1))
1033 // If we couldn't fold both operands into the address at the same time,
1034 // see if we can just put each operand into a register and fold at least
1036 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1037 !AM.Base.Reg.getNode() &&
1038 !AM.IndexReg.getNode()) {
1039 AM.Base.Reg = N.getNode()->getOperand(0);
1040 AM.IndexReg = N.getNode()->getOperand(1);
1048 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1049 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1050 X86ISelAddressMode Backup = AM;
1051 uint64_t Offset = CN->getSExtValue();
1052 // Start with the LHS as an addr mode.
1053 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1054 // Address could not have picked a GV address for the displacement.
1056 // On x86-64, the resultant disp must fit in 32-bits.
1057 (!is64Bit || isInt32(AM.Disp + Offset)) &&
1058 // Check to see if the LHS & C is zero.
1059 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
1068 // Perform some heroic transforms on an and of a constant-count shift
1069 // with a constant to enable use of the scaled offset field.
1071 SDValue Shift = N.getOperand(0);
1072 if (Shift.getNumOperands() != 2) break;
1074 // Scale must not be used already.
1075 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1077 SDValue X = Shift.getOperand(0);
1078 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1079 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1080 if (!C1 || !C2) break;
1082 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1083 // allows us to convert the shift and and into an h-register extract and
1085 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1086 unsigned ScaleLog = 8 - C1->getZExtValue();
1087 if (ScaleLog > 0 && ScaleLog < 4 &&
1088 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1089 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1090 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1091 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1093 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1095 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1096 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1099 // Insert the new nodes into the topological ordering.
1100 if (Eight.getNode()->getNodeId() == -1 ||
1101 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1102 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1103 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1105 if (Mask.getNode()->getNodeId() == -1 ||
1106 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1107 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1108 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1110 if (Srl.getNode()->getNodeId() == -1 ||
1111 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1112 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1113 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1115 if (And.getNode()->getNodeId() == -1 ||
1116 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1117 CurDAG->RepositionNode(N.getNode(), And.getNode());
1118 And.getNode()->setNodeId(N.getNode()->getNodeId());
1120 if (ShlCount.getNode()->getNodeId() == -1 ||
1121 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1122 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1123 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1125 if (Shl.getNode()->getNodeId() == -1 ||
1126 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1127 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1128 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1130 CurDAG->ReplaceAllUsesWith(N, Shl);
1132 AM.Scale = (1 << ScaleLog);
1137 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1138 // allows us to fold the shift into this addressing mode.
1139 if (Shift.getOpcode() != ISD::SHL) break;
1141 // Not likely to be profitable if either the AND or SHIFT node has more
1142 // than one use (unless all uses are for address computation). Besides,
1143 // isel mechanism requires their node ids to be reused.
1144 if (!N.hasOneUse() || !Shift.hasOneUse())
1147 // Verify that the shift amount is something we can fold.
1148 unsigned ShiftCst = C1->getZExtValue();
1149 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1152 // Get the new AND mask, this folds to a constant.
1153 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1154 SDValue(C2, 0), SDValue(C1, 0));
1155 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1157 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1158 NewAND, SDValue(C1, 0));
1160 // Insert the new nodes into the topological ordering.
1161 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1162 CurDAG->RepositionNode(X.getNode(), C1);
1163 C1->setNodeId(X.getNode()->getNodeId());
1165 if (NewANDMask.getNode()->getNodeId() == -1 ||
1166 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1167 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1168 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1170 if (NewAND.getNode()->getNodeId() == -1 ||
1171 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1172 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1173 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1175 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1176 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1177 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1178 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1181 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1183 AM.Scale = 1 << ShiftCst;
1184 AM.IndexReg = NewAND;
1189 return MatchAddressBase(N, AM);
1192 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1193 /// specified addressing mode without any further recursion.
1194 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1195 // Is the base register already occupied?
1196 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1197 // If so, check to see if the scale index register is set.
1198 if (AM.IndexReg.getNode() == 0) {
1204 // Otherwise, we cannot select it.
1208 // Default, generate it as a register.
1209 AM.BaseType = X86ISelAddressMode::RegBase;
1214 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1215 /// It returns the operands which make up the maximal addressing mode it can
1216 /// match by reference.
1217 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1218 SDValue &Scale, SDValue &Index,
1219 SDValue &Disp, SDValue &Segment) {
1220 X86ISelAddressMode AM;
1222 if (AvoidDupAddrCompute && !N.hasOneUse()) {
1223 unsigned Opcode = N.getOpcode();
1224 if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1225 Opcode != X86ISD::Wrapper && Opcode != X86ISD::WrapperRIP) {
1226 // If we are able to fold N into addressing mode, then we'll allow it even
1227 // if N has multiple uses. In general, addressing computation is used as
1228 // addresses by all of its uses. But watch out for CopyToReg uses, that
1229 // means the address computation is liveout. It will be computed by a LEA
1230 // so we want to avoid computing the address twice.
1231 for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1232 UE = N.getNode()->use_end(); UI != UE; ++UI) {
1233 if (UI->getOpcode() == ISD::CopyToReg) {
1234 MatchAddressBase(N, AM);
1242 if (!Done && MatchAddress(N, AM))
1245 MVT VT = N.getValueType();
1246 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1247 if (!AM.Base.Reg.getNode())
1248 AM.Base.Reg = CurDAG->getRegister(0, VT);
1251 if (!AM.IndexReg.getNode())
1252 AM.IndexReg = CurDAG->getRegister(0, VT);
1254 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1258 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1259 /// match a load whose top elements are either undef or zeros. The load flavor
1260 /// is derived from the type of N, which is either v4f32 or v2f64.
1261 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1262 SDValue N, SDValue &Base,
1263 SDValue &Scale, SDValue &Index,
1264 SDValue &Disp, SDValue &Segment,
1266 SDValue &OutChain) {
1267 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1268 InChain = N.getOperand(0).getValue(1);
1269 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1270 InChain.getValue(0).hasOneUse() &&
1272 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1273 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1274 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1276 OutChain = LD->getChain();
1281 // Also handle the case where we explicitly require zeros in the top
1282 // elements. This is a vector shuffle from the zero vector.
1283 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1284 // Check to see if the top elements are all zeros (or bitcast of zeros).
1285 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1286 N.getOperand(0).getNode()->hasOneUse() &&
1287 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1288 N.getOperand(0).getOperand(0).hasOneUse()) {
1289 // Okay, this is a zero extending load. Fold it.
1290 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1291 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1293 OutChain = LD->getChain();
1294 InChain = SDValue(LD, 1);
1301 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1302 /// mode it matches can be cost effectively emitted as an LEA instruction.
1303 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1304 SDValue &Base, SDValue &Scale,
1305 SDValue &Index, SDValue &Disp) {
1306 X86ISelAddressMode AM;
1308 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1310 SDValue Copy = AM.Segment;
1311 SDValue T = CurDAG->getRegister(0, MVT::i32);
1313 if (MatchAddress(N, AM))
1315 assert (T == AM.Segment);
1318 MVT VT = N.getValueType();
1319 unsigned Complexity = 0;
1320 if (AM.BaseType == X86ISelAddressMode::RegBase)
1321 if (AM.Base.Reg.getNode())
1324 AM.Base.Reg = CurDAG->getRegister(0, VT);
1325 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1328 if (AM.IndexReg.getNode())
1331 AM.IndexReg = CurDAG->getRegister(0, VT);
1333 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1338 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1339 // to a LEA. This is determined with some expermentation but is by no means
1340 // optimal (especially for code size consideration). LEA is nice because of
1341 // its three-address nature. Tweak the cost function again when we can run
1342 // convertToThreeAddress() at register allocation time.
1343 if (AM.hasSymbolicDisplacement()) {
1344 // For X86-64, we should always use lea to materialize RIP relative
1346 if (Subtarget->is64Bit())
1352 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1355 // If it isn't worth using an LEA, reject it.
1356 if (Complexity <= 2)
1360 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1364 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1365 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
1366 SDValue &Scale, SDValue &Index,
1368 assert(Op.getOpcode() == X86ISD::TLSADDR);
1369 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1370 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1372 X86ISelAddressMode AM;
1373 AM.GV = GA->getGlobal();
1374 AM.Disp += GA->getOffset();
1375 AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1376 AM.SymbolFlags = GA->getTargetFlags();
1378 if (N.getValueType() == MVT::i32) {
1380 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1382 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1386 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1391 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1392 SDValue &Base, SDValue &Scale,
1393 SDValue &Index, SDValue &Disp,
1395 if (ISD::isNON_EXTLoad(N.getNode()) &&
1397 IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1398 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1402 /// getGlobalBaseReg - Return an SDNode that returns the value of
1403 /// the global base register. Output instructions required to
1404 /// initialize the global base register, if necessary.
1406 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1407 MachineFunction *MF = CurBB->getParent();
1408 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1409 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1412 static SDNode *FindCallStartFromCall(SDNode *Node) {
1413 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1414 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1415 "Node doesn't have a token chain argument!");
1416 return FindCallStartFromCall(Node->getOperand(0).getNode());
1419 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1420 SDValue Chain = Node->getOperand(0);
1421 SDValue In1 = Node->getOperand(1);
1422 SDValue In2L = Node->getOperand(2);
1423 SDValue In2H = Node->getOperand(3);
1424 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1425 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1427 SDValue LSI = Node->getOperand(4); // MemOperand
1428 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, LSI, Chain};
1429 return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1430 MVT::i32, MVT::i32, MVT::Other, Ops,
1431 array_lengthof(Ops));
1434 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1435 SDNode *Node = N.getNode();
1436 MVT NVT = Node->getValueType(0);
1438 unsigned Opcode = Node->getOpcode();
1439 DebugLoc dl = Node->getDebugLoc();
1442 DOUT << std::string(Indent, ' ') << "Selecting: ";
1443 DEBUG(Node->dump(CurDAG));
1448 if (Node->isMachineOpcode()) {
1450 DOUT << std::string(Indent-2, ' ') << "== ";
1451 DEBUG(Node->dump(CurDAG));
1455 return NULL; // Already selected.
1460 case X86ISD::GlobalBaseReg:
1461 return getGlobalBaseReg();
1463 case X86ISD::ATOMOR64_DAG:
1464 return SelectAtomic64(Node, X86::ATOMOR6432);
1465 case X86ISD::ATOMXOR64_DAG:
1466 return SelectAtomic64(Node, X86::ATOMXOR6432);
1467 case X86ISD::ATOMADD64_DAG:
1468 return SelectAtomic64(Node, X86::ATOMADD6432);
1469 case X86ISD::ATOMSUB64_DAG:
1470 return SelectAtomic64(Node, X86::ATOMSUB6432);
1471 case X86ISD::ATOMNAND64_DAG:
1472 return SelectAtomic64(Node, X86::ATOMNAND6432);
1473 case X86ISD::ATOMAND64_DAG:
1474 return SelectAtomic64(Node, X86::ATOMAND6432);
1475 case X86ISD::ATOMSWAP64_DAG:
1476 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1478 case ISD::SMUL_LOHI:
1479 case ISD::UMUL_LOHI: {
1480 SDValue N0 = Node->getOperand(0);
1481 SDValue N1 = Node->getOperand(1);
1483 bool isSigned = Opcode == ISD::SMUL_LOHI;
1485 switch (NVT.getSimpleVT()) {
1486 default: llvm_unreachable("Unsupported VT!");
1487 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1488 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1489 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1490 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1493 switch (NVT.getSimpleVT()) {
1494 default: llvm_unreachable("Unsupported VT!");
1495 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1496 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1497 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1498 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1501 unsigned LoReg, HiReg;
1502 switch (NVT.getSimpleVT()) {
1503 default: llvm_unreachable("Unsupported VT!");
1504 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1505 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1506 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1507 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1510 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1511 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1512 // multiplty is commmutative
1514 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1519 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1520 N0, SDValue()).getValue(1);
1523 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1526 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1527 array_lengthof(Ops));
1528 InFlag = SDValue(CNode, 1);
1529 // Update the chain.
1530 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1533 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1536 // Copy the low half of the result, if it is needed.
1537 if (!N.getValue(0).use_empty()) {
1538 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1539 LoReg, NVT, InFlag);
1540 InFlag = Result.getValue(2);
1541 ReplaceUses(N.getValue(0), Result);
1543 DOUT << std::string(Indent-2, ' ') << "=> ";
1544 DEBUG(Result.getNode()->dump(CurDAG));
1548 // Copy the high half of the result, if it is needed.
1549 if (!N.getValue(1).use_empty()) {
1551 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1552 // Prevent use of AH in a REX instruction by referencing AX instead.
1553 // Shift it down 8 bits.
1554 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1555 X86::AX, MVT::i16, InFlag);
1556 InFlag = Result.getValue(2);
1557 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1559 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1560 // Then truncate it down to i8.
1561 SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1562 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1563 MVT::i8, Result, SRIdx), 0);
1565 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1566 HiReg, NVT, InFlag);
1567 InFlag = Result.getValue(2);
1569 ReplaceUses(N.getValue(1), Result);
1571 DOUT << std::string(Indent-2, ' ') << "=> ";
1572 DEBUG(Result.getNode()->dump(CurDAG));
1585 case ISD::UDIVREM: {
1586 SDValue N0 = Node->getOperand(0);
1587 SDValue N1 = Node->getOperand(1);
1589 bool isSigned = Opcode == ISD::SDIVREM;
1591 switch (NVT.getSimpleVT()) {
1592 default: llvm_unreachable("Unsupported VT!");
1593 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1594 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1595 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1596 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1599 switch (NVT.getSimpleVT()) {
1600 default: llvm_unreachable("Unsupported VT!");
1601 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1602 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1603 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1604 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1607 unsigned LoReg, HiReg;
1608 unsigned ClrOpcode, SExtOpcode;
1609 switch (NVT.getSimpleVT()) {
1610 default: llvm_unreachable("Unsupported VT!");
1612 LoReg = X86::AL; HiReg = X86::AH;
1614 SExtOpcode = X86::CBW;
1617 LoReg = X86::AX; HiReg = X86::DX;
1618 ClrOpcode = X86::MOV16r0;
1619 SExtOpcode = X86::CWD;
1622 LoReg = X86::EAX; HiReg = X86::EDX;
1623 ClrOpcode = X86::MOV32r0;
1624 SExtOpcode = X86::CDQ;
1627 LoReg = X86::RAX; HiReg = X86::RDX;
1628 ClrOpcode = ~0U; // NOT USED.
1629 SExtOpcode = X86::CQO;
1633 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1634 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1635 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1638 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1639 // Special case for div8, just use a move with zero extension to AX to
1640 // clear the upper 8 bits (AH).
1641 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1642 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1643 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1645 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16,
1647 array_lengthof(Ops)), 0);
1648 Chain = Move.getValue(1);
1649 ReplaceUses(N0.getValue(1), Chain);
1652 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1653 Chain = CurDAG->getEntryNode();
1655 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1656 InFlag = Chain.getValue(1);
1659 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1660 LoReg, N0, SDValue()).getValue(1);
1661 if (isSigned && !signBitIsZero) {
1662 // Sign extend the low part into the high part.
1664 SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1666 // Zero out the high part, effectively zero extending the input.
1669 if (NVT.getSimpleVT() == MVT::i64) {
1670 ClrNode = SDValue(CurDAG->getTargetNode(X86::MOV32r0, dl, MVT::i32),
1672 // We just did a 32-bit clear, insert it into a 64-bit register to
1673 // clear the whole 64-bit reg.
1675 SDValue(CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
1678 CurDAG->getTargetConstant(X86::SUBREG_32BIT, MVT::i32);
1680 SDValue(CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG, dl,
1681 MVT::i64, Undef, ClrNode, SubRegNo),
1684 ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT), 0);
1687 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1688 ClrNode, InFlag).getValue(1);
1693 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1696 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1697 array_lengthof(Ops));
1698 InFlag = SDValue(CNode, 1);
1699 // Update the chain.
1700 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1703 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1706 // Copy the division (low) result, if it is needed.
1707 if (!N.getValue(0).use_empty()) {
1708 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1709 LoReg, NVT, InFlag);
1710 InFlag = Result.getValue(2);
1711 ReplaceUses(N.getValue(0), Result);
1713 DOUT << std::string(Indent-2, ' ') << "=> ";
1714 DEBUG(Result.getNode()->dump(CurDAG));
1718 // Copy the remainder (high) result, if it is needed.
1719 if (!N.getValue(1).use_empty()) {
1721 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1722 // Prevent use of AH in a REX instruction by referencing AX instead.
1723 // Shift it down 8 bits.
1724 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1725 X86::AX, MVT::i16, InFlag);
1726 InFlag = Result.getValue(2);
1727 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1729 CurDAG->getTargetConstant(8, MVT::i8)),
1731 // Then truncate it down to i8.
1732 SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1733 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1734 MVT::i8, Result, SRIdx), 0);
1736 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1737 HiReg, NVT, InFlag);
1738 InFlag = Result.getValue(2);
1740 ReplaceUses(N.getValue(1), Result);
1742 DOUT << std::string(Indent-2, ' ') << "=> ";
1743 DEBUG(Result.getNode()->dump(CurDAG));
1755 case ISD::DECLARE: {
1756 // Handle DECLARE nodes here because the second operand may have been
1757 // wrapped in X86ISD::Wrapper.
1758 SDValue Chain = Node->getOperand(0);
1759 SDValue N1 = Node->getOperand(1);
1760 SDValue N2 = Node->getOperand(2);
1761 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1763 // FIXME: We need to handle this for VLAs.
1765 ReplaceUses(N.getValue(0), Chain);
1769 if (N2.getOpcode() == ISD::ADD &&
1770 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1771 N2 = N2.getOperand(1);
1773 // If N2 is not Wrapper(decriptor) then the llvm.declare is mangled
1774 // somehow, just ignore it.
1775 if (N2.getOpcode() != X86ISD::Wrapper &&
1776 N2.getOpcode() != X86ISD::WrapperRIP) {
1777 ReplaceUses(N.getValue(0), Chain);
1780 GlobalAddressSDNode *GVNode =
1781 dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1783 ReplaceUses(N.getValue(0), Chain);
1786 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1787 TLI.getPointerTy());
1788 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1789 TLI.getPointerTy());
1790 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1791 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE, dl,
1793 array_lengthof(Ops));
1797 SDNode *ResNode = SelectCode(N);
1800 DOUT << std::string(Indent-2, ' ') << "=> ";
1801 if (ResNode == NULL || ResNode == N.getNode())
1802 DEBUG(N.getNode()->dump(CurDAG));
1804 DEBUG(ResNode->dump(CurDAG));
1812 bool X86DAGToDAGISel::
1813 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1814 std::vector<SDValue> &OutOps) {
1815 SDValue Op0, Op1, Op2, Op3, Op4;
1816 switch (ConstraintCode) {
1817 case 'o': // offsetable ??
1818 case 'v': // not offsetable ??
1819 default: return true;
1821 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3, Op4))
1826 OutOps.push_back(Op0);
1827 OutOps.push_back(Op1);
1828 OutOps.push_back(Op2);
1829 OutOps.push_back(Op3);
1830 OutOps.push_back(Op4);
1834 /// createX86ISelDag - This pass converts a legalized DAG into a
1835 /// X86-specific DAG, ready for instruction scheduling.
1837 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1838 llvm::CodeGenOpt::Level OptLevel) {
1839 return new X86DAGToDAGISel(TM, OptLevel);