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 "X86MachineFunctionInfo.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Type.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
44 //===----------------------------------------------------------------------===//
45 // Pattern Matcher Implementation
46 //===----------------------------------------------------------------------===//
49 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
50 /// SDValue's instead of register numbers for the leaves of the matched
52 struct X86ISelAddressMode {
58 // This is really a union, discriminated by BaseType!
66 const GlobalValue *GV;
68 const BlockAddress *BlockAddr;
71 unsigned Align; // CP alignment.
72 unsigned char SymbolFlags; // X86II::MO_*
75 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
76 Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
77 SymbolFlags(X86II::MO_NO_FLAG) {
80 bool hasSymbolicDisplacement() const {
81 return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
84 bool hasBaseOrIndexReg() const {
85 return IndexReg.getNode() != 0 || Base_Reg.getNode() != 0;
88 /// isRIPRelative - Return true if this addressing mode is already RIP
90 bool isRIPRelative() const {
91 if (BaseType != RegBase) return false;
92 if (RegisterSDNode *RegNode =
93 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
94 return RegNode->getReg() == X86::RIP;
98 void setBaseReg(SDValue Reg) {
104 dbgs() << "X86ISelAddressMode " << this << '\n';
105 dbgs() << "Base_Reg ";
106 if (Base_Reg.getNode() != 0)
107 Base_Reg.getNode()->dump();
110 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
111 << " Scale" << Scale << '\n'
113 if (IndexReg.getNode() != 0)
114 IndexReg.getNode()->dump();
117 dbgs() << " Disp " << Disp << '\n'
134 dbgs() << " JT" << JT << " Align" << Align << '\n';
140 class X86ISelListener : public SelectionDAG::DAGUpdateListener {
141 SmallSet<SDNode*, 4> Deletes;
143 explicit X86ISelListener() {}
144 virtual void NodeDeleted(SDNode *N, SDNode *E) {
147 virtual void NodeUpdated(SDNode *N) {
150 bool IsDeleted(SDNode *N) {
151 return Deletes.count(N);
155 //===--------------------------------------------------------------------===//
156 /// ISel - X86 specific code to select X86 machine instructions for
157 /// SelectionDAG operations.
159 class X86DAGToDAGISel : public SelectionDAGISel {
160 /// X86Lowering - This object fully describes how to lower LLVM code to an
161 /// X86-specific SelectionDAG.
162 const X86TargetLowering &X86Lowering;
164 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
165 /// make the right decision when generating code for different targets.
166 const X86Subtarget *Subtarget;
168 /// OptForSize - If true, selector should try to optimize for code size
169 /// instead of performance.
173 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
174 : SelectionDAGISel(tm, OptLevel),
175 X86Lowering(*tm.getTargetLowering()),
176 Subtarget(&tm.getSubtarget<X86Subtarget>()),
179 virtual const char *getPassName() const {
180 return "X86 DAG->DAG Instruction Selection";
183 virtual void EmitFunctionEntryCode();
185 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
187 virtual void PreprocessISelDAG();
189 // Include the pieces autogenerated from the target description.
190 #include "X86GenDAGISel.inc"
193 SDNode *Select(SDNode *N);
194 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
195 SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
197 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
198 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
199 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
200 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
201 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
202 X86ISelListener &DeadNodes,
204 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
205 bool SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
206 SDValue &Scale, SDValue &Index, SDValue &Disp,
208 bool SelectLEAAddr(SDNode *Op, SDValue N, SDValue &Base,
209 SDValue &Scale, SDValue &Index, SDValue &Disp);
210 bool SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
211 SDValue &Scale, SDValue &Index, SDValue &Disp);
212 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
213 SDValue &Base, SDValue &Scale,
214 SDValue &Index, SDValue &Disp,
216 SDValue &NodeWithChain);
218 bool TryFoldLoad(SDNode *P, SDValue N,
219 SDValue &Base, SDValue &Scale,
220 SDValue &Index, SDValue &Disp,
223 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
224 /// inline asm expressions.
225 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
227 std::vector<SDValue> &OutOps);
229 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
231 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
232 SDValue &Scale, SDValue &Index,
233 SDValue &Disp, SDValue &Segment) {
234 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
235 CurDAG->getTargetFrameIndex(AM.Base_FrameIndex, TLI.getPointerTy()) :
237 Scale = getI8Imm(AM.Scale);
239 // These are 32-bit even in 64-bit mode since RIP relative offset
242 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
245 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
246 AM.Align, AM.Disp, AM.SymbolFlags);
248 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
249 else if (AM.JT != -1)
250 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
251 else if (AM.BlockAddr)
252 Disp = CurDAG->getBlockAddress(AM.BlockAddr, MVT::i32,
253 true, AM.SymbolFlags);
255 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
257 if (AM.Segment.getNode())
258 Segment = AM.Segment;
260 Segment = CurDAG->getRegister(0, MVT::i32);
263 /// getI8Imm - Return a target constant with the specified value, of type
265 inline SDValue getI8Imm(unsigned Imm) {
266 return CurDAG->getTargetConstant(Imm, MVT::i8);
269 /// getI16Imm - Return a target constant with the specified value, of type
271 inline SDValue getI16Imm(unsigned Imm) {
272 return CurDAG->getTargetConstant(Imm, MVT::i16);
275 /// getI32Imm - Return a target constant with the specified value, of type
277 inline SDValue getI32Imm(unsigned Imm) {
278 return CurDAG->getTargetConstant(Imm, MVT::i32);
281 /// getGlobalBaseReg - Return an SDNode that returns the value of
282 /// the global base register. Output instructions required to
283 /// initialize the global base register, if necessary.
285 SDNode *getGlobalBaseReg();
287 /// getTargetMachine - Return a reference to the TargetMachine, casted
288 /// to the target-specific type.
289 const X86TargetMachine &getTargetMachine() {
290 return static_cast<const X86TargetMachine &>(TM);
293 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
294 /// to the target-specific type.
295 const X86InstrInfo *getInstrInfo() {
296 return getTargetMachine().getInstrInfo();
303 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
304 if (OptLevel == CodeGenOpt::None) return false;
309 if (N.getOpcode() != ISD::LOAD)
312 // If N is a load, do additional profitability checks.
314 switch (U->getOpcode()) {
327 SDValue Op1 = U->getOperand(1);
329 // If the other operand is a 8-bit immediate we should fold the immediate
330 // instead. This reduces code size.
332 // movl 4(%esp), %eax
336 // addl 4(%esp), %eax
337 // The former is 2 bytes shorter. In case where the increment is 1, then
338 // the saving can be 4 bytes (by using incl %eax).
339 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
340 if (Imm->getAPIntValue().isSignedIntN(8))
343 // If the other operand is a TLS address, we should fold it instead.
346 // leal i@NTPOFF(%eax), %eax
348 // movl $i@NTPOFF, %eax
350 // if the block also has an access to a second TLS address this will save
352 // FIXME: This is probably also true for non TLS addresses.
353 if (Op1.getOpcode() == X86ISD::Wrapper) {
354 SDValue Val = Op1.getOperand(0);
355 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
365 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
366 /// load's chain operand and move load below the call's chain operand.
367 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
368 SDValue Call, SDValue OrigChain) {
369 SmallVector<SDValue, 8> Ops;
370 SDValue Chain = OrigChain.getOperand(0);
371 if (Chain.getNode() == Load.getNode())
372 Ops.push_back(Load.getOperand(0));
374 assert(Chain.getOpcode() == ISD::TokenFactor &&
375 "Unexpected chain operand");
376 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
377 if (Chain.getOperand(i).getNode() == Load.getNode())
378 Ops.push_back(Load.getOperand(0));
380 Ops.push_back(Chain.getOperand(i));
382 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
383 MVT::Other, &Ops[0], Ops.size());
385 Ops.push_back(NewChain);
387 for (unsigned i = 1, e = OrigChain.getNumOperands(); i != e; ++i)
388 Ops.push_back(OrigChain.getOperand(i));
389 CurDAG->UpdateNodeOperands(OrigChain, &Ops[0], Ops.size());
390 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
391 Load.getOperand(1), Load.getOperand(2));
393 Ops.push_back(SDValue(Load.getNode(), 1));
394 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
395 Ops.push_back(Call.getOperand(i));
396 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
399 /// isCalleeLoad - Return true if call address is a load and it can be
400 /// moved below CALLSEQ_START and the chains leading up to the call.
401 /// Return the CALLSEQ_START by reference as a second output.
402 /// In the case of a tail call, there isn't a callseq node between the call
403 /// chain and the load.
404 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
405 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
407 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
410 LD->getAddressingMode() != ISD::UNINDEXED ||
411 LD->getExtensionType() != ISD::NON_EXTLOAD)
414 // Now let's find the callseq_start.
415 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
416 if (!Chain.hasOneUse())
418 Chain = Chain.getOperand(0);
421 if (!Chain.getNumOperands())
423 if (Chain.getOperand(0).getNode() == Callee.getNode())
425 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
426 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
427 Callee.getValue(1).hasOneUse())
432 void X86DAGToDAGISel::PreprocessISelDAG() {
433 // OptForSize is used in pattern predicates that isel is matching.
434 OptForSize = MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize);
436 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
437 E = CurDAG->allnodes_end(); I != E; ) {
438 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
440 if (OptLevel != CodeGenOpt::None &&
441 (N->getOpcode() == X86ISD::CALL ||
442 N->getOpcode() == X86ISD::TC_RETURN)) {
443 /// Also try moving call address load from outside callseq_start to just
444 /// before the call to allow it to be folded.
462 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
463 SDValue Chain = N->getOperand(0);
464 SDValue Load = N->getOperand(1);
465 if (!isCalleeLoad(Load, Chain, HasCallSeq))
467 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
472 // Lower fpround and fpextend nodes that target the FP stack to be store and
473 // load to the stack. This is a gross hack. We would like to simply mark
474 // these as being illegal, but when we do that, legalize produces these when
475 // it expands calls, then expands these in the same legalize pass. We would
476 // like dag combine to be able to hack on these between the call expansion
477 // and the node legalization. As such this pass basically does "really
478 // late" legalization of these inline with the X86 isel pass.
479 // FIXME: This should only happen when not compiled with -O0.
480 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
483 // If the source and destination are SSE registers, then this is a legal
484 // conversion that should not be lowered.
485 EVT SrcVT = N->getOperand(0).getValueType();
486 EVT DstVT = N->getValueType(0);
487 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
488 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
489 if (SrcIsSSE && DstIsSSE)
492 if (!SrcIsSSE && !DstIsSSE) {
493 // If this is an FPStack extension, it is a noop.
494 if (N->getOpcode() == ISD::FP_EXTEND)
496 // If this is a value-preserving FPStack truncation, it is a noop.
497 if (N->getConstantOperandVal(1))
501 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
502 // FPStack has extload and truncstore. SSE can fold direct loads into other
503 // operations. Based on this, decide what we want to do.
505 if (N->getOpcode() == ISD::FP_ROUND)
506 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
508 MemVT = SrcIsSSE ? SrcVT : DstVT;
510 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
511 DebugLoc dl = N->getDebugLoc();
513 // FIXME: optimize the case where the src/dest is a load or store?
514 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
516 MemTmp, NULL, 0, MemVT,
518 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
519 NULL, 0, MemVT, false, false, 0);
521 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
522 // extload we created. This will cause general havok on the dag because
523 // anything below the conversion could be folded into other existing nodes.
524 // To avoid invalidating 'I', back it up to the convert node.
526 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
528 // Now that we did that, the node is dead. Increment the iterator to the
529 // next node to process, then delete N.
531 CurDAG->DeleteNode(N);
536 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
537 /// the main function.
538 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
539 MachineFrameInfo *MFI) {
540 const TargetInstrInfo *TII = TM.getInstrInfo();
541 if (Subtarget->isTargetCygMing())
542 BuildMI(BB, DebugLoc(),
543 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
546 void X86DAGToDAGISel::EmitFunctionEntryCode() {
547 // If this is main, emit special code for main.
548 if (const Function *Fn = MF->getFunction())
549 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
550 EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
554 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
555 X86ISelAddressMode &AM) {
556 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
557 SDValue Segment = N.getOperand(0);
559 if (AM.Segment.getNode() == 0) {
560 AM.Segment = Segment;
567 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
568 // This optimization is valid because the GNU TLS model defines that
569 // gs:0 (or fs:0 on X86-64) contains its own address.
570 // For more information see http://people.redhat.com/drepper/tls.pdf
572 SDValue Address = N.getOperand(1);
573 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
574 !MatchSegmentBaseAddress (Address, AM))
580 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
581 /// into an addressing mode. These wrap things that will resolve down into a
582 /// symbol reference. If no match is possible, this returns true, otherwise it
584 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
585 // If the addressing mode already has a symbol as the displacement, we can
586 // never match another symbol.
587 if (AM.hasSymbolicDisplacement())
590 SDValue N0 = N.getOperand(0);
591 CodeModel::Model M = TM.getCodeModel();
593 // Handle X86-64 rip-relative addresses. We check this before checking direct
594 // folding because RIP is preferable to non-RIP accesses.
595 if (Subtarget->is64Bit() &&
596 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
597 // they cannot be folded into immediate fields.
598 // FIXME: This can be improved for kernel and other models?
599 (M == CodeModel::Small || M == CodeModel::Kernel) &&
600 // Base and index reg must be 0 in order to use %rip as base and lowering
602 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
603 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
604 int64_t Offset = AM.Disp + G->getOffset();
605 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
606 AM.GV = G->getGlobal();
608 AM.SymbolFlags = G->getTargetFlags();
609 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
610 int64_t Offset = AM.Disp + CP->getOffset();
611 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
612 AM.CP = CP->getConstVal();
613 AM.Align = CP->getAlignment();
615 AM.SymbolFlags = CP->getTargetFlags();
616 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
617 AM.ES = S->getSymbol();
618 AM.SymbolFlags = S->getTargetFlags();
619 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
620 AM.JT = J->getIndex();
621 AM.SymbolFlags = J->getTargetFlags();
623 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
624 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
627 if (N.getOpcode() == X86ISD::WrapperRIP)
628 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
632 // Handle the case when globals fit in our immediate field: This is true for
633 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
634 // mode, this results in a non-RIP-relative computation.
635 if (!Subtarget->is64Bit() ||
636 ((M == CodeModel::Small || M == CodeModel::Kernel) &&
637 TM.getRelocationModel() == Reloc::Static)) {
638 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
639 AM.GV = G->getGlobal();
640 AM.Disp += G->getOffset();
641 AM.SymbolFlags = G->getTargetFlags();
642 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
643 AM.CP = CP->getConstVal();
644 AM.Align = CP->getAlignment();
645 AM.Disp += CP->getOffset();
646 AM.SymbolFlags = CP->getTargetFlags();
647 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
648 AM.ES = S->getSymbol();
649 AM.SymbolFlags = S->getTargetFlags();
650 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
651 AM.JT = J->getIndex();
652 AM.SymbolFlags = J->getTargetFlags();
654 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
655 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
663 /// MatchAddress - Add the specified node to the specified addressing mode,
664 /// returning true if it cannot be done. This just pattern matches for the
666 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
667 X86ISelListener DeadNodes;
668 if (MatchAddressRecursively(N, AM, DeadNodes, 0))
671 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
672 // a smaller encoding and avoids a scaled-index.
674 AM.BaseType == X86ISelAddressMode::RegBase &&
675 AM.Base_Reg.getNode() == 0) {
676 AM.Base_Reg = AM.IndexReg;
680 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
681 // because it has a smaller encoding.
682 // TODO: Which other code models can use this?
683 if (TM.getCodeModel() == CodeModel::Small &&
684 Subtarget->is64Bit() &&
686 AM.BaseType == X86ISelAddressMode::RegBase &&
687 AM.Base_Reg.getNode() == 0 &&
688 AM.IndexReg.getNode() == 0 &&
689 AM.SymbolFlags == X86II::MO_NO_FLAG &&
690 AM.hasSymbolicDisplacement())
691 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
696 /// isLogicallyAddWithConstant - Return true if this node is semantically an
697 /// add of a value with a constantint.
698 static bool isLogicallyAddWithConstant(SDValue V, SelectionDAG *CurDAG) {
699 // Check for (add x, Cst)
700 if (V->getOpcode() == ISD::ADD)
701 return isa<ConstantSDNode>(V->getOperand(1));
703 // Check for (or x, Cst), where Cst & x == 0.
704 if (V->getOpcode() != ISD::OR ||
705 !isa<ConstantSDNode>(V->getOperand(1)))
708 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
709 ConstantSDNode *CN = cast<ConstantSDNode>(V->getOperand(1));
711 // Check to see if the LHS & C is zero.
712 return CurDAG->MaskedValueIsZero(V->getOperand(0), CN->getAPIntValue());
715 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
716 X86ISelListener &DeadNodes,
718 bool is64Bit = Subtarget->is64Bit();
719 DebugLoc dl = N.getDebugLoc();
721 dbgs() << "MatchAddress: ";
726 return MatchAddressBase(N, AM);
728 CodeModel::Model M = TM.getCodeModel();
730 // If this is already a %rip relative address, we can only merge immediates
731 // into it. Instead of handling this in every case, we handle it here.
732 // RIP relative addressing: %rip + 32-bit displacement!
733 if (AM.isRIPRelative()) {
734 // FIXME: JumpTable and ExternalSymbol address currently don't like
735 // displacements. It isn't very important, but this should be fixed for
737 if (!AM.ES && AM.JT != -1) return true;
739 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
740 int64_t Val = AM.Disp + Cst->getSExtValue();
741 if (X86::isOffsetSuitableForCodeModel(Val, M,
742 AM.hasSymbolicDisplacement())) {
750 switch (N.getOpcode()) {
752 case ISD::Constant: {
753 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
755 X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
756 AM.hasSymbolicDisplacement())) {
763 case X86ISD::SegmentBaseAddress:
764 if (!MatchSegmentBaseAddress(N, AM))
768 case X86ISD::Wrapper:
769 case X86ISD::WrapperRIP:
770 if (!MatchWrapper(N, AM))
775 if (!MatchLoad(N, AM))
779 case ISD::FrameIndex:
780 if (AM.BaseType == X86ISelAddressMode::RegBase
781 && AM.Base_Reg.getNode() == 0) {
782 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
783 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
789 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
793 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
794 unsigned Val = CN->getZExtValue();
795 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
796 // that the base operand remains free for further matching. If
797 // the base doesn't end up getting used, a post-processing step
798 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
799 if (Val == 1 || Val == 2 || Val == 3) {
801 SDValue ShVal = N.getNode()->getOperand(0);
803 // Okay, we know that we have a scale by now. However, if the scaled
804 // value is an add of something and a constant, we can fold the
805 // constant into the disp field here.
806 if (isLogicallyAddWithConstant(ShVal, CurDAG)) {
807 AM.IndexReg = ShVal.getNode()->getOperand(0);
808 ConstantSDNode *AddVal =
809 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
810 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
812 X86::isOffsetSuitableForCodeModel(Disp, M,
813 AM.hasSymbolicDisplacement()))
827 // A mul_lohi where we need the low part can be folded as a plain multiply.
828 if (N.getResNo() != 0) break;
831 case X86ISD::MUL_IMM:
832 // X*[3,5,9] -> X+X*[2,4,8]
833 if (AM.BaseType == X86ISelAddressMode::RegBase &&
834 AM.Base_Reg.getNode() == 0 &&
835 AM.IndexReg.getNode() == 0) {
837 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
838 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
839 CN->getZExtValue() == 9) {
840 AM.Scale = unsigned(CN->getZExtValue())-1;
842 SDValue MulVal = N.getNode()->getOperand(0);
845 // Okay, we know that we have a scale by now. However, if the scaled
846 // value is an add of something and a constant, we can fold the
847 // constant into the disp field here.
848 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
849 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
850 Reg = MulVal.getNode()->getOperand(0);
851 ConstantSDNode *AddVal =
852 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
853 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
856 X86::isOffsetSuitableForCodeModel(Disp, M,
857 AM.hasSymbolicDisplacement()))
860 Reg = N.getNode()->getOperand(0);
862 Reg = N.getNode()->getOperand(0);
865 AM.IndexReg = AM.Base_Reg = Reg;
872 // Given A-B, if A can be completely folded into the address and
873 // the index field with the index field unused, use -B as the index.
874 // This is a win if a has multiple parts that can be folded into
875 // the address. Also, this saves a mov if the base register has
876 // other uses, since it avoids a two-address sub instruction, however
877 // it costs an additional mov if the index register has other uses.
879 // Test if the LHS of the sub can be folded.
880 X86ISelAddressMode Backup = AM;
881 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM,
882 DeadNodes, Depth+1) ||
883 // If it is successful but the recursive update causes N to be deleted,
884 // then it's not safe to continue.
885 DeadNodes.IsDeleted(N.getNode())) {
889 // Test if the index field is free for use.
890 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
896 SDValue RHS = N.getNode()->getOperand(1);
897 // If the RHS involves a register with multiple uses, this
898 // transformation incurs an extra mov, due to the neg instruction
899 // clobbering its operand.
900 if (!RHS.getNode()->hasOneUse() ||
901 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
902 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
903 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
904 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
905 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
907 // If the base is a register with multiple uses, this
908 // transformation may save a mov.
909 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
910 AM.Base_Reg.getNode() &&
911 !AM.Base_Reg.getNode()->hasOneUse()) ||
912 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
914 // If the folded LHS was interesting, this transformation saves
915 // address arithmetic.
916 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
917 ((AM.Disp != 0) && (Backup.Disp == 0)) +
918 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
920 // If it doesn't look like it may be an overall win, don't do it.
926 // Ok, the transformation is legal and appears profitable. Go for it.
927 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
928 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
932 // Insert the new nodes into the topological ordering.
933 if (Zero.getNode()->getNodeId() == -1 ||
934 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
935 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
936 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
938 if (Neg.getNode()->getNodeId() == -1 ||
939 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
940 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
941 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
947 X86ISelAddressMode Backup = AM;
948 if (!MatchAddressRecursively(N.getNode()->getOperand(0), 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(1), 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());
961 // Try again after commuting the operands.
963 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM,
964 DeadNodes, Depth+1)) {
965 if (DeadNodes.IsDeleted(N.getNode()))
966 // If it is successful but the recursive update causes N to be deleted,
967 // then it's not safe to continue.
969 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM,
971 // If it is successful but the recursive update causes N to be deleted,
972 // then it's not safe to continue.
973 return DeadNodes.IsDeleted(N.getNode());
977 // If we couldn't fold both operands into the address at the same time,
978 // see if we can just put each operand into a register and fold at least
980 if (AM.BaseType == X86ISelAddressMode::RegBase &&
981 !AM.Base_Reg.getNode() &&
982 !AM.IndexReg.getNode()) {
983 AM.Base_Reg = N.getNode()->getOperand(0);
984 AM.IndexReg = N.getNode()->getOperand(1);
992 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
993 if (isLogicallyAddWithConstant(N, CurDAG)) {
994 X86ISelAddressMode Backup = AM;
995 ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
996 uint64_t Offset = CN->getSExtValue();
998 // Start with the LHS as an addr mode.
999 if (!MatchAddressRecursively(N.getOperand(0), AM, DeadNodes, Depth+1) &&
1000 // Address could not have picked a GV address for the displacement.
1002 // On x86-64, the resultant disp must fit in 32-bits.
1004 X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
1005 AM.hasSymbolicDisplacement()))) {
1014 // Perform some heroic transforms on an and of a constant-count shift
1015 // with a constant to enable use of the scaled offset field.
1017 SDValue Shift = N.getOperand(0);
1018 if (Shift.getNumOperands() != 2) break;
1020 // Scale must not be used already.
1021 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1023 SDValue X = Shift.getOperand(0);
1024 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1025 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1026 if (!C1 || !C2) break;
1028 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1029 // allows us to convert the shift and and into an h-register extract and
1031 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1032 unsigned ScaleLog = 8 - C1->getZExtValue();
1033 if (ScaleLog > 0 && ScaleLog < 4 &&
1034 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1035 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1036 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1037 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1039 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1041 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1042 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1045 // Insert the new nodes into the topological ordering.
1046 if (Eight.getNode()->getNodeId() == -1 ||
1047 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1048 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1049 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1051 if (Mask.getNode()->getNodeId() == -1 ||
1052 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1053 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1054 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1056 if (Srl.getNode()->getNodeId() == -1 ||
1057 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1058 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1059 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1061 if (And.getNode()->getNodeId() == -1 ||
1062 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1063 CurDAG->RepositionNode(N.getNode(), And.getNode());
1064 And.getNode()->setNodeId(N.getNode()->getNodeId());
1066 if (ShlCount.getNode()->getNodeId() == -1 ||
1067 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1068 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1069 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1071 if (Shl.getNode()->getNodeId() == -1 ||
1072 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1073 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1074 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1076 CurDAG->ReplaceAllUsesWith(N, Shl, &DeadNodes);
1078 AM.Scale = (1 << ScaleLog);
1083 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1084 // allows us to fold the shift into this addressing mode.
1085 if (Shift.getOpcode() != ISD::SHL) break;
1087 // Not likely to be profitable if either the AND or SHIFT node has more
1088 // than one use (unless all uses are for address computation). Besides,
1089 // isel mechanism requires their node ids to be reused.
1090 if (!N.hasOneUse() || !Shift.hasOneUse())
1093 // Verify that the shift amount is something we can fold.
1094 unsigned ShiftCst = C1->getZExtValue();
1095 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1098 // Get the new AND mask, this folds to a constant.
1099 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1100 SDValue(C2, 0), SDValue(C1, 0));
1101 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1103 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1104 NewAND, SDValue(C1, 0));
1106 // Insert the new nodes into the topological ordering.
1107 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1108 CurDAG->RepositionNode(X.getNode(), C1);
1109 C1->setNodeId(X.getNode()->getNodeId());
1111 if (NewANDMask.getNode()->getNodeId() == -1 ||
1112 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1113 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1114 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1116 if (NewAND.getNode()->getNodeId() == -1 ||
1117 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1118 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1119 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1121 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1122 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1123 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1124 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1127 CurDAG->ReplaceAllUsesWith(N, NewSHIFT, &DeadNodes);
1129 AM.Scale = 1 << ShiftCst;
1130 AM.IndexReg = NewAND;
1135 return MatchAddressBase(N, AM);
1138 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1139 /// specified addressing mode without any further recursion.
1140 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1141 // Is the base register already occupied?
1142 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1143 // If so, check to see if the scale index register is set.
1144 if (AM.IndexReg.getNode() == 0) {
1150 // Otherwise, we cannot select it.
1154 // Default, generate it as a register.
1155 AM.BaseType = X86ISelAddressMode::RegBase;
1160 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1161 /// It returns the operands which make up the maximal addressing mode it can
1162 /// match by reference.
1163 bool X86DAGToDAGISel::SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
1164 SDValue &Scale, SDValue &Index,
1165 SDValue &Disp, SDValue &Segment) {
1166 X86ISelAddressMode AM;
1167 if (MatchAddress(N, AM))
1170 EVT VT = N.getValueType();
1171 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1172 if (!AM.Base_Reg.getNode())
1173 AM.Base_Reg = CurDAG->getRegister(0, VT);
1176 if (!AM.IndexReg.getNode())
1177 AM.IndexReg = CurDAG->getRegister(0, VT);
1179 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1183 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1184 /// match a load whose top elements are either undef or zeros. The load flavor
1185 /// is derived from the type of N, which is either v4f32 or v2f64.
1188 /// PatternChainNode: this is the matched node that has a chain input and
1190 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1191 SDValue N, SDValue &Base,
1192 SDValue &Scale, SDValue &Index,
1193 SDValue &Disp, SDValue &Segment,
1194 SDValue &PatternNodeWithChain) {
1195 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1196 PatternNodeWithChain = N.getOperand(0);
1197 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1198 PatternNodeWithChain.hasOneUse() &&
1199 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1200 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1201 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1202 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp,Segment))
1208 // Also handle the case where we explicitly require zeros in the top
1209 // elements. This is a vector shuffle from the zero vector.
1210 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1211 // Check to see if the top elements are all zeros (or bitcast of zeros).
1212 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1213 N.getOperand(0).getNode()->hasOneUse() &&
1214 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1215 N.getOperand(0).getOperand(0).hasOneUse() &&
1216 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1217 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1218 // Okay, this is a zero extending load. Fold it.
1219 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1220 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1222 PatternNodeWithChain = SDValue(LD, 0);
1229 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1230 /// mode it matches can be cost effectively emitted as an LEA instruction.
1231 bool X86DAGToDAGISel::SelectLEAAddr(SDNode *Op, SDValue N,
1232 SDValue &Base, SDValue &Scale,
1233 SDValue &Index, SDValue &Disp) {
1234 X86ISelAddressMode AM;
1236 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1238 SDValue Copy = AM.Segment;
1239 SDValue T = CurDAG->getRegister(0, MVT::i32);
1241 if (MatchAddress(N, AM))
1243 assert (T == AM.Segment);
1246 EVT VT = N.getValueType();
1247 unsigned Complexity = 0;
1248 if (AM.BaseType == X86ISelAddressMode::RegBase)
1249 if (AM.Base_Reg.getNode())
1252 AM.Base_Reg = CurDAG->getRegister(0, VT);
1253 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1256 if (AM.IndexReg.getNode())
1259 AM.IndexReg = CurDAG->getRegister(0, VT);
1261 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1266 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1267 // to a LEA. This is determined with some expermentation but is by no means
1268 // optimal (especially for code size consideration). LEA is nice because of
1269 // its three-address nature. Tweak the cost function again when we can run
1270 // convertToThreeAddress() at register allocation time.
1271 if (AM.hasSymbolicDisplacement()) {
1272 // For X86-64, we should always use lea to materialize RIP relative
1274 if (Subtarget->is64Bit())
1280 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1283 // If it isn't worth using an LEA, reject it.
1284 if (Complexity <= 2)
1288 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1292 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1293 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
1294 SDValue &Scale, SDValue &Index,
1296 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1297 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1299 X86ISelAddressMode AM;
1300 AM.GV = GA->getGlobal();
1301 AM.Disp += GA->getOffset();
1302 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1303 AM.SymbolFlags = GA->getTargetFlags();
1305 if (N.getValueType() == MVT::i32) {
1307 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1309 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1313 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1318 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1319 SDValue &Base, SDValue &Scale,
1320 SDValue &Index, SDValue &Disp,
1322 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1323 !IsProfitableToFold(N, P, P) ||
1324 !IsLegalToFold(N, P, P, OptLevel))
1327 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1330 /// getGlobalBaseReg - Return an SDNode that returns the value of
1331 /// the global base register. Output instructions required to
1332 /// initialize the global base register, if necessary.
1334 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1335 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1336 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1339 static SDNode *FindCallStartFromCall(SDNode *Node) {
1340 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1341 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1342 "Node doesn't have a token chain argument!");
1343 return FindCallStartFromCall(Node->getOperand(0).getNode());
1346 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1347 SDValue Chain = Node->getOperand(0);
1348 SDValue In1 = Node->getOperand(1);
1349 SDValue In2L = Node->getOperand(2);
1350 SDValue In2H = Node->getOperand(3);
1351 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1352 if (!SelectAddr(In1.getNode(), In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1354 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1355 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1356 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1357 SDNode *ResNode = CurDAG->getMachineNode(Opc, Node->getDebugLoc(),
1358 MVT::i32, MVT::i32, MVT::Other, Ops,
1359 array_lengthof(Ops));
1360 cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1364 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1365 if (Node->hasAnyUseOfValue(0))
1368 // Optimize common patterns for __sync_add_and_fetch and
1369 // __sync_sub_and_fetch where the result is not used. This allows us
1370 // to use "lock" version of add, sub, inc, dec instructions.
1371 // FIXME: Do not use special instructions but instead add the "lock"
1372 // prefix to the target node somehow. The extra information will then be
1373 // transferred to machine instruction and it denotes the prefix.
1374 SDValue Chain = Node->getOperand(0);
1375 SDValue Ptr = Node->getOperand(1);
1376 SDValue Val = Node->getOperand(2);
1377 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1378 if (!SelectAddr(Ptr.getNode(), Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1381 bool isInc = false, isDec = false, isSub = false, isCN = false;
1382 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1385 int64_t CNVal = CN->getSExtValue();
1388 else if (CNVal == -1)
1390 else if (CNVal >= 0)
1391 Val = CurDAG->getTargetConstant(CNVal, NVT);
1394 Val = CurDAG->getTargetConstant(-CNVal, NVT);
1396 } else if (Val.hasOneUse() &&
1397 Val.getOpcode() == ISD::SUB &&
1398 X86::isZeroNode(Val.getOperand(0))) {
1400 Val = Val.getOperand(1);
1404 switch (NVT.getSimpleVT().SimpleTy) {
1408 Opc = X86::LOCK_INC8m;
1410 Opc = X86::LOCK_DEC8m;
1413 Opc = X86::LOCK_SUB8mi;
1415 Opc = X86::LOCK_SUB8mr;
1418 Opc = X86::LOCK_ADD8mi;
1420 Opc = X86::LOCK_ADD8mr;
1425 Opc = X86::LOCK_INC16m;
1427 Opc = X86::LOCK_DEC16m;
1430 if (Predicate_immSext8(Val.getNode()))
1431 Opc = X86::LOCK_SUB16mi8;
1433 Opc = X86::LOCK_SUB16mi;
1435 Opc = X86::LOCK_SUB16mr;
1438 if (Predicate_immSext8(Val.getNode()))
1439 Opc = X86::LOCK_ADD16mi8;
1441 Opc = X86::LOCK_ADD16mi;
1443 Opc = X86::LOCK_ADD16mr;
1448 Opc = X86::LOCK_INC32m;
1450 Opc = X86::LOCK_DEC32m;
1453 if (Predicate_immSext8(Val.getNode()))
1454 Opc = X86::LOCK_SUB32mi8;
1456 Opc = X86::LOCK_SUB32mi;
1458 Opc = X86::LOCK_SUB32mr;
1461 if (Predicate_immSext8(Val.getNode()))
1462 Opc = X86::LOCK_ADD32mi8;
1464 Opc = X86::LOCK_ADD32mi;
1466 Opc = X86::LOCK_ADD32mr;
1471 Opc = X86::LOCK_INC64m;
1473 Opc = X86::LOCK_DEC64m;
1475 Opc = X86::LOCK_SUB64mr;
1477 if (Predicate_immSext8(Val.getNode()))
1478 Opc = X86::LOCK_SUB64mi8;
1479 else if (Predicate_i64immSExt32(Val.getNode()))
1480 Opc = X86::LOCK_SUB64mi32;
1483 Opc = X86::LOCK_ADD64mr;
1485 if (Predicate_immSext8(Val.getNode()))
1486 Opc = X86::LOCK_ADD64mi8;
1487 else if (Predicate_i64immSExt32(Val.getNode()))
1488 Opc = X86::LOCK_ADD64mi32;
1494 DebugLoc dl = Node->getDebugLoc();
1495 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1497 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1498 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1499 if (isInc || isDec) {
1500 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1501 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 6), 0);
1502 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1503 SDValue RetVals[] = { Undef, Ret };
1504 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1506 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1507 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 7), 0);
1508 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1509 SDValue RetVals[] = { Undef, Ret };
1510 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1514 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1515 /// any uses which require the SF or OF bits to be accurate.
1516 static bool HasNoSignedComparisonUses(SDNode *N) {
1517 // Examine each user of the node.
1518 for (SDNode::use_iterator UI = N->use_begin(),
1519 UE = N->use_end(); UI != UE; ++UI) {
1520 // Only examine CopyToReg uses.
1521 if (UI->getOpcode() != ISD::CopyToReg)
1523 // Only examine CopyToReg uses that copy to EFLAGS.
1524 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1527 // Examine each user of the CopyToReg use.
1528 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1529 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1530 // Only examine the Flag result.
1531 if (FlagUI.getUse().getResNo() != 1) continue;
1532 // Anything unusual: assume conservatively.
1533 if (!FlagUI->isMachineOpcode()) return false;
1534 // Examine the opcode of the user.
1535 switch (FlagUI->getMachineOpcode()) {
1536 // These comparisons don't treat the most significant bit specially.
1537 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1538 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1539 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1540 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1541 case X86::JA_4: case X86::JAE_4: case X86::JB_4: case X86::JBE_4:
1542 case X86::JE_4: case X86::JNE_4: case X86::JP_4: case X86::JNP_4:
1543 case X86::CMOVA16rr: case X86::CMOVA16rm:
1544 case X86::CMOVA32rr: case X86::CMOVA32rm:
1545 case X86::CMOVA64rr: case X86::CMOVA64rm:
1546 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1547 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1548 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1549 case X86::CMOVB16rr: case X86::CMOVB16rm:
1550 case X86::CMOVB32rr: case X86::CMOVB32rm:
1551 case X86::CMOVB64rr: case X86::CMOVB64rm:
1552 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1553 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1554 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1555 case X86::CMOVE16rr: case X86::CMOVE16rm:
1556 case X86::CMOVE32rr: case X86::CMOVE32rm:
1557 case X86::CMOVE64rr: case X86::CMOVE64rm:
1558 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1559 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1560 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1561 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1562 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1563 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1564 case X86::CMOVP16rr: case X86::CMOVP16rm:
1565 case X86::CMOVP32rr: case X86::CMOVP32rm:
1566 case X86::CMOVP64rr: case X86::CMOVP64rm:
1568 // Anything else: assume conservatively.
1569 default: return false;
1576 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1577 EVT NVT = Node->getValueType(0);
1579 unsigned Opcode = Node->getOpcode();
1580 DebugLoc dl = Node->getDebugLoc();
1582 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1584 if (Node->isMachineOpcode()) {
1585 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
1586 return NULL; // Already selected.
1591 case X86ISD::GlobalBaseReg:
1592 return getGlobalBaseReg();
1594 case X86ISD::ATOMOR64_DAG:
1595 return SelectAtomic64(Node, X86::ATOMOR6432);
1596 case X86ISD::ATOMXOR64_DAG:
1597 return SelectAtomic64(Node, X86::ATOMXOR6432);
1598 case X86ISD::ATOMADD64_DAG:
1599 return SelectAtomic64(Node, X86::ATOMADD6432);
1600 case X86ISD::ATOMSUB64_DAG:
1601 return SelectAtomic64(Node, X86::ATOMSUB6432);
1602 case X86ISD::ATOMNAND64_DAG:
1603 return SelectAtomic64(Node, X86::ATOMNAND6432);
1604 case X86ISD::ATOMAND64_DAG:
1605 return SelectAtomic64(Node, X86::ATOMAND6432);
1606 case X86ISD::ATOMSWAP64_DAG:
1607 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1609 case ISD::ATOMIC_LOAD_ADD: {
1610 SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1616 case ISD::SMUL_LOHI:
1617 case ISD::UMUL_LOHI: {
1618 SDValue N0 = Node->getOperand(0);
1619 SDValue N1 = Node->getOperand(1);
1621 bool isSigned = Opcode == ISD::SMUL_LOHI;
1623 switch (NVT.getSimpleVT().SimpleTy) {
1624 default: llvm_unreachable("Unsupported VT!");
1625 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1626 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1627 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1628 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1631 switch (NVT.getSimpleVT().SimpleTy) {
1632 default: llvm_unreachable("Unsupported VT!");
1633 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1634 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1635 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1636 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1640 unsigned LoReg, HiReg;
1641 switch (NVT.getSimpleVT().SimpleTy) {
1642 default: llvm_unreachable("Unsupported VT!");
1643 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1644 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1645 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1646 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1649 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1650 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1651 // Multiply is commmutative.
1653 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1658 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1659 N0, SDValue()).getValue(1);
1662 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1665 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1666 array_lengthof(Ops));
1667 InFlag = SDValue(CNode, 1);
1668 // Update the chain.
1669 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1672 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1675 // Copy the low half of the result, if it is needed.
1676 if (!SDValue(Node, 0).use_empty()) {
1677 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1678 LoReg, NVT, InFlag);
1679 InFlag = Result.getValue(2);
1680 ReplaceUses(SDValue(Node, 0), Result);
1681 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1683 // Copy the high half of the result, if it is needed.
1684 if (!SDValue(Node, 1).use_empty()) {
1686 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1687 // Prevent use of AH in a REX instruction by referencing AX instead.
1688 // Shift it down 8 bits.
1689 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1690 X86::AX, MVT::i16, InFlag);
1691 InFlag = Result.getValue(2);
1692 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1694 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1695 // Then truncate it down to i8.
1696 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1699 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1700 HiReg, NVT, InFlag);
1701 InFlag = Result.getValue(2);
1703 ReplaceUses(SDValue(Node, 1), Result);
1704 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1711 case ISD::UDIVREM: {
1712 SDValue N0 = Node->getOperand(0);
1713 SDValue N1 = Node->getOperand(1);
1715 bool isSigned = Opcode == ISD::SDIVREM;
1717 switch (NVT.getSimpleVT().SimpleTy) {
1718 default: llvm_unreachable("Unsupported VT!");
1719 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1720 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1721 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1722 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1725 switch (NVT.getSimpleVT().SimpleTy) {
1726 default: llvm_unreachable("Unsupported VT!");
1727 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1728 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1729 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1730 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1734 unsigned LoReg, HiReg, ClrReg;
1735 unsigned ClrOpcode, SExtOpcode;
1736 switch (NVT.getSimpleVT().SimpleTy) {
1737 default: llvm_unreachable("Unsupported VT!");
1739 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
1741 SExtOpcode = X86::CBW;
1744 LoReg = X86::AX; HiReg = X86::DX;
1745 ClrOpcode = X86::MOV16r0; ClrReg = X86::DX;
1746 SExtOpcode = X86::CWD;
1749 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
1750 ClrOpcode = X86::MOV32r0;
1751 SExtOpcode = X86::CDQ;
1754 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
1755 ClrOpcode = X86::MOV64r0;
1756 SExtOpcode = X86::CQO;
1760 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1761 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1762 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1765 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1766 // Special case for div8, just use a move with zero extension to AX to
1767 // clear the upper 8 bits (AH).
1768 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1769 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1770 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1772 SDValue(CurDAG->getMachineNode(X86::MOVZX16rm8, dl, MVT::i16,
1774 array_lengthof(Ops)), 0);
1775 Chain = Move.getValue(1);
1776 ReplaceUses(N0.getValue(1), Chain);
1779 SDValue(CurDAG->getMachineNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1780 Chain = CurDAG->getEntryNode();
1782 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1783 InFlag = Chain.getValue(1);
1786 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1787 LoReg, N0, SDValue()).getValue(1);
1788 if (isSigned && !signBitIsZero) {
1789 // Sign extend the low part into the high part.
1791 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1793 // Zero out the high part, effectively zero extending the input.
1795 SDValue(CurDAG->getMachineNode(ClrOpcode, dl, NVT), 0);
1796 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
1797 ClrNode, InFlag).getValue(1);
1802 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1805 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1806 array_lengthof(Ops));
1807 InFlag = SDValue(CNode, 1);
1808 // Update the chain.
1809 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1812 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1815 // Copy the division (low) result, if it is needed.
1816 if (!SDValue(Node, 0).use_empty()) {
1817 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1818 LoReg, NVT, InFlag);
1819 InFlag = Result.getValue(2);
1820 ReplaceUses(SDValue(Node, 0), Result);
1821 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1823 // Copy the remainder (high) result, if it is needed.
1824 if (!SDValue(Node, 1).use_empty()) {
1826 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1827 // Prevent use of AH in a REX instruction by referencing AX instead.
1828 // Shift it down 8 bits.
1829 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1830 X86::AX, MVT::i16, InFlag);
1831 InFlag = Result.getValue(2);
1832 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1834 CurDAG->getTargetConstant(8, MVT::i8)),
1836 // Then truncate it down to i8.
1837 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1840 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1841 HiReg, NVT, InFlag);
1842 InFlag = Result.getValue(2);
1844 ReplaceUses(SDValue(Node, 1), Result);
1845 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1851 SDValue N0 = Node->getOperand(0);
1852 SDValue N1 = Node->getOperand(1);
1854 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
1855 // use a smaller encoding.
1856 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
1857 // Look past the truncate if CMP is the only use of it.
1858 N0 = N0.getOperand(0);
1859 if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1860 N0.getValueType() != MVT::i8 &&
1861 X86::isZeroNode(N1)) {
1862 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
1865 // For example, convert "testl %eax, $8" to "testb %al, $8"
1866 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
1867 (!(C->getZExtValue() & 0x80) ||
1868 HasNoSignedComparisonUses(Node))) {
1869 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
1870 SDValue Reg = N0.getNode()->getOperand(0);
1872 // On x86-32, only the ABCD registers have 8-bit subregisters.
1873 if (!Subtarget->is64Bit()) {
1874 TargetRegisterClass *TRC = 0;
1875 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1876 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1877 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1878 default: llvm_unreachable("Unsupported TEST operand type!");
1880 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1881 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1882 Reg.getValueType(), Reg, RC), 0);
1885 // Extract the l-register.
1886 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1890 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
1893 // For example, "testl %eax, $2048" to "testb %ah, $8".
1894 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
1895 (!(C->getZExtValue() & 0x8000) ||
1896 HasNoSignedComparisonUses(Node))) {
1897 // Shift the immediate right by 8 bits.
1898 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
1900 SDValue Reg = N0.getNode()->getOperand(0);
1902 // Put the value in an ABCD register.
1903 TargetRegisterClass *TRC = 0;
1904 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1905 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
1906 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1907 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1908 default: llvm_unreachable("Unsupported TEST operand type!");
1910 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1911 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1912 Reg.getValueType(), Reg, RC), 0);
1914 // Extract the h-register.
1915 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
1918 // Emit a testb. No special NOREX tricks are needed since there's
1919 // only one GPR operand!
1920 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
1921 Subreg, ShiftedImm);
1924 // For example, "testl %eax, $32776" to "testw %ax, $32776".
1925 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
1926 N0.getValueType() != MVT::i16 &&
1927 (!(C->getZExtValue() & 0x8000) ||
1928 HasNoSignedComparisonUses(Node))) {
1929 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
1930 SDValue Reg = N0.getNode()->getOperand(0);
1932 // Extract the 16-bit subregister.
1933 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
1937 return CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
1940 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
1941 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
1942 N0.getValueType() == MVT::i64 &&
1943 (!(C->getZExtValue() & 0x80000000) ||
1944 HasNoSignedComparisonUses(Node))) {
1945 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
1946 SDValue Reg = N0.getNode()->getOperand(0);
1948 // Extract the 32-bit subregister.
1949 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
1953 return CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
1960 SDNode *ResNode = SelectCode(Node);
1962 DEBUG(dbgs() << "=> ";
1963 if (ResNode == NULL || ResNode == Node)
1966 ResNode->dump(CurDAG);
1972 bool X86DAGToDAGISel::
1973 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1974 std::vector<SDValue> &OutOps) {
1975 SDValue Op0, Op1, Op2, Op3, Op4;
1976 switch (ConstraintCode) {
1977 case 'o': // offsetable ??
1978 case 'v': // not offsetable ??
1979 default: return true;
1981 if (!SelectAddr(Op.getNode(), Op, Op0, Op1, Op2, Op3, Op4))
1986 OutOps.push_back(Op0);
1987 OutOps.push_back(Op1);
1988 OutOps.push_back(Op2);
1989 OutOps.push_back(Op3);
1990 OutOps.push_back(Op4);
1994 /// createX86ISelDag - This pass converts a legalized DAG into a
1995 /// X86-specific DAG, ready for instruction scheduling.
1997 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1998 llvm::CodeGenOpt::Level OptLevel) {
1999 return new X86DAGToDAGISel(TM, OptLevel);