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/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
51 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52 /// SDValue's instead of register numbers for the leaves of the matched
54 struct X86ISelAddressMode {
60 struct { // This is really a union, discriminated by BaseType!
71 BlockAddress *BlockAddr;
74 unsigned Align; // CP alignment.
75 unsigned char SymbolFlags; // X86II::MO_*
78 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
79 Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
80 SymbolFlags(X86II::MO_NO_FLAG) {
83 bool hasSymbolicDisplacement() const {
84 return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
87 bool hasBaseOrIndexReg() const {
88 return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
91 /// isRIPRelative - Return true if this addressing mode is already RIP
93 bool isRIPRelative() const {
94 if (BaseType != RegBase) return false;
95 if (RegisterSDNode *RegNode =
96 dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
97 return RegNode->getReg() == X86::RIP;
101 void setBaseReg(SDValue Reg) {
107 dbgs() << "X86ISelAddressMode " << this << '\n';
108 dbgs() << "Base.Reg ";
109 if (Base.Reg.getNode() != 0)
110 Base.Reg.getNode()->dump();
113 dbgs() << " Base.FrameIndex " << Base.FrameIndex << '\n'
114 << " Scale" << Scale << '\n'
116 if (IndexReg.getNode() != 0)
117 IndexReg.getNode()->dump();
120 dbgs() << " Disp " << Disp << '\n'
137 dbgs() << " JT" << JT << " Align" << Align << '\n';
143 class X86ISelListener : public SelectionDAG::DAGUpdateListener {
144 SmallSet<SDNode*, 4> Deletes;
146 explicit X86ISelListener() {}
147 virtual void NodeDeleted(SDNode *N, SDNode *E) {
150 virtual void NodeUpdated(SDNode *N) {
153 bool IsDeleted(SDNode *N) {
154 return Deletes.count(N);
158 //===--------------------------------------------------------------------===//
159 /// ISel - X86 specific code to select X86 machine instructions for
160 /// SelectionDAG operations.
162 class X86DAGToDAGISel : public SelectionDAGISel {
163 /// X86Lowering - This object fully describes how to lower LLVM code to an
164 /// X86-specific SelectionDAG.
165 X86TargetLowering &X86Lowering;
167 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
168 /// make the right decision when generating code for different targets.
169 const X86Subtarget *Subtarget;
171 /// OptForSize - If true, selector should try to optimize for code size
172 /// instead of performance.
176 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
177 : SelectionDAGISel(tm, OptLevel),
178 X86Lowering(*tm.getTargetLowering()),
179 Subtarget(&tm.getSubtarget<X86Subtarget>()),
182 virtual const char *getPassName() const {
183 return "X86 DAG->DAG Instruction Selection";
186 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
188 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
190 virtual void PreprocessISelDAG();
192 // Include the pieces autogenerated from the target description.
193 #include "X86GenDAGISel.inc"
196 SDNode *Select(SDNode *N);
197 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
198 SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
200 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
201 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
202 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
203 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
204 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
205 X86ISelListener &DeadNodes,
207 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
208 bool SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
209 SDValue &Scale, SDValue &Index, SDValue &Disp,
211 bool SelectLEAAddr(SDNode *Op, SDValue N, SDValue &Base,
212 SDValue &Scale, SDValue &Index, SDValue &Disp);
213 bool SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
214 SDValue &Scale, SDValue &Index, SDValue &Disp);
215 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
216 SDValue &Base, SDValue &Scale,
217 SDValue &Index, SDValue &Disp,
219 SDValue &NodeWithChain);
221 bool TryFoldLoad(SDNode *P, SDValue N,
222 SDValue &Base, SDValue &Scale,
223 SDValue &Index, SDValue &Disp,
226 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
227 /// inline asm expressions.
228 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
230 std::vector<SDValue> &OutOps);
232 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
234 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
235 SDValue &Scale, SDValue &Index,
236 SDValue &Disp, SDValue &Segment) {
237 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
238 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
240 Scale = getI8Imm(AM.Scale);
242 // These are 32-bit even in 64-bit mode since RIP relative offset
245 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
248 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
249 AM.Align, AM.Disp, AM.SymbolFlags);
251 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
252 else if (AM.JT != -1)
253 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
254 else if (AM.BlockAddr)
255 Disp = CurDAG->getBlockAddress(AM.BlockAddr, MVT::i32,
256 true, AM.SymbolFlags);
258 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
260 if (AM.Segment.getNode())
261 Segment = AM.Segment;
263 Segment = CurDAG->getRegister(0, MVT::i32);
266 /// getI8Imm - Return a target constant with the specified value, of type
268 inline SDValue getI8Imm(unsigned Imm) {
269 return CurDAG->getTargetConstant(Imm, MVT::i8);
272 /// getI16Imm - Return a target constant with the specified value, of type
274 inline SDValue getI16Imm(unsigned Imm) {
275 return CurDAG->getTargetConstant(Imm, MVT::i16);
278 /// getI32Imm - Return a target constant with the specified value, of type
280 inline SDValue getI32Imm(unsigned Imm) {
281 return CurDAG->getTargetConstant(Imm, MVT::i32);
284 /// getGlobalBaseReg - Return an SDNode that returns the value of
285 /// the global base register. Output instructions required to
286 /// initialize the global base register, if necessary.
288 SDNode *getGlobalBaseReg();
290 /// getTargetMachine - Return a reference to the TargetMachine, casted
291 /// to the target-specific type.
292 const X86TargetMachine &getTargetMachine() {
293 return static_cast<const X86TargetMachine &>(TM);
296 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
297 /// to the target-specific type.
298 const X86InstrInfo *getInstrInfo() {
299 return getTargetMachine().getInstrInfo();
306 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
307 if (OptLevel == CodeGenOpt::None) return false;
312 if (N.getOpcode() != ISD::LOAD)
315 // If N is a load, do additional profitability checks.
317 switch (U->getOpcode()) {
330 SDValue Op1 = U->getOperand(1);
332 // If the other operand is a 8-bit immediate we should fold the immediate
333 // instead. This reduces code size.
335 // movl 4(%esp), %eax
339 // addl 4(%esp), %eax
340 // The former is 2 bytes shorter. In case where the increment is 1, then
341 // the saving can be 4 bytes (by using incl %eax).
342 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
343 if (Imm->getAPIntValue().isSignedIntN(8))
346 // If the other operand is a TLS address, we should fold it instead.
349 // leal i@NTPOFF(%eax), %eax
351 // movl $i@NTPOFF, %eax
353 // if the block also has an access to a second TLS address this will save
355 // FIXME: This is probably also true for non TLS addresses.
356 if (Op1.getOpcode() == X86ISD::Wrapper) {
357 SDValue Val = Op1.getOperand(0);
358 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
368 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
369 /// load's chain operand and move load below the call's chain operand.
370 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
371 SDValue Call, SDValue OrigChain) {
372 SmallVector<SDValue, 8> Ops;
373 SDValue Chain = OrigChain.getOperand(0);
374 if (Chain.getNode() == Load.getNode())
375 Ops.push_back(Load.getOperand(0));
377 assert(Chain.getOpcode() == ISD::TokenFactor &&
378 "Unexpected chain operand");
379 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
380 if (Chain.getOperand(i).getNode() == Load.getNode())
381 Ops.push_back(Load.getOperand(0));
383 Ops.push_back(Chain.getOperand(i));
385 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
386 MVT::Other, &Ops[0], Ops.size());
388 Ops.push_back(NewChain);
390 for (unsigned i = 1, e = OrigChain.getNumOperands(); i != e; ++i)
391 Ops.push_back(OrigChain.getOperand(i));
392 CurDAG->UpdateNodeOperands(OrigChain, &Ops[0], Ops.size());
393 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
394 Load.getOperand(1), Load.getOperand(2));
396 Ops.push_back(SDValue(Load.getNode(), 1));
397 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
398 Ops.push_back(Call.getOperand(i));
399 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
402 /// isCalleeLoad - Return true if call address is a load and it can be
403 /// moved below CALLSEQ_START and the chains leading up to the call.
404 /// Return the CALLSEQ_START by reference as a second output.
405 /// In the case of a tail call, there isn't a callseq node between the call
406 /// chain and the load.
407 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
408 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
410 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
413 LD->getAddressingMode() != ISD::UNINDEXED ||
414 LD->getExtensionType() != ISD::NON_EXTLOAD)
417 // Now let's find the callseq_start.
418 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
419 if (!Chain.hasOneUse())
421 Chain = Chain.getOperand(0);
424 if (!Chain.getNumOperands())
426 if (Chain.getOperand(0).getNode() == Callee.getNode())
428 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
429 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
430 Callee.getValue(1).hasOneUse())
435 void X86DAGToDAGISel::PreprocessISelDAG() {
436 // OptForSize is used in pattern predicates that isel is matching.
437 OptForSize = MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize);
439 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
440 E = CurDAG->allnodes_end(); I != E; ) {
441 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
443 if (OptLevel != CodeGenOpt::None &&
444 (N->getOpcode() == X86ISD::CALL ||
445 N->getOpcode() == X86ISD::TC_RETURN)) {
446 /// Also try moving call address load from outside callseq_start to just
447 /// before the call to allow it to be folded.
465 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
466 SDValue Chain = N->getOperand(0);
467 SDValue Load = N->getOperand(1);
468 if (!isCalleeLoad(Load, Chain, HasCallSeq))
470 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
475 // Lower fpround and fpextend nodes that target the FP stack to be store and
476 // load to the stack. This is a gross hack. We would like to simply mark
477 // these as being illegal, but when we do that, legalize produces these when
478 // it expands calls, then expands these in the same legalize pass. We would
479 // like dag combine to be able to hack on these between the call expansion
480 // and the node legalization. As such this pass basically does "really
481 // late" legalization of these inline with the X86 isel pass.
482 // FIXME: This should only happen when not compiled with -O0.
483 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
486 // If the source and destination are SSE registers, then this is a legal
487 // conversion that should not be lowered.
488 EVT SrcVT = N->getOperand(0).getValueType();
489 EVT DstVT = N->getValueType(0);
490 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
491 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
492 if (SrcIsSSE && DstIsSSE)
495 if (!SrcIsSSE && !DstIsSSE) {
496 // If this is an FPStack extension, it is a noop.
497 if (N->getOpcode() == ISD::FP_EXTEND)
499 // If this is a value-preserving FPStack truncation, it is a noop.
500 if (N->getConstantOperandVal(1))
504 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
505 // FPStack has extload and truncstore. SSE can fold direct loads into other
506 // operations. Based on this, decide what we want to do.
508 if (N->getOpcode() == ISD::FP_ROUND)
509 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
511 MemVT = SrcIsSSE ? SrcVT : DstVT;
513 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
514 DebugLoc dl = N->getDebugLoc();
516 // FIXME: optimize the case where the src/dest is a load or store?
517 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
519 MemTmp, NULL, 0, MemVT,
521 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
522 NULL, 0, MemVT, false, false, 0);
524 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
525 // extload we created. This will cause general havok on the dag because
526 // anything below the conversion could be folded into other existing nodes.
527 // To avoid invalidating 'I', back it up to the convert node.
529 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
531 // Now that we did that, the node is dead. Increment the iterator to the
532 // next node to process, then delete N.
534 CurDAG->DeleteNode(N);
539 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
540 /// the main function.
541 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
542 MachineFrameInfo *MFI) {
543 const TargetInstrInfo *TII = TM.getInstrInfo();
544 if (Subtarget->isTargetCygMing())
545 BuildMI(BB, DebugLoc(),
546 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
549 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
550 // If this is main, emit special code for main.
551 MachineBasicBlock *BB = MF.begin();
552 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
553 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
557 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
558 X86ISelAddressMode &AM) {
559 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
560 SDValue Segment = N.getOperand(0);
562 if (AM.Segment.getNode() == 0) {
563 AM.Segment = Segment;
570 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
571 // This optimization is valid because the GNU TLS model defines that
572 // gs:0 (or fs:0 on X86-64) contains its own address.
573 // For more information see http://people.redhat.com/drepper/tls.pdf
575 SDValue Address = N.getOperand(1);
576 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
577 !MatchSegmentBaseAddress (Address, AM))
583 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
584 /// into an addressing mode. These wrap things that will resolve down into a
585 /// symbol reference. If no match is possible, this returns true, otherwise it
587 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
588 // If the addressing mode already has a symbol as the displacement, we can
589 // never match another symbol.
590 if (AM.hasSymbolicDisplacement())
593 SDValue N0 = N.getOperand(0);
594 CodeModel::Model M = TM.getCodeModel();
596 // Handle X86-64 rip-relative addresses. We check this before checking direct
597 // folding because RIP is preferable to non-RIP accesses.
598 if (Subtarget->is64Bit() &&
599 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
600 // they cannot be folded into immediate fields.
601 // FIXME: This can be improved for kernel and other models?
602 (M == CodeModel::Small || M == CodeModel::Kernel) &&
603 // Base and index reg must be 0 in order to use %rip as base and lowering
605 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
606 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
607 int64_t Offset = AM.Disp + G->getOffset();
608 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
609 AM.GV = G->getGlobal();
611 AM.SymbolFlags = G->getTargetFlags();
612 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
613 int64_t Offset = AM.Disp + CP->getOffset();
614 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
615 AM.CP = CP->getConstVal();
616 AM.Align = CP->getAlignment();
618 AM.SymbolFlags = CP->getTargetFlags();
619 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
620 AM.ES = S->getSymbol();
621 AM.SymbolFlags = S->getTargetFlags();
622 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
623 AM.JT = J->getIndex();
624 AM.SymbolFlags = J->getTargetFlags();
626 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
627 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
630 if (N.getOpcode() == X86ISD::WrapperRIP)
631 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
635 // Handle the case when globals fit in our immediate field: This is true for
636 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
637 // mode, this results in a non-RIP-relative computation.
638 if (!Subtarget->is64Bit() ||
639 ((M == CodeModel::Small || M == CodeModel::Kernel) &&
640 TM.getRelocationModel() == Reloc::Static)) {
641 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
642 AM.GV = G->getGlobal();
643 AM.Disp += G->getOffset();
644 AM.SymbolFlags = G->getTargetFlags();
645 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
646 AM.CP = CP->getConstVal();
647 AM.Align = CP->getAlignment();
648 AM.Disp += CP->getOffset();
649 AM.SymbolFlags = CP->getTargetFlags();
650 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
651 AM.ES = S->getSymbol();
652 AM.SymbolFlags = S->getTargetFlags();
653 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
654 AM.JT = J->getIndex();
655 AM.SymbolFlags = J->getTargetFlags();
657 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
658 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
666 /// MatchAddress - Add the specified node to the specified addressing mode,
667 /// returning true if it cannot be done. This just pattern matches for the
669 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
670 X86ISelListener DeadNodes;
671 if (MatchAddressRecursively(N, AM, DeadNodes, 0))
674 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
675 // a smaller encoding and avoids a scaled-index.
677 AM.BaseType == X86ISelAddressMode::RegBase &&
678 AM.Base.Reg.getNode() == 0) {
679 AM.Base.Reg = AM.IndexReg;
683 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
684 // because it has a smaller encoding.
685 // TODO: Which other code models can use this?
686 if (TM.getCodeModel() == CodeModel::Small &&
687 Subtarget->is64Bit() &&
689 AM.BaseType == X86ISelAddressMode::RegBase &&
690 AM.Base.Reg.getNode() == 0 &&
691 AM.IndexReg.getNode() == 0 &&
692 AM.SymbolFlags == X86II::MO_NO_FLAG &&
693 AM.hasSymbolicDisplacement())
694 AM.Base.Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
699 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
700 X86ISelListener &DeadNodes,
702 bool is64Bit = Subtarget->is64Bit();
703 DebugLoc dl = N.getDebugLoc();
705 dbgs() << "MatchAddress: ";
710 return MatchAddressBase(N, AM);
712 CodeModel::Model M = TM.getCodeModel();
714 // If this is already a %rip relative address, we can only merge immediates
715 // into it. Instead of handling this in every case, we handle it here.
716 // RIP relative addressing: %rip + 32-bit displacement!
717 if (AM.isRIPRelative()) {
718 // FIXME: JumpTable and ExternalSymbol address currently don't like
719 // displacements. It isn't very important, but this should be fixed for
721 if (!AM.ES && AM.JT != -1) return true;
723 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
724 int64_t Val = AM.Disp + Cst->getSExtValue();
725 if (X86::isOffsetSuitableForCodeModel(Val, M,
726 AM.hasSymbolicDisplacement())) {
734 switch (N.getOpcode()) {
736 case ISD::Constant: {
737 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
739 X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
740 AM.hasSymbolicDisplacement())) {
747 case X86ISD::SegmentBaseAddress:
748 if (!MatchSegmentBaseAddress(N, AM))
752 case X86ISD::Wrapper:
753 case X86ISD::WrapperRIP:
754 if (!MatchWrapper(N, AM))
759 if (!MatchLoad(N, AM))
763 case ISD::FrameIndex:
764 if (AM.BaseType == X86ISelAddressMode::RegBase
765 && AM.Base.Reg.getNode() == 0) {
766 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
767 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
773 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
777 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
778 unsigned Val = CN->getZExtValue();
779 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
780 // that the base operand remains free for further matching. If
781 // the base doesn't end up getting used, a post-processing step
782 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
783 if (Val == 1 || Val == 2 || Val == 3) {
785 SDValue ShVal = N.getNode()->getOperand(0);
787 // Okay, we know that we have a scale by now. However, if the scaled
788 // value is an add of something and a constant, we can fold the
789 // constant into the disp field here.
790 if (ShVal.getNode()->getOpcode() == ISD::ADD &&
791 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
792 AM.IndexReg = ShVal.getNode()->getOperand(0);
793 ConstantSDNode *AddVal =
794 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
795 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
797 X86::isOffsetSuitableForCodeModel(Disp, M,
798 AM.hasSymbolicDisplacement()))
812 // A mul_lohi where we need the low part can be folded as a plain multiply.
813 if (N.getResNo() != 0) break;
816 case X86ISD::MUL_IMM:
817 // X*[3,5,9] -> X+X*[2,4,8]
818 if (AM.BaseType == X86ISelAddressMode::RegBase &&
819 AM.Base.Reg.getNode() == 0 &&
820 AM.IndexReg.getNode() == 0) {
822 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
823 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
824 CN->getZExtValue() == 9) {
825 AM.Scale = unsigned(CN->getZExtValue())-1;
827 SDValue MulVal = N.getNode()->getOperand(0);
830 // Okay, we know that we have a scale by now. However, if the scaled
831 // value is an add of something and a constant, we can fold the
832 // constant into the disp field here.
833 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
834 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
835 Reg = MulVal.getNode()->getOperand(0);
836 ConstantSDNode *AddVal =
837 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
838 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
841 X86::isOffsetSuitableForCodeModel(Disp, M,
842 AM.hasSymbolicDisplacement()))
845 Reg = N.getNode()->getOperand(0);
847 Reg = N.getNode()->getOperand(0);
850 AM.IndexReg = AM.Base.Reg = Reg;
857 // Given A-B, if A can be completely folded into the address and
858 // the index field with the index field unused, use -B as the index.
859 // This is a win if a has multiple parts that can be folded into
860 // the address. Also, this saves a mov if the base register has
861 // other uses, since it avoids a two-address sub instruction, however
862 // it costs an additional mov if the index register has other uses.
864 // Test if the LHS of the sub can be folded.
865 X86ISelAddressMode Backup = AM;
866 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM,
867 DeadNodes, Depth+1) ||
868 // If it is successful but the recursive update causes N to be deleted,
869 // then it's not safe to continue.
870 DeadNodes.IsDeleted(N.getNode())) {
874 // Test if the index field is free for use.
875 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
881 SDValue RHS = N.getNode()->getOperand(1);
882 // If the RHS involves a register with multiple uses, this
883 // transformation incurs an extra mov, due to the neg instruction
884 // clobbering its operand.
885 if (!RHS.getNode()->hasOneUse() ||
886 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
887 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
888 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
889 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
890 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
892 // If the base is a register with multiple uses, this
893 // transformation may save a mov.
894 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
895 AM.Base.Reg.getNode() &&
896 !AM.Base.Reg.getNode()->hasOneUse()) ||
897 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
899 // If the folded LHS was interesting, this transformation saves
900 // address arithmetic.
901 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
902 ((AM.Disp != 0) && (Backup.Disp == 0)) +
903 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
905 // If it doesn't look like it may be an overall win, don't do it.
911 // Ok, the transformation is legal and appears profitable. Go for it.
912 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
913 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
917 // Insert the new nodes into the topological ordering.
918 if (Zero.getNode()->getNodeId() == -1 ||
919 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
920 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
921 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
923 if (Neg.getNode()->getNodeId() == -1 ||
924 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
925 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
926 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
932 X86ISelAddressMode Backup = AM;
933 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM,
934 DeadNodes, Depth+1)) {
935 if (DeadNodes.IsDeleted(N.getNode()))
936 // If it is successful but the recursive update causes N to be deleted,
937 // then it's not safe to continue.
939 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM,
941 // If it is successful but the recursive update causes N to be deleted,
942 // then it's not safe to continue.
943 return DeadNodes.IsDeleted(N.getNode());
946 // Try again after commuting the operands.
948 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM,
949 DeadNodes, Depth+1)) {
950 if (DeadNodes.IsDeleted(N.getNode()))
951 // If it is successful but the recursive update causes N to be deleted,
952 // then it's not safe to continue.
954 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM,
956 // If it is successful but the recursive update causes N to be deleted,
957 // then it's not safe to continue.
958 return DeadNodes.IsDeleted(N.getNode());
962 // If we couldn't fold both operands into the address at the same time,
963 // see if we can just put each operand into a register and fold at least
965 if (AM.BaseType == X86ISelAddressMode::RegBase &&
966 !AM.Base.Reg.getNode() &&
967 !AM.IndexReg.getNode()) {
968 AM.Base.Reg = N.getNode()->getOperand(0);
969 AM.IndexReg = N.getNode()->getOperand(1);
977 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
978 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
979 X86ISelAddressMode Backup = AM;
980 uint64_t Offset = CN->getSExtValue();
982 // Check to see if the LHS & C is zero.
983 if (!CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue()))
986 // Start with the LHS as an addr mode.
987 if (!MatchAddressRecursively(N.getOperand(0), AM, DeadNodes, Depth+1) &&
988 // Address could not have picked a GV address for the displacement.
990 // On x86-64, the resultant disp must fit in 32-bits.
992 X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
993 AM.hasSymbolicDisplacement()))) {
1002 // Perform some heroic transforms on an and of a constant-count shift
1003 // with a constant to enable use of the scaled offset field.
1005 SDValue Shift = N.getOperand(0);
1006 if (Shift.getNumOperands() != 2) break;
1008 // Scale must not be used already.
1009 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1011 SDValue X = Shift.getOperand(0);
1012 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1013 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1014 if (!C1 || !C2) break;
1016 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1017 // allows us to convert the shift and and into an h-register extract and
1019 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1020 unsigned ScaleLog = 8 - C1->getZExtValue();
1021 if (ScaleLog > 0 && ScaleLog < 4 &&
1022 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1023 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1024 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1025 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1027 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1029 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1030 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1033 // Insert the new nodes into the topological ordering.
1034 if (Eight.getNode()->getNodeId() == -1 ||
1035 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1036 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1037 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1039 if (Mask.getNode()->getNodeId() == -1 ||
1040 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1041 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1042 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1044 if (Srl.getNode()->getNodeId() == -1 ||
1045 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1046 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1047 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1049 if (And.getNode()->getNodeId() == -1 ||
1050 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1051 CurDAG->RepositionNode(N.getNode(), And.getNode());
1052 And.getNode()->setNodeId(N.getNode()->getNodeId());
1054 if (ShlCount.getNode()->getNodeId() == -1 ||
1055 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1056 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1057 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1059 if (Shl.getNode()->getNodeId() == -1 ||
1060 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1061 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1062 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1064 CurDAG->ReplaceAllUsesWith(N, Shl, &DeadNodes);
1066 AM.Scale = (1 << ScaleLog);
1071 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1072 // allows us to fold the shift into this addressing mode.
1073 if (Shift.getOpcode() != ISD::SHL) break;
1075 // Not likely to be profitable if either the AND or SHIFT node has more
1076 // than one use (unless all uses are for address computation). Besides,
1077 // isel mechanism requires their node ids to be reused.
1078 if (!N.hasOneUse() || !Shift.hasOneUse())
1081 // Verify that the shift amount is something we can fold.
1082 unsigned ShiftCst = C1->getZExtValue();
1083 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1086 // Get the new AND mask, this folds to a constant.
1087 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1088 SDValue(C2, 0), SDValue(C1, 0));
1089 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1091 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1092 NewAND, SDValue(C1, 0));
1094 // Insert the new nodes into the topological ordering.
1095 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1096 CurDAG->RepositionNode(X.getNode(), C1);
1097 C1->setNodeId(X.getNode()->getNodeId());
1099 if (NewANDMask.getNode()->getNodeId() == -1 ||
1100 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1101 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1102 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1104 if (NewAND.getNode()->getNodeId() == -1 ||
1105 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1106 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1107 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1109 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1110 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1111 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1112 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1115 CurDAG->ReplaceAllUsesWith(N, NewSHIFT, &DeadNodes);
1117 AM.Scale = 1 << ShiftCst;
1118 AM.IndexReg = NewAND;
1123 return MatchAddressBase(N, AM);
1126 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1127 /// specified addressing mode without any further recursion.
1128 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1129 // Is the base register already occupied?
1130 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1131 // If so, check to see if the scale index register is set.
1132 if (AM.IndexReg.getNode() == 0) {
1138 // Otherwise, we cannot select it.
1142 // Default, generate it as a register.
1143 AM.BaseType = X86ISelAddressMode::RegBase;
1148 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1149 /// It returns the operands which make up the maximal addressing mode it can
1150 /// match by reference.
1151 bool X86DAGToDAGISel::SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
1152 SDValue &Scale, SDValue &Index,
1153 SDValue &Disp, SDValue &Segment) {
1154 X86ISelAddressMode AM;
1155 if (MatchAddress(N, AM))
1158 EVT VT = N.getValueType();
1159 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1160 if (!AM.Base.Reg.getNode())
1161 AM.Base.Reg = CurDAG->getRegister(0, VT);
1164 if (!AM.IndexReg.getNode())
1165 AM.IndexReg = CurDAG->getRegister(0, VT);
1167 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1171 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1172 /// match a load whose top elements are either undef or zeros. The load flavor
1173 /// is derived from the type of N, which is either v4f32 or v2f64.
1176 /// PatternChainNode: this is the matched node that has a chain input and
1178 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1179 SDValue N, SDValue &Base,
1180 SDValue &Scale, SDValue &Index,
1181 SDValue &Disp, SDValue &Segment,
1182 SDValue &PatternNodeWithChain) {
1183 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1184 PatternNodeWithChain = N.getOperand(0);
1185 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1186 PatternNodeWithChain.hasOneUse() &&
1187 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1188 IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1189 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1190 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp,Segment))
1196 // Also handle the case where we explicitly require zeros in the top
1197 // elements. This is a vector shuffle from the zero vector.
1198 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1199 // Check to see if the top elements are all zeros (or bitcast of zeros).
1200 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1201 N.getOperand(0).getNode()->hasOneUse() &&
1202 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1203 N.getOperand(0).getOperand(0).hasOneUse() &&
1204 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1205 IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1206 // Okay, this is a zero extending load. Fold it.
1207 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1208 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1210 PatternNodeWithChain = SDValue(LD, 0);
1217 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1218 /// mode it matches can be cost effectively emitted as an LEA instruction.
1219 bool X86DAGToDAGISel::SelectLEAAddr(SDNode *Op, SDValue N,
1220 SDValue &Base, SDValue &Scale,
1221 SDValue &Index, SDValue &Disp) {
1222 X86ISelAddressMode AM;
1224 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1226 SDValue Copy = AM.Segment;
1227 SDValue T = CurDAG->getRegister(0, MVT::i32);
1229 if (MatchAddress(N, AM))
1231 assert (T == AM.Segment);
1234 EVT VT = N.getValueType();
1235 unsigned Complexity = 0;
1236 if (AM.BaseType == X86ISelAddressMode::RegBase)
1237 if (AM.Base.Reg.getNode())
1240 AM.Base.Reg = CurDAG->getRegister(0, VT);
1241 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1244 if (AM.IndexReg.getNode())
1247 AM.IndexReg = CurDAG->getRegister(0, VT);
1249 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1254 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1255 // to a LEA. This is determined with some expermentation but is by no means
1256 // optimal (especially for code size consideration). LEA is nice because of
1257 // its three-address nature. Tweak the cost function again when we can run
1258 // convertToThreeAddress() at register allocation time.
1259 if (AM.hasSymbolicDisplacement()) {
1260 // For X86-64, we should always use lea to materialize RIP relative
1262 if (Subtarget->is64Bit())
1268 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1271 // If it isn't worth using an LEA, reject it.
1272 if (Complexity <= 2)
1276 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1280 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1281 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
1282 SDValue &Scale, SDValue &Index,
1284 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1285 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1287 X86ISelAddressMode AM;
1288 AM.GV = GA->getGlobal();
1289 AM.Disp += GA->getOffset();
1290 AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1291 AM.SymbolFlags = GA->getTargetFlags();
1293 if (N.getValueType() == MVT::i32) {
1295 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1297 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1301 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1306 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1307 SDValue &Base, SDValue &Scale,
1308 SDValue &Index, SDValue &Disp,
1310 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1311 !IsProfitableToFold(N, P, P) ||
1312 !IsLegalToFold(N, P, P))
1315 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1318 /// getGlobalBaseReg - Return an SDNode that returns the value of
1319 /// the global base register. Output instructions required to
1320 /// initialize the global base register, if necessary.
1322 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1323 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1324 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1327 static SDNode *FindCallStartFromCall(SDNode *Node) {
1328 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1329 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1330 "Node doesn't have a token chain argument!");
1331 return FindCallStartFromCall(Node->getOperand(0).getNode());
1334 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1335 SDValue Chain = Node->getOperand(0);
1336 SDValue In1 = Node->getOperand(1);
1337 SDValue In2L = Node->getOperand(2);
1338 SDValue In2H = Node->getOperand(3);
1339 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1340 if (!SelectAddr(In1.getNode(), In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1342 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1343 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1344 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1345 SDNode *ResNode = CurDAG->getMachineNode(Opc, Node->getDebugLoc(),
1346 MVT::i32, MVT::i32, MVT::Other, Ops,
1347 array_lengthof(Ops));
1348 cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1352 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1353 if (Node->hasAnyUseOfValue(0))
1356 // Optimize common patterns for __sync_add_and_fetch and
1357 // __sync_sub_and_fetch where the result is not used. This allows us
1358 // to use "lock" version of add, sub, inc, dec instructions.
1359 // FIXME: Do not use special instructions but instead add the "lock"
1360 // prefix to the target node somehow. The extra information will then be
1361 // transferred to machine instruction and it denotes the prefix.
1362 SDValue Chain = Node->getOperand(0);
1363 SDValue Ptr = Node->getOperand(1);
1364 SDValue Val = Node->getOperand(2);
1365 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1366 if (!SelectAddr(Ptr.getNode(), Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1369 bool isInc = false, isDec = false, isSub = false, isCN = false;
1370 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1373 int64_t CNVal = CN->getSExtValue();
1376 else if (CNVal == -1)
1378 else if (CNVal >= 0)
1379 Val = CurDAG->getTargetConstant(CNVal, NVT);
1382 Val = CurDAG->getTargetConstant(-CNVal, NVT);
1384 } else if (Val.hasOneUse() &&
1385 Val.getOpcode() == ISD::SUB &&
1386 X86::isZeroNode(Val.getOperand(0))) {
1388 Val = Val.getOperand(1);
1392 switch (NVT.getSimpleVT().SimpleTy) {
1396 Opc = X86::LOCK_INC8m;
1398 Opc = X86::LOCK_DEC8m;
1401 Opc = X86::LOCK_SUB8mi;
1403 Opc = X86::LOCK_SUB8mr;
1406 Opc = X86::LOCK_ADD8mi;
1408 Opc = X86::LOCK_ADD8mr;
1413 Opc = X86::LOCK_INC16m;
1415 Opc = X86::LOCK_DEC16m;
1418 if (Predicate_immSext8(Val.getNode()))
1419 Opc = X86::LOCK_SUB16mi8;
1421 Opc = X86::LOCK_SUB16mi;
1423 Opc = X86::LOCK_SUB16mr;
1426 if (Predicate_immSext8(Val.getNode()))
1427 Opc = X86::LOCK_ADD16mi8;
1429 Opc = X86::LOCK_ADD16mi;
1431 Opc = X86::LOCK_ADD16mr;
1436 Opc = X86::LOCK_INC32m;
1438 Opc = X86::LOCK_DEC32m;
1441 if (Predicate_immSext8(Val.getNode()))
1442 Opc = X86::LOCK_SUB32mi8;
1444 Opc = X86::LOCK_SUB32mi;
1446 Opc = X86::LOCK_SUB32mr;
1449 if (Predicate_immSext8(Val.getNode()))
1450 Opc = X86::LOCK_ADD32mi8;
1452 Opc = X86::LOCK_ADD32mi;
1454 Opc = X86::LOCK_ADD32mr;
1459 Opc = X86::LOCK_INC64m;
1461 Opc = X86::LOCK_DEC64m;
1463 Opc = X86::LOCK_SUB64mr;
1465 if (Predicate_immSext8(Val.getNode()))
1466 Opc = X86::LOCK_SUB64mi8;
1467 else if (Predicate_i64immSExt32(Val.getNode()))
1468 Opc = X86::LOCK_SUB64mi32;
1471 Opc = X86::LOCK_ADD64mr;
1473 if (Predicate_immSext8(Val.getNode()))
1474 Opc = X86::LOCK_ADD64mi8;
1475 else if (Predicate_i64immSExt32(Val.getNode()))
1476 Opc = X86::LOCK_ADD64mi32;
1482 DebugLoc dl = Node->getDebugLoc();
1483 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1485 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1486 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1487 if (isInc || isDec) {
1488 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1489 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 6), 0);
1490 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1491 SDValue RetVals[] = { Undef, Ret };
1492 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1494 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1495 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 7), 0);
1496 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1497 SDValue RetVals[] = { Undef, Ret };
1498 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1502 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1503 /// any uses which require the SF or OF bits to be accurate.
1504 static bool HasNoSignedComparisonUses(SDNode *N) {
1505 // Examine each user of the node.
1506 for (SDNode::use_iterator UI = N->use_begin(),
1507 UE = N->use_end(); UI != UE; ++UI) {
1508 // Only examine CopyToReg uses.
1509 if (UI->getOpcode() != ISD::CopyToReg)
1511 // Only examine CopyToReg uses that copy to EFLAGS.
1512 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1515 // Examine each user of the CopyToReg use.
1516 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1517 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1518 // Only examine the Flag result.
1519 if (FlagUI.getUse().getResNo() != 1) continue;
1520 // Anything unusual: assume conservatively.
1521 if (!FlagUI->isMachineOpcode()) return false;
1522 // Examine the opcode of the user.
1523 switch (FlagUI->getMachineOpcode()) {
1524 // These comparisons don't treat the most significant bit specially.
1525 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1526 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1527 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1528 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1529 case X86::JA_4: case X86::JAE_4: case X86::JB_4: case X86::JBE_4:
1530 case X86::JE_4: case X86::JNE_4: case X86::JP_4: case X86::JNP_4:
1531 case X86::CMOVA16rr: case X86::CMOVA16rm:
1532 case X86::CMOVA32rr: case X86::CMOVA32rm:
1533 case X86::CMOVA64rr: case X86::CMOVA64rm:
1534 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1535 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1536 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1537 case X86::CMOVB16rr: case X86::CMOVB16rm:
1538 case X86::CMOVB32rr: case X86::CMOVB32rm:
1539 case X86::CMOVB64rr: case X86::CMOVB64rm:
1540 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1541 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1542 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1543 case X86::CMOVE16rr: case X86::CMOVE16rm:
1544 case X86::CMOVE32rr: case X86::CMOVE32rm:
1545 case X86::CMOVE64rr: case X86::CMOVE64rm:
1546 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1547 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1548 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1549 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1550 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1551 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1552 case X86::CMOVP16rr: case X86::CMOVP16rm:
1553 case X86::CMOVP32rr: case X86::CMOVP32rm:
1554 case X86::CMOVP64rr: case X86::CMOVP64rm:
1556 // Anything else: assume conservatively.
1557 default: return false;
1564 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1565 EVT NVT = Node->getValueType(0);
1567 unsigned Opcode = Node->getOpcode();
1568 DebugLoc dl = Node->getDebugLoc();
1570 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1572 if (Node->isMachineOpcode()) {
1573 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
1574 return NULL; // Already selected.
1579 case X86ISD::GlobalBaseReg:
1580 return getGlobalBaseReg();
1582 case X86ISD::ATOMOR64_DAG:
1583 return SelectAtomic64(Node, X86::ATOMOR6432);
1584 case X86ISD::ATOMXOR64_DAG:
1585 return SelectAtomic64(Node, X86::ATOMXOR6432);
1586 case X86ISD::ATOMADD64_DAG:
1587 return SelectAtomic64(Node, X86::ATOMADD6432);
1588 case X86ISD::ATOMSUB64_DAG:
1589 return SelectAtomic64(Node, X86::ATOMSUB6432);
1590 case X86ISD::ATOMNAND64_DAG:
1591 return SelectAtomic64(Node, X86::ATOMNAND6432);
1592 case X86ISD::ATOMAND64_DAG:
1593 return SelectAtomic64(Node, X86::ATOMAND6432);
1594 case X86ISD::ATOMSWAP64_DAG:
1595 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1597 case ISD::ATOMIC_LOAD_ADD: {
1598 SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1604 case ISD::SMUL_LOHI:
1605 case ISD::UMUL_LOHI: {
1606 SDValue N0 = Node->getOperand(0);
1607 SDValue N1 = Node->getOperand(1);
1609 bool isSigned = Opcode == ISD::SMUL_LOHI;
1611 switch (NVT.getSimpleVT().SimpleTy) {
1612 default: llvm_unreachable("Unsupported VT!");
1613 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1614 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1615 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1616 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1619 switch (NVT.getSimpleVT().SimpleTy) {
1620 default: llvm_unreachable("Unsupported VT!");
1621 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1622 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1623 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1624 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1628 unsigned LoReg, HiReg;
1629 switch (NVT.getSimpleVT().SimpleTy) {
1630 default: llvm_unreachable("Unsupported VT!");
1631 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1632 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1633 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1634 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1637 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1638 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1639 // Multiply is commmutative.
1641 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1646 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1647 N0, SDValue()).getValue(1);
1650 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1653 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1654 array_lengthof(Ops));
1655 InFlag = SDValue(CNode, 1);
1656 // Update the chain.
1657 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1660 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1663 // Copy the low half of the result, if it is needed.
1664 if (!SDValue(Node, 0).use_empty()) {
1665 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1666 LoReg, NVT, InFlag);
1667 InFlag = Result.getValue(2);
1668 ReplaceUses(SDValue(Node, 0), Result);
1669 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1671 // Copy the high half of the result, if it is needed.
1672 if (!SDValue(Node, 1).use_empty()) {
1674 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1675 // Prevent use of AH in a REX instruction by referencing AX instead.
1676 // Shift it down 8 bits.
1677 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1678 X86::AX, MVT::i16, InFlag);
1679 InFlag = Result.getValue(2);
1680 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1682 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1683 // Then truncate it down to i8.
1684 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1687 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1688 HiReg, NVT, InFlag);
1689 InFlag = Result.getValue(2);
1691 ReplaceUses(SDValue(Node, 1), Result);
1692 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1699 case ISD::UDIVREM: {
1700 SDValue N0 = Node->getOperand(0);
1701 SDValue N1 = Node->getOperand(1);
1703 bool isSigned = Opcode == ISD::SDIVREM;
1705 switch (NVT.getSimpleVT().SimpleTy) {
1706 default: llvm_unreachable("Unsupported VT!");
1707 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1708 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1709 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1710 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1713 switch (NVT.getSimpleVT().SimpleTy) {
1714 default: llvm_unreachable("Unsupported VT!");
1715 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1716 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1717 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1718 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1722 unsigned LoReg, HiReg, ClrReg;
1723 unsigned ClrOpcode, SExtOpcode;
1724 switch (NVT.getSimpleVT().SimpleTy) {
1725 default: llvm_unreachable("Unsupported VT!");
1727 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
1729 SExtOpcode = X86::CBW;
1732 LoReg = X86::AX; HiReg = X86::DX;
1733 ClrOpcode = X86::MOV16r0; ClrReg = X86::DX;
1734 SExtOpcode = X86::CWD;
1737 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
1738 ClrOpcode = X86::MOV32r0;
1739 SExtOpcode = X86::CDQ;
1742 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
1743 ClrOpcode = X86::MOV64r0;
1744 SExtOpcode = X86::CQO;
1748 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1749 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1750 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1753 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1754 // Special case for div8, just use a move with zero extension to AX to
1755 // clear the upper 8 bits (AH).
1756 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1757 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1758 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1760 SDValue(CurDAG->getMachineNode(X86::MOVZX16rm8, dl, MVT::i16,
1762 array_lengthof(Ops)), 0);
1763 Chain = Move.getValue(1);
1764 ReplaceUses(N0.getValue(1), Chain);
1767 SDValue(CurDAG->getMachineNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1768 Chain = CurDAG->getEntryNode();
1770 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1771 InFlag = Chain.getValue(1);
1774 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1775 LoReg, N0, SDValue()).getValue(1);
1776 if (isSigned && !signBitIsZero) {
1777 // Sign extend the low part into the high part.
1779 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1781 // Zero out the high part, effectively zero extending the input.
1783 SDValue(CurDAG->getMachineNode(ClrOpcode, dl, NVT), 0);
1784 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
1785 ClrNode, InFlag).getValue(1);
1790 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1793 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1794 array_lengthof(Ops));
1795 InFlag = SDValue(CNode, 1);
1796 // Update the chain.
1797 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1800 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1803 // Copy the division (low) result, if it is needed.
1804 if (!SDValue(Node, 0).use_empty()) {
1805 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1806 LoReg, NVT, InFlag);
1807 InFlag = Result.getValue(2);
1808 ReplaceUses(SDValue(Node, 0), Result);
1809 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1811 // Copy the remainder (high) result, if it is needed.
1812 if (!SDValue(Node, 1).use_empty()) {
1814 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1815 // Prevent use of AH in a REX instruction by referencing AX instead.
1816 // Shift it down 8 bits.
1817 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1818 X86::AX, MVT::i16, InFlag);
1819 InFlag = Result.getValue(2);
1820 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1822 CurDAG->getTargetConstant(8, MVT::i8)),
1824 // Then truncate it down to i8.
1825 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1828 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1829 HiReg, NVT, InFlag);
1830 InFlag = Result.getValue(2);
1832 ReplaceUses(SDValue(Node, 1), Result);
1833 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1839 SDValue N0 = Node->getOperand(0);
1840 SDValue N1 = Node->getOperand(1);
1842 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
1843 // use a smaller encoding.
1844 if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1845 N0.getValueType() != MVT::i8 &&
1846 X86::isZeroNode(N1)) {
1847 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
1850 // For example, convert "testl %eax, $8" to "testb %al, $8"
1851 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
1852 (!(C->getZExtValue() & 0x80) ||
1853 HasNoSignedComparisonUses(Node))) {
1854 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
1855 SDValue Reg = N0.getNode()->getOperand(0);
1857 // On x86-32, only the ABCD registers have 8-bit subregisters.
1858 if (!Subtarget->is64Bit()) {
1859 TargetRegisterClass *TRC = 0;
1860 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1861 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1862 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1863 default: llvm_unreachable("Unsupported TEST operand type!");
1865 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1866 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1867 Reg.getValueType(), Reg, RC), 0);
1870 // Extract the l-register.
1871 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1875 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
1878 // For example, "testl %eax, $2048" to "testb %ah, $8".
1879 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
1880 (!(C->getZExtValue() & 0x8000) ||
1881 HasNoSignedComparisonUses(Node))) {
1882 // Shift the immediate right by 8 bits.
1883 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
1885 SDValue Reg = N0.getNode()->getOperand(0);
1887 // Put the value in an ABCD register.
1888 TargetRegisterClass *TRC = 0;
1889 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1890 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
1891 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1892 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1893 default: llvm_unreachable("Unsupported TEST operand type!");
1895 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1896 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1897 Reg.getValueType(), Reg, RC), 0);
1899 // Extract the h-register.
1900 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
1903 // Emit a testb. No special NOREX tricks are needed since there's
1904 // only one GPR operand!
1905 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
1906 Subreg, ShiftedImm);
1909 // For example, "testl %eax, $32776" to "testw %ax, $32776".
1910 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
1911 N0.getValueType() != MVT::i16 &&
1912 (!(C->getZExtValue() & 0x8000) ||
1913 HasNoSignedComparisonUses(Node))) {
1914 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
1915 SDValue Reg = N0.getNode()->getOperand(0);
1917 // Extract the 16-bit subregister.
1918 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
1922 return CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
1925 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
1926 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
1927 N0.getValueType() == MVT::i64 &&
1928 (!(C->getZExtValue() & 0x80000000) ||
1929 HasNoSignedComparisonUses(Node))) {
1930 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
1931 SDValue Reg = N0.getNode()->getOperand(0);
1933 // Extract the 32-bit subregister.
1934 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
1938 return CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
1945 SDNode *ResNode = SelectCode(Node);
1947 DEBUG(dbgs() << "=> ";
1948 if (ResNode == NULL || ResNode == Node)
1951 ResNode->dump(CurDAG);
1957 bool X86DAGToDAGISel::
1958 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1959 std::vector<SDValue> &OutOps) {
1960 SDValue Op0, Op1, Op2, Op3, Op4;
1961 switch (ConstraintCode) {
1962 case 'o': // offsetable ??
1963 case 'v': // not offsetable ??
1964 default: return true;
1966 if (!SelectAddr(Op.getNode(), Op, Op0, Op1, Op2, Op3, Op4))
1971 OutOps.push_back(Op0);
1972 OutOps.push_back(Op1);
1973 OutOps.push_back(Op2);
1974 OutOps.push_back(Op3);
1975 OutOps.push_back(Op4);
1979 /// createX86ISelDag - This pass converts a legalized DAG into a
1980 /// X86-specific DAG, ready for instruction scheduling.
1982 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1983 llvm::CodeGenOpt::Level OptLevel) {
1984 return new X86DAGToDAGISel(TM, OptLevel);