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 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
40 #define DEBUG_TYPE "x86-isel"
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;
72 unsigned Align; // CP alignment.
73 unsigned char SymbolFlags; // X86II::MO_*
76 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
77 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
78 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
80 bool hasSymbolicDisplacement() const {
81 return GV != nullptr || CP != nullptr || ES != nullptr ||
82 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
85 bool hasBaseOrIndexReg() const {
86 return BaseType == FrameIndexBase ||
87 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
90 /// isRIPRelative - Return true if this addressing mode is already RIP
92 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
95 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
96 return RegNode->getReg() == X86::RIP;
100 void setBaseReg(SDValue Reg) {
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
107 dbgs() << "X86ISelAddressMode " << this << '\n';
108 dbgs() << "Base_Reg ";
109 if (Base_Reg.getNode())
110 Base_Reg.getNode()->dump();
113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114 << " Scale" << Scale << '\n'
116 if (IndexReg.getNode())
117 IndexReg.getNode()->dump();
120 dbgs() << " Disp " << Disp << '\n'
142 dbgs() << " JT" << JT << " Align" << Align << '\n';
149 //===--------------------------------------------------------------------===//
150 /// ISel - X86 specific code to select X86 machine instructions for
151 /// SelectionDAG operations.
153 class X86DAGToDAGISel final : public SelectionDAGISel {
154 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
158 /// OptForSize - If true, selector should try to optimize for code size
159 /// instead of performance.
163 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
164 : SelectionDAGISel(tm, OptLevel), OptForSize(false) {}
166 const char *getPassName() const override {
167 return "X86 DAG->DAG Instruction Selection";
170 bool runOnMachineFunction(MachineFunction &MF) override {
171 // Reset the subtarget each time through.
172 Subtarget = &MF.getSubtarget<X86Subtarget>();
173 SelectionDAGISel::runOnMachineFunction(MF);
177 void EmitFunctionEntryCode() override;
179 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
181 void PreprocessISelDAG() override;
183 inline bool immSext8(SDNode *N) const {
184 return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
187 // i64immSExt32 predicate - True if the 64-bit immediate fits in a 32-bit
188 // sign extended field.
189 inline bool i64immSExt32(SDNode *N) const {
190 uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
191 return (int64_t)v == (int32_t)v;
194 // Include the pieces autogenerated from the target description.
195 #include "X86GenDAGISel.inc"
198 SDNode *Select(SDNode *N) override;
199 SDNode *SelectGather(SDNode *N, unsigned Opc);
200 SDNode *SelectAtomicLoadArith(SDNode *Node, MVT NVT);
202 bool FoldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203 bool MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
205 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
206 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
208 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
209 bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
210 SDValue &Scale, SDValue &Index, SDValue &Disp,
212 bool SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
213 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 bool SelectMOV64Imm32(SDValue N, SDValue &Imm);
216 bool SelectLEAAddr(SDValue N, SDValue &Base,
217 SDValue &Scale, SDValue &Index, SDValue &Disp,
219 bool SelectLEA64_32Addr(SDValue N, SDValue &Base,
220 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 bool SelectTLSADDRAddr(SDValue N, SDValue &Base,
223 SDValue &Scale, SDValue &Index, SDValue &Disp,
225 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
226 SDValue &Base, SDValue &Scale,
227 SDValue &Index, SDValue &Disp,
229 SDValue &NodeWithChain);
231 bool TryFoldLoad(SDNode *P, SDValue N,
232 SDValue &Base, SDValue &Scale,
233 SDValue &Index, SDValue &Disp,
236 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
237 /// inline asm expressions.
238 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
239 unsigned ConstraintID,
240 std::vector<SDValue> &OutOps) override;
242 void EmitSpecialCodeForMain();
244 inline void getAddressOperands(X86ISelAddressMode &AM, SDLoc DL,
245 SDValue &Base, SDValue &Scale,
246 SDValue &Index, SDValue &Disp,
248 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
249 ? CurDAG->getTargetFrameIndex(
251 TLI->getPointerTy(CurDAG->getDataLayout()))
253 Scale = getI8Imm(AM.Scale, DL);
255 // These are 32-bit even in 64-bit mode since RIP relative offset
258 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
262 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
263 AM.Align, AM.Disp, AM.SymbolFlags);
265 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
266 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
267 } else if (AM.MCSym) {
268 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
269 assert(AM.SymbolFlags == 0 && "oo");
270 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
271 } else if (AM.JT != -1) {
272 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
273 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
274 } else if (AM.BlockAddr)
275 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
278 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
280 if (AM.Segment.getNode())
281 Segment = AM.Segment;
283 Segment = CurDAG->getRegister(0, MVT::i32);
286 // Utility function to determine whether we should avoid selecting
287 // immediate forms of instructions for better code size or not.
288 // At a high level, we'd like to avoid such instructions when
289 // we have similar constants used within the same basic block
290 // that can be kept in a register.
292 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
293 uint32_t UseCount = 0;
295 // Do not want to hoist if we're not optimizing for size.
296 // TODO: We'd like to remove this restriction.
297 // See the comment in X86InstrInfo.td for more info.
301 // Walk all the users of the immediate.
302 for (SDNode::use_iterator UI = N->use_begin(),
303 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
307 // This user is already selected. Count it as a legitimate use and
309 if (User->isMachineOpcode()) {
314 // We want to count stores of immediates as real uses.
315 if (User->getOpcode() == ISD::STORE &&
316 User->getOperand(1).getNode() == N) {
321 // We don't currently match users that have > 2 operands (except
322 // for stores, which are handled above)
323 // Those instruction won't match in ISEL, for now, and would
324 // be counted incorrectly.
325 // This may change in the future as we add additional instruction
327 if (User->getNumOperands() != 2)
330 // Immediates that are used for offsets as part of stack
331 // manipulation should be left alone. These are typically
332 // used to indicate SP offsets for argument passing and
333 // will get pulled into stores/pushes (implicitly).
334 if (User->getOpcode() == X86ISD::ADD ||
335 User->getOpcode() == ISD::ADD ||
336 User->getOpcode() == X86ISD::SUB ||
337 User->getOpcode() == ISD::SUB) {
339 // Find the other operand of the add/sub.
340 SDValue OtherOp = User->getOperand(0);
341 if (OtherOp.getNode() == N)
342 OtherOp = User->getOperand(1);
344 // Don't count if the other operand is SP.
345 RegisterSDNode *RegNode;
346 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
347 (RegNode = dyn_cast_or_null<RegisterSDNode>(
348 OtherOp->getOperand(1).getNode())))
349 if ((RegNode->getReg() == X86::ESP) ||
350 (RegNode->getReg() == X86::RSP))
354 // ... otherwise, count this and move on.
358 // If we have more than 1 use, then recommend for hoisting.
359 return (UseCount > 1);
362 /// getI8Imm - Return a target constant with the specified value, of type
364 inline SDValue getI8Imm(unsigned Imm, SDLoc DL) {
365 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
368 /// getI32Imm - Return a target constant with the specified value, of type
370 inline SDValue getI32Imm(unsigned Imm, SDLoc DL) {
371 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
374 /// getGlobalBaseReg - Return an SDNode that returns the value of
375 /// the global base register. Output instructions required to
376 /// initialize the global base register, if necessary.
378 SDNode *getGlobalBaseReg();
380 /// getTargetMachine - Return a reference to the TargetMachine, casted
381 /// to the target-specific type.
382 const X86TargetMachine &getTargetMachine() const {
383 return static_cast<const X86TargetMachine &>(TM);
386 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
387 /// to the target-specific type.
388 const X86InstrInfo *getInstrInfo() const {
389 return Subtarget->getInstrInfo();
392 /// \brief Address-mode matching performs shift-of-and to and-of-shift
393 /// reassociation in order to expose more scaled addressing
395 bool ComplexPatternFuncMutatesDAG() const override {
403 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
404 if (OptLevel == CodeGenOpt::None) return false;
409 if (N.getOpcode() != ISD::LOAD)
412 // If N is a load, do additional profitability checks.
414 switch (U->getOpcode()) {
427 SDValue Op1 = U->getOperand(1);
429 // If the other operand is a 8-bit immediate we should fold the immediate
430 // instead. This reduces code size.
432 // movl 4(%esp), %eax
436 // addl 4(%esp), %eax
437 // The former is 2 bytes shorter. In case where the increment is 1, then
438 // the saving can be 4 bytes (by using incl %eax).
439 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
440 if (Imm->getAPIntValue().isSignedIntN(8))
443 // If the other operand is a TLS address, we should fold it instead.
446 // leal i@NTPOFF(%eax), %eax
448 // movl $i@NTPOFF, %eax
450 // if the block also has an access to a second TLS address this will save
452 // FIXME: This is probably also true for non-TLS addresses.
453 if (Op1.getOpcode() == X86ISD::Wrapper) {
454 SDValue Val = Op1.getOperand(0);
455 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
465 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
466 /// load's chain operand and move load below the call's chain operand.
467 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
468 SDValue Call, SDValue OrigChain) {
469 SmallVector<SDValue, 8> Ops;
470 SDValue Chain = OrigChain.getOperand(0);
471 if (Chain.getNode() == Load.getNode())
472 Ops.push_back(Load.getOperand(0));
474 assert(Chain.getOpcode() == ISD::TokenFactor &&
475 "Unexpected chain operand");
476 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
477 if (Chain.getOperand(i).getNode() == Load.getNode())
478 Ops.push_back(Load.getOperand(0));
480 Ops.push_back(Chain.getOperand(i));
482 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
484 Ops.push_back(NewChain);
486 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
487 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
488 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
489 Load.getOperand(1), Load.getOperand(2));
492 Ops.push_back(SDValue(Load.getNode(), 1));
493 Ops.append(Call->op_begin() + 1, Call->op_end());
494 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
497 /// isCalleeLoad - Return true if call address is a load and it can be
498 /// moved below CALLSEQ_START and the chains leading up to the call.
499 /// Return the CALLSEQ_START by reference as a second output.
500 /// In the case of a tail call, there isn't a callseq node between the call
501 /// chain and the load.
502 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
503 // The transformation is somewhat dangerous if the call's chain was glued to
504 // the call. After MoveBelowOrigChain the load is moved between the call and
505 // the chain, this can create a cycle if the load is not folded. So it is
506 // *really* important that we are sure the load will be folded.
507 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
509 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
512 LD->getAddressingMode() != ISD::UNINDEXED ||
513 LD->getExtensionType() != ISD::NON_EXTLOAD)
516 // Now let's find the callseq_start.
517 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
518 if (!Chain.hasOneUse())
520 Chain = Chain.getOperand(0);
523 if (!Chain.getNumOperands())
525 // Since we are not checking for AA here, conservatively abort if the chain
526 // writes to memory. It's not safe to move the callee (a load) across a store.
527 if (isa<MemSDNode>(Chain.getNode()) &&
528 cast<MemSDNode>(Chain.getNode())->writeMem())
530 if (Chain.getOperand(0).getNode() == Callee.getNode())
532 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
533 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
534 Callee.getValue(1).hasOneUse())
539 void X86DAGToDAGISel::PreprocessISelDAG() {
540 // OptForSize is used in pattern predicates that isel is matching.
541 OptForSize = MF->getFunction()->optForSize();
543 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
544 E = CurDAG->allnodes_end(); I != E; ) {
545 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
547 if (OptLevel != CodeGenOpt::None &&
548 // Only does this when target favors doesn't favor register indirect
550 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
551 (N->getOpcode() == X86ISD::TC_RETURN &&
552 // Only does this if load can be folded into TC_RETURN.
553 (Subtarget->is64Bit() ||
554 getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
555 /// Also try moving call address load from outside callseq_start to just
556 /// before the call to allow it to be folded.
574 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
575 SDValue Chain = N->getOperand(0);
576 SDValue Load = N->getOperand(1);
577 if (!isCalleeLoad(Load, Chain, HasCallSeq))
579 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
584 // Lower fpround and fpextend nodes that target the FP stack to be store and
585 // load to the stack. This is a gross hack. We would like to simply mark
586 // these as being illegal, but when we do that, legalize produces these when
587 // it expands calls, then expands these in the same legalize pass. We would
588 // like dag combine to be able to hack on these between the call expansion
589 // and the node legalization. As such this pass basically does "really
590 // late" legalization of these inline with the X86 isel pass.
591 // FIXME: This should only happen when not compiled with -O0.
592 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
595 MVT SrcVT = N->getOperand(0).getSimpleValueType();
596 MVT DstVT = N->getSimpleValueType(0);
598 // If any of the sources are vectors, no fp stack involved.
599 if (SrcVT.isVector() || DstVT.isVector())
602 // If the source and destination are SSE registers, then this is a legal
603 // conversion that should not be lowered.
604 const X86TargetLowering *X86Lowering =
605 static_cast<const X86TargetLowering *>(TLI);
606 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
607 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
608 if (SrcIsSSE && DstIsSSE)
611 if (!SrcIsSSE && !DstIsSSE) {
612 // If this is an FPStack extension, it is a noop.
613 if (N->getOpcode() == ISD::FP_EXTEND)
615 // If this is a value-preserving FPStack truncation, it is a noop.
616 if (N->getConstantOperandVal(1))
620 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
621 // FPStack has extload and truncstore. SSE can fold direct loads into other
622 // operations. Based on this, decide what we want to do.
624 if (N->getOpcode() == ISD::FP_ROUND)
625 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
627 MemVT = SrcIsSSE ? SrcVT : DstVT;
629 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
632 // FIXME: optimize the case where the src/dest is a load or store?
633 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
635 MemTmp, MachinePointerInfo(), MemVT,
637 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
638 MachinePointerInfo(),
639 MemVT, false, false, false, 0);
641 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
642 // extload we created. This will cause general havok on the dag because
643 // anything below the conversion could be folded into other existing nodes.
644 // To avoid invalidating 'I', back it up to the convert node.
646 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
648 // Now that we did that, the node is dead. Increment the iterator to the
649 // next node to process, then delete N.
651 CurDAG->DeleteNode(N);
656 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
657 /// the main function.
658 void X86DAGToDAGISel::EmitSpecialCodeForMain() {
659 if (Subtarget->isTargetCygMing()) {
660 TargetLowering::ArgListTy Args;
661 auto &DL = CurDAG->getDataLayout();
663 TargetLowering::CallLoweringInfo CLI(*CurDAG);
664 CLI.setChain(CurDAG->getRoot())
665 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
666 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
668 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
669 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
670 CurDAG->setRoot(Result.second);
674 void X86DAGToDAGISel::EmitFunctionEntryCode() {
675 // If this is main, emit special code for main.
676 if (const Function *Fn = MF->getFunction())
677 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
678 EmitSpecialCodeForMain();
681 static bool isDispSafeForFrameIndex(int64_t Val) {
682 // On 64-bit platforms, we can run into an issue where a frame index
683 // includes a displacement that, when added to the explicit displacement,
684 // will overflow the displacement field. Assuming that the frame index
685 // displacement fits into a 31-bit integer (which is only slightly more
686 // aggressive than the current fundamental assumption that it fits into
687 // a 32-bit integer), a 31-bit disp should always be safe.
688 return isInt<31>(Val);
691 bool X86DAGToDAGISel::FoldOffsetIntoAddress(uint64_t Offset,
692 X86ISelAddressMode &AM) {
693 // Cannot combine ExternalSymbol displacements with integer offsets.
694 if (Offset != 0 && (AM.ES || AM.MCSym))
696 int64_t Val = AM.Disp + Offset;
697 CodeModel::Model M = TM.getCodeModel();
698 if (Subtarget->is64Bit()) {
699 if (!X86::isOffsetSuitableForCodeModel(Val, M,
700 AM.hasSymbolicDisplacement()))
702 // In addition to the checks required for a register base, check that
703 // we do not try to use an unsafe Disp with a frame index.
704 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
705 !isDispSafeForFrameIndex(Val))
713 bool X86DAGToDAGISel::MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
714 SDValue Address = N->getOperand(1);
716 // load gs:0 -> GS segment register.
717 // load fs:0 -> FS segment register.
719 // This optimization is valid because the GNU TLS model defines that
720 // gs:0 (or fs:0 on X86-64) contains its own address.
721 // For more information see http://people.redhat.com/drepper/tls.pdf
722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
723 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
724 Subtarget->isTargetLinux())
725 switch (N->getPointerInfo().getAddrSpace()) {
727 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
730 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
737 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
738 /// into an addressing mode. These wrap things that will resolve down into a
739 /// symbol reference. If no match is possible, this returns true, otherwise it
741 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
742 // If the addressing mode already has a symbol as the displacement, we can
743 // never match another symbol.
744 if (AM.hasSymbolicDisplacement())
747 SDValue N0 = N.getOperand(0);
748 CodeModel::Model M = TM.getCodeModel();
750 // Handle X86-64 rip-relative addresses. We check this before checking direct
751 // folding because RIP is preferable to non-RIP accesses.
752 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
753 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
754 // they cannot be folded into immediate fields.
755 // FIXME: This can be improved for kernel and other models?
756 (M == CodeModel::Small || M == CodeModel::Kernel)) {
757 // Base and index reg must be 0 in order to use %rip as base.
758 if (AM.hasBaseOrIndexReg())
760 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
761 X86ISelAddressMode Backup = AM;
762 AM.GV = G->getGlobal();
763 AM.SymbolFlags = G->getTargetFlags();
764 if (FoldOffsetIntoAddress(G->getOffset(), AM)) {
768 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
769 X86ISelAddressMode Backup = AM;
770 AM.CP = CP->getConstVal();
771 AM.Align = CP->getAlignment();
772 AM.SymbolFlags = CP->getTargetFlags();
773 if (FoldOffsetIntoAddress(CP->getOffset(), AM)) {
777 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
778 AM.ES = S->getSymbol();
779 AM.SymbolFlags = S->getTargetFlags();
780 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
781 AM.MCSym = S->getMCSymbol();
782 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
783 AM.JT = J->getIndex();
784 AM.SymbolFlags = J->getTargetFlags();
785 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
786 X86ISelAddressMode Backup = AM;
787 AM.BlockAddr = BA->getBlockAddress();
788 AM.SymbolFlags = BA->getTargetFlags();
789 if (FoldOffsetIntoAddress(BA->getOffset(), AM)) {
794 llvm_unreachable("Unhandled symbol reference node.");
796 if (N.getOpcode() == X86ISD::WrapperRIP)
797 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
801 // Handle the case when globals fit in our immediate field: This is true for
802 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
803 // mode, this only applies to a non-RIP-relative computation.
804 if (!Subtarget->is64Bit() ||
805 M == CodeModel::Small || M == CodeModel::Kernel) {
806 assert(N.getOpcode() != X86ISD::WrapperRIP &&
807 "RIP-relative addressing already handled");
808 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
809 AM.GV = G->getGlobal();
810 AM.Disp += G->getOffset();
811 AM.SymbolFlags = G->getTargetFlags();
812 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
813 AM.CP = CP->getConstVal();
814 AM.Align = CP->getAlignment();
815 AM.Disp += CP->getOffset();
816 AM.SymbolFlags = CP->getTargetFlags();
817 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
818 AM.ES = S->getSymbol();
819 AM.SymbolFlags = S->getTargetFlags();
820 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
821 AM.MCSym = S->getMCSymbol();
822 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
823 AM.JT = J->getIndex();
824 AM.SymbolFlags = J->getTargetFlags();
825 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
826 AM.BlockAddr = BA->getBlockAddress();
827 AM.Disp += BA->getOffset();
828 AM.SymbolFlags = BA->getTargetFlags();
830 llvm_unreachable("Unhandled symbol reference node.");
837 /// MatchAddress - Add the specified node to the specified addressing mode,
838 /// returning true if it cannot be done. This just pattern matches for the
840 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
841 if (MatchAddressRecursively(N, AM, 0))
844 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
845 // a smaller encoding and avoids a scaled-index.
847 AM.BaseType == X86ISelAddressMode::RegBase &&
848 AM.Base_Reg.getNode() == nullptr) {
849 AM.Base_Reg = AM.IndexReg;
853 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
854 // because it has a smaller encoding.
855 // TODO: Which other code models can use this?
856 if (TM.getCodeModel() == CodeModel::Small &&
857 Subtarget->is64Bit() &&
859 AM.BaseType == X86ISelAddressMode::RegBase &&
860 AM.Base_Reg.getNode() == nullptr &&
861 AM.IndexReg.getNode() == nullptr &&
862 AM.SymbolFlags == X86II::MO_NO_FLAG &&
863 AM.hasSymbolicDisplacement())
864 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
869 // Insert a node into the DAG at least before the Pos node's position. This
870 // will reposition the node as needed, and will assign it a node ID that is <=
871 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
872 // IDs! The selection DAG must no longer depend on their uniqueness when this
874 static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
875 if (N.getNode()->getNodeId() == -1 ||
876 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
877 DAG.RepositionNode(Pos.getNode(), N.getNode());
878 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
882 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
883 // safe. This allows us to convert the shift and and into an h-register
884 // extract and a scaled index. Returns false if the simplification is
886 static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
888 SDValue Shift, SDValue X,
889 X86ISelAddressMode &AM) {
890 if (Shift.getOpcode() != ISD::SRL ||
891 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
895 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
896 if (ScaleLog <= 0 || ScaleLog >= 4 ||
897 Mask != (0xffu << ScaleLog))
900 MVT VT = N.getSimpleValueType();
902 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
903 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
904 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
905 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
906 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
907 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
909 // Insert the new nodes into the topological ordering. We must do this in
910 // a valid topological ordering as nothing is going to go back and re-sort
911 // these nodes. We continually insert before 'N' in sequence as this is
912 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
913 // hierarchy left to express.
914 InsertDAGNode(DAG, N, Eight);
915 InsertDAGNode(DAG, N, Srl);
916 InsertDAGNode(DAG, N, NewMask);
917 InsertDAGNode(DAG, N, And);
918 InsertDAGNode(DAG, N, ShlCount);
919 InsertDAGNode(DAG, N, Shl);
920 DAG.ReplaceAllUsesWith(N, Shl);
922 AM.Scale = (1 << ScaleLog);
926 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
927 // allows us to fold the shift into this addressing mode. Returns false if the
928 // transform succeeded.
929 static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
931 SDValue Shift, SDValue X,
932 X86ISelAddressMode &AM) {
933 if (Shift.getOpcode() != ISD::SHL ||
934 !isa<ConstantSDNode>(Shift.getOperand(1)))
937 // Not likely to be profitable if either the AND or SHIFT node has more
938 // than one use (unless all uses are for address computation). Besides,
939 // isel mechanism requires their node ids to be reused.
940 if (!N.hasOneUse() || !Shift.hasOneUse())
943 // Verify that the shift amount is something we can fold.
944 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
945 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
948 MVT VT = N.getSimpleValueType();
950 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
951 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
952 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
954 // Insert the new nodes into the topological ordering. We must do this in
955 // a valid topological ordering as nothing is going to go back and re-sort
956 // these nodes. We continually insert before 'N' in sequence as this is
957 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
958 // hierarchy left to express.
959 InsertDAGNode(DAG, N, NewMask);
960 InsertDAGNode(DAG, N, NewAnd);
961 InsertDAGNode(DAG, N, NewShift);
962 DAG.ReplaceAllUsesWith(N, NewShift);
964 AM.Scale = 1 << ShiftAmt;
965 AM.IndexReg = NewAnd;
969 // Implement some heroics to detect shifts of masked values where the mask can
970 // be replaced by extending the shift and undoing that in the addressing mode
971 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
972 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
973 // the addressing mode. This results in code such as:
975 // int f(short *y, int *lookup_table) {
977 // return *y + lookup_table[*y >> 11];
981 // movzwl (%rdi), %eax
984 // addl (%rsi,%rcx,4), %eax
987 // movzwl (%rdi), %eax
991 // addl (%rsi,%rcx), %eax
993 // Note that this function assumes the mask is provided as a mask *after* the
994 // value is shifted. The input chain may or may not match that, but computing
995 // such a mask is trivial.
996 static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
998 SDValue Shift, SDValue X,
999 X86ISelAddressMode &AM) {
1000 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1001 !isa<ConstantSDNode>(Shift.getOperand(1)))
1004 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1005 unsigned MaskLZ = countLeadingZeros(Mask);
1006 unsigned MaskTZ = countTrailingZeros(Mask);
1008 // The amount of shift we're trying to fit into the addressing mode is taken
1009 // from the trailing zeros of the mask.
1010 unsigned AMShiftAmt = MaskTZ;
1012 // There is nothing we can do here unless the mask is removing some bits.
1013 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1014 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1016 // We also need to ensure that mask is a continuous run of bits.
1017 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1019 // Scale the leading zero count down based on the actual size of the value.
1020 // Also scale it down based on the size of the shift.
1021 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1023 // The final check is to ensure that any masked out high bits of X are
1024 // already known to be zero. Otherwise, the mask has a semantic impact
1025 // other than masking out a couple of low bits. Unfortunately, because of
1026 // the mask, zero extensions will be removed from operands in some cases.
1027 // This code works extra hard to look through extensions because we can
1028 // replace them with zero extensions cheaply if necessary.
1029 bool ReplacingAnyExtend = false;
1030 if (X.getOpcode() == ISD::ANY_EXTEND) {
1031 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1032 X.getOperand(0).getSimpleValueType().getSizeInBits();
1033 // Assume that we'll replace the any-extend with a zero-extend, and
1034 // narrow the search to the extended value.
1035 X = X.getOperand(0);
1036 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1037 ReplacingAnyExtend = true;
1039 APInt MaskedHighBits =
1040 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1041 APInt KnownZero, KnownOne;
1042 DAG.computeKnownBits(X, KnownZero, KnownOne);
1043 if (MaskedHighBits != KnownZero) return true;
1045 // We've identified a pattern that can be transformed into a single shift
1046 // and an addressing mode. Make it so.
1047 MVT VT = N.getSimpleValueType();
1048 if (ReplacingAnyExtend) {
1049 assert(X.getValueType() != VT);
1050 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1051 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1052 InsertDAGNode(DAG, N, NewX);
1056 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1057 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1058 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1059 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1061 // Insert the new nodes into the topological ordering. We must do this in
1062 // a valid topological ordering as nothing is going to go back and re-sort
1063 // these nodes. We continually insert before 'N' in sequence as this is
1064 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1065 // hierarchy left to express.
1066 InsertDAGNode(DAG, N, NewSRLAmt);
1067 InsertDAGNode(DAG, N, NewSRL);
1068 InsertDAGNode(DAG, N, NewSHLAmt);
1069 InsertDAGNode(DAG, N, NewSHL);
1070 DAG.ReplaceAllUsesWith(N, NewSHL);
1072 AM.Scale = 1 << AMShiftAmt;
1073 AM.IndexReg = NewSRL;
1077 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1081 dbgs() << "MatchAddress: ";
1086 return MatchAddressBase(N, AM);
1088 // If this is already a %rip relative address, we can only merge immediates
1089 // into it. Instead of handling this in every case, we handle it here.
1090 // RIP relative addressing: %rip + 32-bit displacement!
1091 if (AM.isRIPRelative()) {
1092 // FIXME: JumpTable and ExternalSymbol address currently don't like
1093 // displacements. It isn't very important, but this should be fixed for
1095 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1098 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1099 if (!FoldOffsetIntoAddress(Cst->getSExtValue(), AM))
1104 switch (N.getOpcode()) {
1106 case ISD::LOCAL_RECOVER: {
1107 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1108 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1109 // Use the symbol and don't prefix it.
1110 AM.MCSym = ESNode->getMCSymbol();
1115 case ISD::Constant: {
1116 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1117 if (!FoldOffsetIntoAddress(Val, AM))
1122 case X86ISD::Wrapper:
1123 case X86ISD::WrapperRIP:
1124 if (!MatchWrapper(N, AM))
1129 if (!MatchLoadInAddress(cast<LoadSDNode>(N), AM))
1133 case ISD::FrameIndex:
1134 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1135 AM.Base_Reg.getNode() == nullptr &&
1136 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1137 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1138 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1144 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1148 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1149 unsigned Val = CN->getZExtValue();
1150 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1151 // that the base operand remains free for further matching. If
1152 // the base doesn't end up getting used, a post-processing step
1153 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1154 if (Val == 1 || Val == 2 || Val == 3) {
1155 AM.Scale = 1 << Val;
1156 SDValue ShVal = N.getNode()->getOperand(0);
1158 // Okay, we know that we have a scale by now. However, if the scaled
1159 // value is an add of something and a constant, we can fold the
1160 // constant into the disp field here.
1161 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1162 AM.IndexReg = ShVal.getNode()->getOperand(0);
1163 ConstantSDNode *AddVal =
1164 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1165 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1166 if (!FoldOffsetIntoAddress(Disp, AM))
1170 AM.IndexReg = ShVal;
1177 // Scale must not be used already.
1178 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1180 SDValue And = N.getOperand(0);
1181 if (And.getOpcode() != ISD::AND) break;
1182 SDValue X = And.getOperand(0);
1184 // We only handle up to 64-bit values here as those are what matter for
1185 // addressing mode optimizations.
1186 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1188 // The mask used for the transform is expected to be post-shift, but we
1189 // found the shift first so just apply the shift to the mask before passing
1191 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1192 !isa<ConstantSDNode>(And.getOperand(1)))
1194 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1196 // Try to fold the mask and shift into the scale, and return false if we
1198 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1203 case ISD::SMUL_LOHI:
1204 case ISD::UMUL_LOHI:
1205 // A mul_lohi where we need the low part can be folded as a plain multiply.
1206 if (N.getResNo() != 0) break;
1209 case X86ISD::MUL_IMM:
1210 // X*[3,5,9] -> X+X*[2,4,8]
1211 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1212 AM.Base_Reg.getNode() == nullptr &&
1213 AM.IndexReg.getNode() == nullptr) {
1215 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1216 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1217 CN->getZExtValue() == 9) {
1218 AM.Scale = unsigned(CN->getZExtValue())-1;
1220 SDValue MulVal = N.getNode()->getOperand(0);
1223 // Okay, we know that we have a scale by now. However, if the scaled
1224 // value is an add of something and a constant, we can fold the
1225 // constant into the disp field here.
1226 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1227 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1228 Reg = MulVal.getNode()->getOperand(0);
1229 ConstantSDNode *AddVal =
1230 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1231 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1232 if (FoldOffsetIntoAddress(Disp, AM))
1233 Reg = N.getNode()->getOperand(0);
1235 Reg = N.getNode()->getOperand(0);
1238 AM.IndexReg = AM.Base_Reg = Reg;
1245 // Given A-B, if A can be completely folded into the address and
1246 // the index field with the index field unused, use -B as the index.
1247 // This is a win if a has multiple parts that can be folded into
1248 // the address. Also, this saves a mov if the base register has
1249 // other uses, since it avoids a two-address sub instruction, however
1250 // it costs an additional mov if the index register has other uses.
1252 // Add an artificial use to this node so that we can keep track of
1253 // it if it gets CSE'd with a different node.
1254 HandleSDNode Handle(N);
1256 // Test if the LHS of the sub can be folded.
1257 X86ISelAddressMode Backup = AM;
1258 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1262 // Test if the index field is free for use.
1263 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1269 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1270 // If the RHS involves a register with multiple uses, this
1271 // transformation incurs an extra mov, due to the neg instruction
1272 // clobbering its operand.
1273 if (!RHS.getNode()->hasOneUse() ||
1274 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1275 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1276 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1277 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1278 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1280 // If the base is a register with multiple uses, this
1281 // transformation may save a mov.
1282 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1283 AM.Base_Reg.getNode() &&
1284 !AM.Base_Reg.getNode()->hasOneUse()) ||
1285 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1287 // If the folded LHS was interesting, this transformation saves
1288 // address arithmetic.
1289 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1290 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1291 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1293 // If it doesn't look like it may be an overall win, don't do it.
1299 // Ok, the transformation is legal and appears profitable. Go for it.
1300 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1301 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1305 // Insert the new nodes into the topological ordering.
1306 InsertDAGNode(*CurDAG, N, Zero);
1307 InsertDAGNode(*CurDAG, N, Neg);
1312 // Add an artificial use to this node so that we can keep track of
1313 // it if it gets CSE'd with a different node.
1314 HandleSDNode Handle(N);
1316 X86ISelAddressMode Backup = AM;
1317 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1318 !MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1322 // Try again after commuting the operands.
1323 if (!MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)&&
1324 !MatchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1328 // If we couldn't fold both operands into the address at the same time,
1329 // see if we can just put each operand into a register and fold at least
1331 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1332 !AM.Base_Reg.getNode() &&
1333 !AM.IndexReg.getNode()) {
1334 N = Handle.getValue();
1335 AM.Base_Reg = N.getOperand(0);
1336 AM.IndexReg = N.getOperand(1);
1340 N = Handle.getValue();
1345 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1346 if (CurDAG->isBaseWithConstantOffset(N)) {
1347 X86ISelAddressMode Backup = AM;
1348 ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
1350 // Start with the LHS as an addr mode.
1351 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1352 !FoldOffsetIntoAddress(CN->getSExtValue(), AM))
1359 // Perform some heroic transforms on an and of a constant-count shift
1360 // with a constant to enable use of the scaled offset field.
1362 // Scale must not be used already.
1363 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1365 SDValue Shift = N.getOperand(0);
1366 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1367 SDValue X = Shift.getOperand(0);
1369 // We only handle up to 64-bit values here as those are what matter for
1370 // addressing mode optimizations.
1371 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1373 if (!isa<ConstantSDNode>(N.getOperand(1)))
1375 uint64_t Mask = N.getConstantOperandVal(1);
1377 // Try to fold the mask and shift into an extract and scale.
1378 if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1381 // Try to fold the mask and shift directly into the scale.
1382 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1385 // Try to swap the mask and shift to place shifts which can be done as
1386 // a scale on the outside of the mask.
1387 if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1393 return MatchAddressBase(N, AM);
1396 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1397 /// specified addressing mode without any further recursion.
1398 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1399 // Is the base register already occupied?
1400 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1401 // If so, check to see if the scale index register is set.
1402 if (!AM.IndexReg.getNode()) {
1408 // Otherwise, we cannot select it.
1412 // Default, generate it as a register.
1413 AM.BaseType = X86ISelAddressMode::RegBase;
1418 bool X86DAGToDAGISel::SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1419 SDValue &Scale, SDValue &Index,
1420 SDValue &Disp, SDValue &Segment) {
1422 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1425 X86ISelAddressMode AM;
1426 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1427 // AddrSpace 256 -> GS, 257 -> FS.
1428 if (AddrSpace == 256)
1429 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1430 if (AddrSpace == 257)
1431 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1434 Base = Mgs->getBasePtr();
1435 Index = Mgs->getIndex();
1436 unsigned ScalarSize = Mgs->getValue().getValueType().getScalarSizeInBits();
1437 Scale = getI8Imm(ScalarSize/8, DL);
1439 // If Base is 0, the whole address is in index and the Scale is 1
1440 if (isa<ConstantSDNode>(Base)) {
1441 assert(dyn_cast<ConstantSDNode>(Base)->isNullValue() &&
1442 "Unexpected base in gather/scatter");
1443 Scale = getI8Imm(1, DL);
1444 Base = CurDAG->getRegister(0, MVT::i32);
1446 if (AM.Segment.getNode())
1447 Segment = AM.Segment;
1449 Segment = CurDAG->getRegister(0, MVT::i32);
1450 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1454 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1455 /// It returns the operands which make up the maximal addressing mode it can
1456 /// match by reference.
1458 /// Parent is the parent node of the addr operand that is being matched. It
1459 /// is always a load, store, atomic node, or null. It is only null when
1460 /// checking memory operands for inline asm nodes.
1461 bool X86DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1462 SDValue &Scale, SDValue &Index,
1463 SDValue &Disp, SDValue &Segment) {
1464 X86ISelAddressMode AM;
1467 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1468 // that are not a MemSDNode, and thus don't have proper addrspace info.
1469 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1470 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1471 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1472 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1473 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1474 unsigned AddrSpace =
1475 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1476 // AddrSpace 256 -> GS, 257 -> FS.
1477 if (AddrSpace == 256)
1478 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1479 if (AddrSpace == 257)
1480 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1483 if (MatchAddress(N, AM))
1486 MVT VT = N.getSimpleValueType();
1487 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1488 if (!AM.Base_Reg.getNode())
1489 AM.Base_Reg = CurDAG->getRegister(0, VT);
1492 if (!AM.IndexReg.getNode())
1493 AM.IndexReg = CurDAG->getRegister(0, VT);
1495 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1499 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1500 /// match a load whose top elements are either undef or zeros. The load flavor
1501 /// is derived from the type of N, which is either v4f32 or v2f64.
1504 /// PatternChainNode: this is the matched node that has a chain input and
1506 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1507 SDValue N, SDValue &Base,
1508 SDValue &Scale, SDValue &Index,
1509 SDValue &Disp, SDValue &Segment,
1510 SDValue &PatternNodeWithChain) {
1511 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1512 PatternNodeWithChain = N.getOperand(0);
1513 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1514 PatternNodeWithChain.hasOneUse() &&
1515 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1516 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1517 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1518 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1524 // Also handle the case where we explicitly require zeros in the top
1525 // elements. This is a vector shuffle from the zero vector.
1526 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1527 // Check to see if the top elements are all zeros (or bitcast of zeros).
1528 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1529 N.getOperand(0).getNode()->hasOneUse() &&
1530 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1531 N.getOperand(0).getOperand(0).hasOneUse() &&
1532 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1533 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1534 // Okay, this is a zero extending load. Fold it.
1535 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1536 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1538 PatternNodeWithChain = SDValue(LD, 0);
1545 bool X86DAGToDAGISel::SelectMOV64Imm32(SDValue N, SDValue &Imm) {
1546 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1547 uint64_t ImmVal = CN->getZExtValue();
1548 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1551 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1555 // In static codegen with small code model, we can get the address of a label
1556 // into a register with 'movl'. TableGen has already made sure we're looking
1557 // at a label of some kind.
1558 assert(N->getOpcode() == X86ISD::Wrapper &&
1559 "Unexpected node type for MOV32ri64");
1560 N = N.getOperand(0);
1562 if (N->getOpcode() != ISD::TargetConstantPool &&
1563 N->getOpcode() != ISD::TargetJumpTable &&
1564 N->getOpcode() != ISD::TargetGlobalAddress &&
1565 N->getOpcode() != ISD::TargetExternalSymbol &&
1566 N->getOpcode() != ISD::MCSymbol &&
1567 N->getOpcode() != ISD::TargetBlockAddress)
1571 return TM.getCodeModel() == CodeModel::Small;
1574 bool X86DAGToDAGISel::SelectLEA64_32Addr(SDValue N, SDValue &Base,
1575 SDValue &Scale, SDValue &Index,
1576 SDValue &Disp, SDValue &Segment) {
1577 if (!SelectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1581 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1582 if (RN && RN->getReg() == 0)
1583 Base = CurDAG->getRegister(0, MVT::i64);
1584 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1585 // Base could already be %rip, particularly in the x32 ABI.
1586 Base = SDValue(CurDAG->getMachineNode(
1587 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1588 CurDAG->getTargetConstant(0, DL, MVT::i64),
1590 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1594 RN = dyn_cast<RegisterSDNode>(Index);
1595 if (RN && RN->getReg() == 0)
1596 Index = CurDAG->getRegister(0, MVT::i64);
1598 assert(Index.getValueType() == MVT::i32 &&
1599 "Expect to be extending 32-bit registers for use in LEA");
1600 Index = SDValue(CurDAG->getMachineNode(
1601 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1602 CurDAG->getTargetConstant(0, DL, MVT::i64),
1604 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1612 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1613 /// mode it matches can be cost effectively emitted as an LEA instruction.
1614 bool X86DAGToDAGISel::SelectLEAAddr(SDValue N,
1615 SDValue &Base, SDValue &Scale,
1616 SDValue &Index, SDValue &Disp,
1618 X86ISelAddressMode AM;
1620 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1622 SDValue Copy = AM.Segment;
1623 SDValue T = CurDAG->getRegister(0, MVT::i32);
1625 if (MatchAddress(N, AM))
1627 assert (T == AM.Segment);
1630 MVT VT = N.getSimpleValueType();
1631 unsigned Complexity = 0;
1632 if (AM.BaseType == X86ISelAddressMode::RegBase)
1633 if (AM.Base_Reg.getNode())
1636 AM.Base_Reg = CurDAG->getRegister(0, VT);
1637 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1640 if (AM.IndexReg.getNode())
1643 AM.IndexReg = CurDAG->getRegister(0, VT);
1645 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1650 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1651 // to a LEA. This is determined with some expermentation but is by no means
1652 // optimal (especially for code size consideration). LEA is nice because of
1653 // its three-address nature. Tweak the cost function again when we can run
1654 // convertToThreeAddress() at register allocation time.
1655 if (AM.hasSymbolicDisplacement()) {
1656 // For X86-64, we should always use lea to materialize RIP relative
1658 if (Subtarget->is64Bit())
1664 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1667 // If it isn't worth using an LEA, reject it.
1668 if (Complexity <= 2)
1671 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1675 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1676 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue N, SDValue &Base,
1677 SDValue &Scale, SDValue &Index,
1678 SDValue &Disp, SDValue &Segment) {
1679 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1680 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1682 X86ISelAddressMode AM;
1683 AM.GV = GA->getGlobal();
1684 AM.Disp += GA->getOffset();
1685 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1686 AM.SymbolFlags = GA->getTargetFlags();
1688 if (N.getValueType() == MVT::i32) {
1690 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1692 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1695 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1700 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1701 SDValue &Base, SDValue &Scale,
1702 SDValue &Index, SDValue &Disp,
1704 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1705 !IsProfitableToFold(N, P, P) ||
1706 !IsLegalToFold(N, P, P, OptLevel))
1709 return SelectAddr(N.getNode(),
1710 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1713 /// getGlobalBaseReg - Return an SDNode that returns the value of
1714 /// the global base register. Output instructions required to
1715 /// initialize the global base register, if necessary.
1717 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1718 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1719 auto &DL = MF->getDataLayout();
1720 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1723 /// Atomic opcode table
1751 static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] = {
1762 X86::LOCK_ADD64mi32,
1775 X86::LOCK_SUB64mi32,
1827 X86::LOCK_AND64mi32,
1840 X86::LOCK_XOR64mi32,
1845 // Return the target constant operand for atomic-load-op and do simple
1846 // translations, such as from atomic-load-add to lock-sub. The return value is
1847 // one of the following 3 cases:
1848 // + target-constant, the operand could be supported as a target constant.
1849 // + empty, the operand is not needed any more with the new op selected.
1850 // + non-empty, otherwise.
1851 static SDValue getAtomicLoadArithTargetConstant(SelectionDAG *CurDAG,
1853 enum AtomicOpc &Op, MVT NVT,
1855 const X86Subtarget *Subtarget) {
1856 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val)) {
1857 int64_t CNVal = CN->getSExtValue();
1858 // Quit if not 32-bit imm.
1859 if ((int32_t)CNVal != CNVal)
1861 // Quit if INT32_MIN: it would be negated as it is negative and overflow,
1862 // producing an immediate that does not fit in the 32 bits available for
1863 // an immediate operand to sub. However, it still fits in 32 bits for the
1864 // add (since it is not negated) so we can return target-constant.
1865 if (CNVal == INT32_MIN)
1866 return CurDAG->getTargetConstant(CNVal, dl, NVT);
1867 // For atomic-load-add, we could do some optimizations.
1869 // Translate to INC/DEC if ADD by 1 or -1.
1870 if (((CNVal == 1) || (CNVal == -1)) && !Subtarget->slowIncDec()) {
1871 Op = (CNVal == 1) ? INC : DEC;
1872 // No more constant operand after being translated into INC/DEC.
1875 // Translate to SUB if ADD by negative value.
1881 return CurDAG->getTargetConstant(CNVal, dl, NVT);
1884 // If the value operand is single-used, try to optimize it.
1885 if (Op == ADD && Val.hasOneUse()) {
1886 // Translate (atomic-load-add ptr (sub 0 x)) back to (lock-sub x).
1887 if (Val.getOpcode() == ISD::SUB && X86::isZeroNode(Val.getOperand(0))) {
1889 return Val.getOperand(1);
1891 // A special case for i16, which needs truncating as, in most cases, it's
1892 // promoted to i32. We will translate
1893 // (atomic-load-add (truncate (sub 0 x))) to (lock-sub (EXTRACT_SUBREG x))
1894 if (Val.getOpcode() == ISD::TRUNCATE && NVT == MVT::i16 &&
1895 Val.getOperand(0).getOpcode() == ISD::SUB &&
1896 X86::isZeroNode(Val.getOperand(0).getOperand(0))) {
1898 Val = Val.getOperand(0);
1899 return CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, NVT,
1907 SDNode *X86DAGToDAGISel::SelectAtomicLoadArith(SDNode *Node, MVT NVT) {
1908 if (Node->hasAnyUseOfValue(0))
1913 // Optimize common patterns for __sync_or_and_fetch and similar arith
1914 // operations where the result is not used. This allows us to use the "lock"
1915 // version of the arithmetic instruction.
1916 SDValue Chain = Node->getOperand(0);
1917 SDValue Ptr = Node->getOperand(1);
1918 SDValue Val = Node->getOperand(2);
1919 SDValue Base, Scale, Index, Disp, Segment;
1920 if (!SelectAddr(Node, Ptr, Base, Scale, Index, Disp, Segment))
1923 // Which index into the table.
1925 switch (Node->getOpcode()) {
1928 case ISD::ATOMIC_LOAD_OR:
1931 case ISD::ATOMIC_LOAD_AND:
1934 case ISD::ATOMIC_LOAD_XOR:
1937 case ISD::ATOMIC_LOAD_ADD:
1942 Val = getAtomicLoadArithTargetConstant(CurDAG, dl, Op, NVT, Val, Subtarget);
1943 bool isUnOp = !Val.getNode();
1944 bool isCN = Val.getNode() && (Val.getOpcode() == ISD::TargetConstant);
1947 switch (NVT.SimpleTy) {
1948 default: return nullptr;
1951 Opc = AtomicOpcTbl[Op][ConstantI8];
1953 Opc = AtomicOpcTbl[Op][I8];
1957 if (immSext8(Val.getNode()))
1958 Opc = AtomicOpcTbl[Op][SextConstantI16];
1960 Opc = AtomicOpcTbl[Op][ConstantI16];
1962 Opc = AtomicOpcTbl[Op][I16];
1966 if (immSext8(Val.getNode()))
1967 Opc = AtomicOpcTbl[Op][SextConstantI32];
1969 Opc = AtomicOpcTbl[Op][ConstantI32];
1971 Opc = AtomicOpcTbl[Op][I32];
1975 if (immSext8(Val.getNode()))
1976 Opc = AtomicOpcTbl[Op][SextConstantI64];
1977 else if (i64immSExt32(Val.getNode()))
1978 Opc = AtomicOpcTbl[Op][ConstantI64];
1980 llvm_unreachable("True 64 bits constant in SelectAtomicLoadArith");
1982 Opc = AtomicOpcTbl[Op][I64];
1986 assert(Opc != 0 && "Invalid arith lock transform!");
1988 // Building the new node.
1991 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Chain };
1992 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1994 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Val, Chain };
1995 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1998 // Copying the MachineMemOperand.
1999 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2000 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
2001 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
2003 // We need to have two outputs as that is what the original instruction had.
2004 // So we add a dummy, undefined output. This is safe as we checked first
2005 // that no-one uses our output anyway.
2006 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
2008 SDValue RetVals[] = { Undef, Ret };
2009 return CurDAG->getMergeValues(RetVals, dl).getNode();
2012 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
2013 /// any uses which require the SF or OF bits to be accurate.
2014 static bool HasNoSignedComparisonUses(SDNode *N) {
2015 // Examine each user of the node.
2016 for (SDNode::use_iterator UI = N->use_begin(),
2017 UE = N->use_end(); UI != UE; ++UI) {
2018 // Only examine CopyToReg uses.
2019 if (UI->getOpcode() != ISD::CopyToReg)
2021 // Only examine CopyToReg uses that copy to EFLAGS.
2022 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2025 // Examine each user of the CopyToReg use.
2026 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2027 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2028 // Only examine the Flag result.
2029 if (FlagUI.getUse().getResNo() != 1) continue;
2030 // Anything unusual: assume conservatively.
2031 if (!FlagUI->isMachineOpcode()) return false;
2032 // Examine the opcode of the user.
2033 switch (FlagUI->getMachineOpcode()) {
2034 // These comparisons don't treat the most significant bit specially.
2035 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2036 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2037 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2038 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
2039 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2040 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
2041 case X86::CMOVA16rr: case X86::CMOVA16rm:
2042 case X86::CMOVA32rr: case X86::CMOVA32rm:
2043 case X86::CMOVA64rr: case X86::CMOVA64rm:
2044 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2045 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2046 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2047 case X86::CMOVB16rr: case X86::CMOVB16rm:
2048 case X86::CMOVB32rr: case X86::CMOVB32rm:
2049 case X86::CMOVB64rr: case X86::CMOVB64rm:
2050 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2051 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2052 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
2053 case X86::CMOVE16rr: case X86::CMOVE16rm:
2054 case X86::CMOVE32rr: case X86::CMOVE32rm:
2055 case X86::CMOVE64rr: case X86::CMOVE64rm:
2056 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2057 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2058 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2059 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2060 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2061 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2062 case X86::CMOVP16rr: case X86::CMOVP16rm:
2063 case X86::CMOVP32rr: case X86::CMOVP32rm:
2064 case X86::CMOVP64rr: case X86::CMOVP64rm:
2066 // Anything else: assume conservatively.
2067 default: return false;
2074 /// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNode
2075 /// is suitable for doing the {load; increment or decrement; store} to modify
2077 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
2078 SDValue StoredVal, SelectionDAG *CurDAG,
2079 LoadSDNode* &LoadNode, SDValue &InputChain) {
2081 // is the value stored the result of a DEC or INC?
2082 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
2084 // is the stored value result 0 of the load?
2085 if (StoredVal.getResNo() != 0) return false;
2087 // are there other uses of the loaded value than the inc or dec?
2088 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2090 // is the store non-extending and non-indexed?
2091 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2094 SDValue Load = StoredVal->getOperand(0);
2095 // Is the stored value a non-extending and non-indexed load?
2096 if (!ISD::isNormalLoad(Load.getNode())) return false;
2098 // Return LoadNode by reference.
2099 LoadNode = cast<LoadSDNode>(Load);
2100 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
2101 EVT LdVT = LoadNode->getMemoryVT();
2102 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
2106 // Is store the only read of the loaded value?
2107 if (!Load.hasOneUse())
2110 // Is the address of the store the same as the load?
2111 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2112 LoadNode->getOffset() != StoreNode->getOffset())
2115 // Check if the chain is produced by the load or is a TokenFactor with
2116 // the load output chain as an operand. Return InputChain by reference.
2117 SDValue Chain = StoreNode->getChain();
2119 bool ChainCheck = false;
2120 if (Chain == Load.getValue(1)) {
2122 InputChain = LoadNode->getChain();
2123 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2124 SmallVector<SDValue, 4> ChainOps;
2125 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2126 SDValue Op = Chain.getOperand(i);
2127 if (Op == Load.getValue(1)) {
2132 // Make sure using Op as part of the chain would not cause a cycle here.
2133 // In theory, we could check whether the chain node is a predecessor of
2134 // the load. But that can be very expensive. Instead visit the uses and
2135 // make sure they all have smaller node id than the load.
2136 int LoadId = LoadNode->getNodeId();
2137 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2138 UE = UI->use_end(); UI != UE; ++UI) {
2139 if (UI.getUse().getResNo() != 0)
2141 if (UI->getNodeId() > LoadId)
2145 ChainOps.push_back(Op);
2149 // Make a new TokenFactor with all the other input chains except
2151 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
2152 MVT::Other, ChainOps);
2160 /// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
2161 /// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
2162 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
2163 if (Opc == X86ISD::DEC) {
2164 if (LdVT == MVT::i64) return X86::DEC64m;
2165 if (LdVT == MVT::i32) return X86::DEC32m;
2166 if (LdVT == MVT::i16) return X86::DEC16m;
2167 if (LdVT == MVT::i8) return X86::DEC8m;
2169 assert(Opc == X86ISD::INC && "unrecognized opcode");
2170 if (LdVT == MVT::i64) return X86::INC64m;
2171 if (LdVT == MVT::i32) return X86::INC32m;
2172 if (LdVT == MVT::i16) return X86::INC16m;
2173 if (LdVT == MVT::i8) return X86::INC8m;
2175 llvm_unreachable("unrecognized size for LdVT");
2178 /// SelectGather - Customized ISel for GATHER operations.
2180 SDNode *X86DAGToDAGISel::SelectGather(SDNode *Node, unsigned Opc) {
2181 // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
2182 SDValue Chain = Node->getOperand(0);
2183 SDValue VSrc = Node->getOperand(2);
2184 SDValue Base = Node->getOperand(3);
2185 SDValue VIdx = Node->getOperand(4);
2186 SDValue VMask = Node->getOperand(5);
2187 ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
2191 SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
2196 // Memory Operands: Base, Scale, Index, Disp, Segment
2197 SDValue Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
2198 SDValue Segment = CurDAG->getRegister(0, MVT::i32);
2199 const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue(), DL), VIdx,
2200 Disp, Segment, VMask, Chain};
2201 SDNode *ResNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
2202 // Node has 2 outputs: VDst and MVT::Other.
2203 // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
2204 // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
2206 ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
2207 ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
2211 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
2212 MVT NVT = Node->getSimpleValueType(0);
2214 unsigned Opcode = Node->getOpcode();
2217 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2219 if (Node->isMachineOpcode()) {
2220 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
2221 Node->setNodeId(-1);
2222 return nullptr; // Already selected.
2228 if (Subtarget->isTargetNaCl())
2229 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2230 // leave the instruction alone.
2232 if (Subtarget->isTarget64BitILP32()) {
2233 // Converts a 32-bit register to a 64-bit, zero-extended version of
2234 // it. This is needed because x86-64 can do many things, but jmp %r32
2235 // ain't one of them.
2236 const SDValue &Target = Node->getOperand(1);
2237 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2238 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2239 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2240 Node->getOperand(0), ZextTarget);
2241 ReplaceUses(SDValue(Node, 0), Brind);
2242 SelectCode(ZextTarget.getNode());
2243 SelectCode(Brind.getNode());
2248 case ISD::INTRINSIC_W_CHAIN: {
2249 unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2252 case Intrinsic::x86_avx2_gather_d_pd:
2253 case Intrinsic::x86_avx2_gather_d_pd_256:
2254 case Intrinsic::x86_avx2_gather_q_pd:
2255 case Intrinsic::x86_avx2_gather_q_pd_256:
2256 case Intrinsic::x86_avx2_gather_d_ps:
2257 case Intrinsic::x86_avx2_gather_d_ps_256:
2258 case Intrinsic::x86_avx2_gather_q_ps:
2259 case Intrinsic::x86_avx2_gather_q_ps_256:
2260 case Intrinsic::x86_avx2_gather_d_q:
2261 case Intrinsic::x86_avx2_gather_d_q_256:
2262 case Intrinsic::x86_avx2_gather_q_q:
2263 case Intrinsic::x86_avx2_gather_q_q_256:
2264 case Intrinsic::x86_avx2_gather_d_d:
2265 case Intrinsic::x86_avx2_gather_d_d_256:
2266 case Intrinsic::x86_avx2_gather_q_d:
2267 case Intrinsic::x86_avx2_gather_q_d_256: {
2268 if (!Subtarget->hasAVX2())
2272 default: llvm_unreachable("Impossible intrinsic");
2273 case Intrinsic::x86_avx2_gather_d_pd: Opc = X86::VGATHERDPDrm; break;
2274 case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
2275 case Intrinsic::x86_avx2_gather_q_pd: Opc = X86::VGATHERQPDrm; break;
2276 case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
2277 case Intrinsic::x86_avx2_gather_d_ps: Opc = X86::VGATHERDPSrm; break;
2278 case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
2279 case Intrinsic::x86_avx2_gather_q_ps: Opc = X86::VGATHERQPSrm; break;
2280 case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
2281 case Intrinsic::x86_avx2_gather_d_q: Opc = X86::VPGATHERDQrm; break;
2282 case Intrinsic::x86_avx2_gather_d_q_256: Opc = X86::VPGATHERDQYrm; break;
2283 case Intrinsic::x86_avx2_gather_q_q: Opc = X86::VPGATHERQQrm; break;
2284 case Intrinsic::x86_avx2_gather_q_q_256: Opc = X86::VPGATHERQQYrm; break;
2285 case Intrinsic::x86_avx2_gather_d_d: Opc = X86::VPGATHERDDrm; break;
2286 case Intrinsic::x86_avx2_gather_d_d_256: Opc = X86::VPGATHERDDYrm; break;
2287 case Intrinsic::x86_avx2_gather_q_d: Opc = X86::VPGATHERQDrm; break;
2288 case Intrinsic::x86_avx2_gather_q_d_256: Opc = X86::VPGATHERQDYrm; break;
2290 SDNode *RetVal = SelectGather(Node, Opc);
2292 // We already called ReplaceUses inside SelectGather.
2299 case X86ISD::GlobalBaseReg:
2300 return getGlobalBaseReg();
2302 case X86ISD::SHRUNKBLEND: {
2303 // SHRUNKBLEND selects like a regular VSELECT.
2304 SDValue VSelect = CurDAG->getNode(
2305 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2306 Node->getOperand(1), Node->getOperand(2));
2307 ReplaceUses(SDValue(Node, 0), VSelect);
2308 SelectCode(VSelect.getNode());
2309 // We already called ReplaceUses.
2313 case ISD::ATOMIC_LOAD_XOR:
2314 case ISD::ATOMIC_LOAD_AND:
2315 case ISD::ATOMIC_LOAD_OR:
2316 case ISD::ATOMIC_LOAD_ADD: {
2317 SDNode *RetVal = SelectAtomicLoadArith(Node, NVT);
2325 // For operations of the form (x << C1) op C2, check if we can use a smaller
2326 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2327 SDValue N0 = Node->getOperand(0);
2328 SDValue N1 = Node->getOperand(1);
2330 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2333 // i8 is unshrinkable, i16 should be promoted to i32.
2334 if (NVT != MVT::i32 && NVT != MVT::i64)
2337 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2338 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2339 if (!Cst || !ShlCst)
2342 int64_t Val = Cst->getSExtValue();
2343 uint64_t ShlVal = ShlCst->getZExtValue();
2345 // Make sure that we don't change the operation by removing bits.
2346 // This only matters for OR and XOR, AND is unaffected.
2347 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2348 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2351 unsigned ShlOp, AddOp, Op;
2354 // Check the minimum bitwidth for the new constant.
2355 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2356 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2357 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2358 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2360 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2363 // Bail if there is no smaller encoding.
2367 switch (NVT.SimpleTy) {
2368 default: llvm_unreachable("Unsupported VT!");
2370 assert(CstVT == MVT::i8);
2371 ShlOp = X86::SHL32ri;
2372 AddOp = X86::ADD32rr;
2375 default: llvm_unreachable("Impossible opcode");
2376 case ISD::AND: Op = X86::AND32ri8; break;
2377 case ISD::OR: Op = X86::OR32ri8; break;
2378 case ISD::XOR: Op = X86::XOR32ri8; break;
2382 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2383 ShlOp = X86::SHL64ri;
2384 AddOp = X86::ADD64rr;
2387 default: llvm_unreachable("Impossible opcode");
2388 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2389 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2390 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2395 // Emit the smaller op and the shift.
2396 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2397 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2399 return CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2401 return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2402 getI8Imm(ShlVal, dl));
2405 case X86ISD::SMUL8: {
2406 SDValue N0 = Node->getOperand(0);
2407 SDValue N1 = Node->getOperand(1);
2409 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2411 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2412 N0, SDValue()).getValue(1);
2414 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2415 SDValue Ops[] = {N1, InFlag};
2416 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2418 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2419 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2423 case X86ISD::UMUL: {
2424 SDValue N0 = Node->getOperand(0);
2425 SDValue N1 = Node->getOperand(1);
2428 switch (NVT.SimpleTy) {
2429 default: llvm_unreachable("Unsupported VT!");
2430 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2431 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2432 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2433 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2436 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2437 N0, SDValue()).getValue(1);
2439 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2440 SDValue Ops[] = {N1, InFlag};
2441 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2443 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2444 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2445 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
2449 case ISD::SMUL_LOHI:
2450 case ISD::UMUL_LOHI: {
2451 SDValue N0 = Node->getOperand(0);
2452 SDValue N1 = Node->getOperand(1);
2454 bool isSigned = Opcode == ISD::SMUL_LOHI;
2455 bool hasBMI2 = Subtarget->hasBMI2();
2457 switch (NVT.SimpleTy) {
2458 default: llvm_unreachable("Unsupported VT!");
2459 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2460 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2461 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2462 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2463 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2464 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2467 switch (NVT.SimpleTy) {
2468 default: llvm_unreachable("Unsupported VT!");
2469 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2470 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2471 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2472 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2476 unsigned SrcReg, LoReg, HiReg;
2478 default: llvm_unreachable("Unknown MUL opcode!");
2481 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2485 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2489 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2493 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2496 SrcReg = X86::EDX; LoReg = HiReg = 0;
2499 SrcReg = X86::RDX; LoReg = HiReg = 0;
2503 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2504 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2505 // Multiply is commmutative.
2507 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2512 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2513 N0, SDValue()).getValue(1);
2514 SDValue ResHi, ResLo;
2518 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2520 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2521 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2522 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2523 ResHi = SDValue(CNode, 0);
2524 ResLo = SDValue(CNode, 1);
2525 Chain = SDValue(CNode, 2);
2526 InFlag = SDValue(CNode, 3);
2528 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2529 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2530 Chain = SDValue(CNode, 0);
2531 InFlag = SDValue(CNode, 1);
2534 // Update the chain.
2535 ReplaceUses(N1.getValue(1), Chain);
2537 SDValue Ops[] = { N1, InFlag };
2538 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2539 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2540 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2541 ResHi = SDValue(CNode, 0);
2542 ResLo = SDValue(CNode, 1);
2543 InFlag = SDValue(CNode, 2);
2545 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2546 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2547 InFlag = SDValue(CNode, 0);
2551 // Prevent use of AH in a REX instruction by referencing AX instead.
2552 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2553 !SDValue(Node, 1).use_empty()) {
2554 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2555 X86::AX, MVT::i16, InFlag);
2556 InFlag = Result.getValue(2);
2557 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2559 if (!SDValue(Node, 0).use_empty())
2560 ReplaceUses(SDValue(Node, 1),
2561 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2563 // Shift AX down 8 bits.
2564 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2566 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2568 // Then truncate it down to i8.
2569 ReplaceUses(SDValue(Node, 1),
2570 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2572 // Copy the low half of the result, if it is needed.
2573 if (!SDValue(Node, 0).use_empty()) {
2574 if (!ResLo.getNode()) {
2575 assert(LoReg && "Register for low half is not defined!");
2576 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2578 InFlag = ResLo.getValue(2);
2580 ReplaceUses(SDValue(Node, 0), ResLo);
2581 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2583 // Copy the high half of the result, if it is needed.
2584 if (!SDValue(Node, 1).use_empty()) {
2585 if (!ResHi.getNode()) {
2586 assert(HiReg && "Register for high half is not defined!");
2587 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2589 InFlag = ResHi.getValue(2);
2591 ReplaceUses(SDValue(Node, 1), ResHi);
2592 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2600 case X86ISD::SDIVREM8_SEXT_HREG:
2601 case X86ISD::UDIVREM8_ZEXT_HREG: {
2602 SDValue N0 = Node->getOperand(0);
2603 SDValue N1 = Node->getOperand(1);
2605 bool isSigned = (Opcode == ISD::SDIVREM ||
2606 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2608 switch (NVT.SimpleTy) {
2609 default: llvm_unreachable("Unsupported VT!");
2610 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2611 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2612 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2613 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2616 switch (NVT.SimpleTy) {
2617 default: llvm_unreachable("Unsupported VT!");
2618 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2619 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2620 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2621 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2625 unsigned LoReg, HiReg, ClrReg;
2626 unsigned SExtOpcode;
2627 switch (NVT.SimpleTy) {
2628 default: llvm_unreachable("Unsupported VT!");
2630 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2631 SExtOpcode = X86::CBW;
2634 LoReg = X86::AX; HiReg = X86::DX;
2636 SExtOpcode = X86::CWD;
2639 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2640 SExtOpcode = X86::CDQ;
2643 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2644 SExtOpcode = X86::CQO;
2648 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2649 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2650 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2653 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2654 // Special case for div8, just use a move with zero extension to AX to
2655 // clear the upper 8 bits (AH).
2656 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2657 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2658 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2660 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2661 MVT::Other, Ops), 0);
2662 Chain = Move.getValue(1);
2663 ReplaceUses(N0.getValue(1), Chain);
2666 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2667 Chain = CurDAG->getEntryNode();
2669 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2670 InFlag = Chain.getValue(1);
2673 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2674 LoReg, N0, SDValue()).getValue(1);
2675 if (isSigned && !signBitIsZero) {
2676 // Sign extend the low part into the high part.
2678 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2680 // Zero out the high part, effectively zero extending the input.
2681 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2682 switch (NVT.SimpleTy) {
2685 SDValue(CurDAG->getMachineNode(
2686 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2687 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2695 SDValue(CurDAG->getMachineNode(
2696 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2697 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2698 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2703 llvm_unreachable("Unexpected division source");
2706 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2707 ClrNode, InFlag).getValue(1);
2712 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2715 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2716 InFlag = SDValue(CNode, 1);
2717 // Update the chain.
2718 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2721 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2724 // Prevent use of AH in a REX instruction by explicitly copying it to
2725 // an ABCD_L register.
2727 // The current assumption of the register allocator is that isel
2728 // won't generate explicit references to the GR8_ABCD_H registers. If
2729 // the allocator and/or the backend get enhanced to be more robust in
2730 // that regard, this can be, and should be, removed.
2731 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2732 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2733 unsigned AHExtOpcode =
2734 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2736 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2737 MVT::Glue, AHCopy, InFlag);
2738 SDValue Result(RNode, 0);
2739 InFlag = SDValue(RNode, 1);
2741 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2742 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2743 if (Node->getValueType(1) == MVT::i64) {
2744 // It's not possible to directly movsx AH to a 64bit register, because
2745 // the latter needs the REX prefix, but the former can't have it.
2746 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2747 "Unexpected i64 sext of h-register");
2749 SDValue(CurDAG->getMachineNode(
2750 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2751 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2752 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2758 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2760 ReplaceUses(SDValue(Node, 1), Result);
2761 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2763 // Copy the division (low) result, if it is needed.
2764 if (!SDValue(Node, 0).use_empty()) {
2765 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2766 LoReg, NVT, InFlag);
2767 InFlag = Result.getValue(2);
2768 ReplaceUses(SDValue(Node, 0), Result);
2769 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2771 // Copy the remainder (high) result, if it is needed.
2772 if (!SDValue(Node, 1).use_empty()) {
2773 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2774 HiReg, NVT, InFlag);
2775 InFlag = Result.getValue(2);
2776 ReplaceUses(SDValue(Node, 1), Result);
2777 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2784 // Sometimes a SUB is used to perform comparison.
2785 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2786 // This node is not a CMP.
2788 SDValue N0 = Node->getOperand(0);
2789 SDValue N1 = Node->getOperand(1);
2791 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2792 HasNoSignedComparisonUses(Node))
2793 N0 = N0.getOperand(0);
2795 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2796 // use a smaller encoding.
2797 // Look past the truncate if CMP is the only use of it.
2798 if ((N0.getNode()->getOpcode() == ISD::AND ||
2799 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2800 N0.getNode()->hasOneUse() &&
2801 N0.getValueType() != MVT::i8 &&
2802 X86::isZeroNode(N1)) {
2803 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2806 // For example, convert "testl %eax, $8" to "testb %al, $8"
2807 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2808 (!(C->getZExtValue() & 0x80) ||
2809 HasNoSignedComparisonUses(Node))) {
2810 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2811 SDValue Reg = N0.getNode()->getOperand(0);
2813 // On x86-32, only the ABCD registers have 8-bit subregisters.
2814 if (!Subtarget->is64Bit()) {
2815 const TargetRegisterClass *TRC;
2816 switch (N0.getSimpleValueType().SimpleTy) {
2817 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2818 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2819 default: llvm_unreachable("Unsupported TEST operand type!");
2821 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2822 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2823 Reg.getValueType(), Reg, RC), 0);
2826 // Extract the l-register.
2827 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2831 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2833 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2834 // one, do not call ReplaceAllUsesWith.
2835 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2836 SDValue(NewNode, 0));
2840 // For example, "testl %eax, $2048" to "testb %ah, $8".
2841 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2842 (!(C->getZExtValue() & 0x8000) ||
2843 HasNoSignedComparisonUses(Node))) {
2844 // Shift the immediate right by 8 bits.
2845 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2847 SDValue Reg = N0.getNode()->getOperand(0);
2849 // Put the value in an ABCD register.
2850 const TargetRegisterClass *TRC;
2851 switch (N0.getSimpleValueType().SimpleTy) {
2852 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2853 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2854 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2855 default: llvm_unreachable("Unsupported TEST operand type!");
2857 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2858 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2859 Reg.getValueType(), Reg, RC), 0);
2861 // Extract the h-register.
2862 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2865 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2866 // target GR8_NOREX registers, so make sure the register class is
2868 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2869 MVT::i32, Subreg, ShiftedImm);
2870 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2871 // one, do not call ReplaceAllUsesWith.
2872 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2873 SDValue(NewNode, 0));
2877 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2878 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2879 N0.getValueType() != MVT::i16 &&
2880 (!(C->getZExtValue() & 0x8000) ||
2881 HasNoSignedComparisonUses(Node))) {
2882 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2884 SDValue Reg = N0.getNode()->getOperand(0);
2886 // Extract the 16-bit subregister.
2887 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2891 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2893 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2894 // one, do not call ReplaceAllUsesWith.
2895 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2896 SDValue(NewNode, 0));
2900 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2901 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2902 N0.getValueType() == MVT::i64 &&
2903 (!(C->getZExtValue() & 0x80000000) ||
2904 HasNoSignedComparisonUses(Node))) {
2905 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2907 SDValue Reg = N0.getNode()->getOperand(0);
2909 // Extract the 32-bit subregister.
2910 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2914 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2916 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2917 // one, do not call ReplaceAllUsesWith.
2918 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2919 SDValue(NewNode, 0));
2926 // Change a chain of {load; incr or dec; store} of the same value into
2927 // a simple increment or decrement through memory of that value, if the
2928 // uses of the modified value and its address are suitable.
2929 // The DEC64m tablegen pattern is currently not able to match the case where
2930 // the EFLAGS on the original DEC are used. (This also applies to
2931 // {INC,DEC}X{64,32,16,8}.)
2932 // We'll need to improve tablegen to allow flags to be transferred from a
2933 // node in the pattern to the result node. probably with a new keyword
2934 // for example, we have this
2935 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2936 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2937 // (implicit EFLAGS)]>;
2938 // but maybe need something like this
2939 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2940 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2941 // (transferrable EFLAGS)]>;
2943 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2944 SDValue StoredVal = StoreNode->getOperand(1);
2945 unsigned Opc = StoredVal->getOpcode();
2947 LoadSDNode *LoadNode = nullptr;
2949 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2950 LoadNode, InputChain))
2953 SDValue Base, Scale, Index, Disp, Segment;
2954 if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
2955 Base, Scale, Index, Disp, Segment))
2958 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2959 MemOp[0] = StoreNode->getMemOperand();
2960 MemOp[1] = LoadNode->getMemOperand();
2961 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2962 EVT LdVT = LoadNode->getMemoryVT();
2963 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2964 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2966 MVT::i32, MVT::Other, Ops);
2967 Result->setMemRefs(MemOp, MemOp + 2);
2969 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2970 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2976 SDNode *ResNode = SelectCode(Node);
2978 DEBUG(dbgs() << "=> ";
2979 if (ResNode == nullptr || ResNode == Node)
2982 ResNode->dump(CurDAG);
2988 bool X86DAGToDAGISel::
2989 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2990 std::vector<SDValue> &OutOps) {
2991 SDValue Op0, Op1, Op2, Op3, Op4;
2992 switch (ConstraintID) {
2994 llvm_unreachable("Unexpected asm memory constraint");
2995 case InlineAsm::Constraint_i:
2996 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2997 // be an immediate and not a memory constraint.
2999 case InlineAsm::Constraint_o: // offsetable ??
3000 case InlineAsm::Constraint_v: // not offsetable ??
3001 case InlineAsm::Constraint_m: // memory
3002 case InlineAsm::Constraint_X:
3003 if (!SelectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
3008 OutOps.push_back(Op0);
3009 OutOps.push_back(Op1);
3010 OutOps.push_back(Op2);
3011 OutOps.push_back(Op3);
3012 OutOps.push_back(Op4);
3016 /// createX86ISelDag - This pass converts a legalized DAG into a
3017 /// X86-specific DAG, ready for instruction scheduling.
3019 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
3020 CodeGenOpt::Level OptLevel) {
3021 return new X86DAGToDAGISel(TM, OptLevel);