1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source 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 "X86RegisterInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86ISelLowering.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/Statistic.h"
34 //===----------------------------------------------------------------------===//
35 // Pattern Matcher Implementation
36 //===----------------------------------------------------------------------===//
39 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
40 /// SDOperand's instead of register numbers for the leaves of the matched
42 struct X86ISelAddressMode {
49 struct { // This is really a union, discriminated by BaseType!
60 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0), GV(0) {
67 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
69 //===--------------------------------------------------------------------===//
70 /// ISel - X86 specific code to select X86 machine instructions for
71 /// SelectionDAG operations.
73 class X86DAGToDAGISel : public SelectionDAGISel {
74 /// ContainsFPCode - Every instruction we select that uses or defines a FP
75 /// register should set this to true.
78 /// X86Lowering - This object fully describes how to lower LLVM code to an
79 /// X86-specific SelectionDAG.
80 X86TargetLowering X86Lowering;
82 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
83 /// make the right decision when generating code for different targets.
84 const X86Subtarget *Subtarget;
86 X86DAGToDAGISel(TargetMachine &TM)
87 : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
88 Subtarget = &TM.getSubtarget<X86Subtarget>();
91 virtual const char *getPassName() const {
92 return "X86 DAG->DAG Instruction Selection";
95 /// InstructionSelectBasicBlock - This callback is invoked by
96 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
97 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
99 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
101 // Include the pieces autogenerated from the target description.
102 #include "X86GenDAGISel.inc"
105 SDOperand Select(SDOperand N);
107 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
108 bool SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
109 SDOperand &Index, SDOperand &Disp);
110 bool SelectLEAAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
111 SDOperand &Index, SDOperand &Disp);
112 bool TryFoldLoad(SDOperand N, SDOperand &Base, SDOperand &Scale,
113 SDOperand &Index, SDOperand &Disp);
115 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
116 SDOperand &Scale, SDOperand &Index,
118 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
119 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, MVT::i32) : AM.Base.Reg;
120 Scale = getI8Imm(AM.Scale);
122 Disp = AM.GV ? CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp)
123 : getI32Imm(AM.Disp);
126 /// getI8Imm - Return a target constant with the specified value, of type
128 inline SDOperand getI8Imm(unsigned Imm) {
129 return CurDAG->getTargetConstant(Imm, MVT::i8);
132 /// getI16Imm - Return a target constant with the specified value, of type
134 inline SDOperand getI16Imm(unsigned Imm) {
135 return CurDAG->getTargetConstant(Imm, MVT::i16);
138 /// getI32Imm - Return a target constant with the specified value, of type
140 inline SDOperand getI32Imm(unsigned Imm) {
141 return CurDAG->getTargetConstant(Imm, MVT::i32);
146 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
147 /// when it has created a SelectionDAG for us to codegen.
148 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
150 MachineFunction::iterator FirstMBB = BB;
152 // Codegen the basic block.
153 DAG.setRoot(Select(DAG.getRoot()));
155 DAG.RemoveDeadNodes();
157 // Emit machine code to BB.
158 ScheduleAndEmitDAG(DAG);
160 // If we are emitting FP stack code, scan the basic block to determine if this
161 // block defines any FP values. If so, put an FP_REG_KILL instruction before
162 // the terminator of the block.
163 if (X86Vector < SSE2) {
164 // Note that FP stack instructions *are* used in SSE code when returning
165 // values, but these are not live out of the basic block, so we don't need
166 // an FP_REG_KILL in this case either.
167 bool ContainsFPCode = false;
169 // Scan all of the machine instructions in these MBBs, checking for FP
171 MachineFunction::iterator MBBI = FirstMBB;
173 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
174 !ContainsFPCode && I != E; ++I) {
175 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
176 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
177 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
178 RegMap->getRegClass(I->getOperand(0).getReg()) ==
179 X86::RFPRegisterClass) {
180 ContainsFPCode = true;
185 } while (!ContainsFPCode && &*(MBBI++) != BB);
187 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
188 // a copy of the input value in this block.
189 if (!ContainsFPCode) {
190 // Final check, check LLVM BB's that are successors to the LLVM BB
191 // corresponding to BB for FP PHI nodes.
192 const BasicBlock *LLVMBB = BB->getBasicBlock();
194 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
195 !ContainsFPCode && SI != E; ++SI) {
196 for (BasicBlock::const_iterator II = SI->begin();
197 (PN = dyn_cast<PHINode>(II)); ++II) {
198 if (PN->getType()->isFloatingPoint()) {
199 ContainsFPCode = true;
206 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
207 if (ContainsFPCode) {
208 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
214 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
215 /// the main function.
216 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
217 MachineFrameInfo *MFI) {
219 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
220 int CWFrameIdx = MFI->CreateStackObject(2, 2);
221 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
223 // Set the high part to be 64-bit precision.
224 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
225 CWFrameIdx, 1).addImm(2);
227 // Reload the modified control word now.
228 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
232 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
233 // If this is main, emit special code for main.
234 MachineBasicBlock *BB = MF.begin();
235 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
236 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
239 /// MatchAddress - Add the specified node to the specified addressing mode,
240 /// returning true if it cannot be done. This just pattern matches for the
242 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
243 switch (N.getOpcode()) {
245 case ISD::FrameIndex:
246 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
247 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
248 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
253 case ISD::ConstantPool:
254 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
255 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N)) {
256 AM.BaseType = X86ISelAddressMode::ConstantPoolBase;
257 AM.Base.Reg = CurDAG->getTargetConstantPool(CP->get(), MVT::i32);
263 case ISD::GlobalAddress:
264 case ISD::TargetGlobalAddress:
266 AM.GV = cast<GlobalAddressSDNode>(N)->getGlobal();
272 AM.Disp += cast<ConstantSDNode>(N)->getValue();
276 if (AM.IndexReg.Val == 0 && AM.Scale == 1)
277 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
278 unsigned Val = CN->getValue();
279 if (Val == 1 || Val == 2 || Val == 3) {
281 SDOperand ShVal = N.Val->getOperand(0);
283 // Okay, we know that we have a scale by now. However, if the scaled
284 // value is an add of something and a constant, we can fold the
285 // constant into the disp field here.
286 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
287 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
288 AM.IndexReg = ShVal.Val->getOperand(0);
289 ConstantSDNode *AddVal =
290 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
291 AM.Disp += AddVal->getValue() << Val;
301 // X*[3,5,9] -> X+X*[2,4,8]
302 if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
303 AM.Base.Reg.Val == 0)
304 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
305 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
306 AM.Scale = unsigned(CN->getValue())-1;
308 SDOperand MulVal = N.Val->getOperand(0);
311 // Okay, we know that we have a scale by now. However, if the scaled
312 // value is an add of something and a constant, we can fold the
313 // constant into the disp field here.
314 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
315 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
316 Reg = MulVal.Val->getOperand(0);
317 ConstantSDNode *AddVal =
318 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
319 AM.Disp += AddVal->getValue() * CN->getValue();
321 Reg = N.Val->getOperand(0);
324 AM.IndexReg = AM.Base.Reg = Reg;
330 X86ISelAddressMode Backup = AM;
331 if (!MatchAddress(N.Val->getOperand(0), AM) &&
332 !MatchAddress(N.Val->getOperand(1), AM))
335 if (!MatchAddress(N.Val->getOperand(1), AM) &&
336 !MatchAddress(N.Val->getOperand(0), AM))
343 // Is the base register already occupied?
344 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
345 // If so, check to see if the scale index register is set.
346 if (AM.IndexReg.Val == 0) {
352 // Otherwise, we cannot select it.
356 // Default, generate it as a register.
357 AM.BaseType = X86ISelAddressMode::RegBase;
362 /// SelectAddr - returns true if it is able pattern match an addressing mode.
363 /// It returns the operands which make up the maximal addressing mode it can
364 /// match by reference.
365 bool X86DAGToDAGISel::SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
366 SDOperand &Index, SDOperand &Disp) {
367 X86ISelAddressMode AM;
368 if (MatchAddress(N, AM))
371 if (AM.BaseType == X86ISelAddressMode::RegBase) {
372 if (AM.Base.Reg.Val) {
373 if (AM.Base.Reg.getOpcode() != ISD::Register)
374 AM.Base.Reg = Select(AM.Base.Reg);
376 AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
381 AM.IndexReg = Select(AM.IndexReg);
383 AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
385 getAddressOperands(AM, Base, Scale, Index, Disp);
389 bool X86DAGToDAGISel::TryFoldLoad(SDOperand N, SDOperand &Base,
390 SDOperand &Scale, SDOperand &Index,
392 if (N.getOpcode() == ISD::LOAD && N.hasOneUse() &&
393 CodeGenMap.count(N.getValue(1)) == 0)
394 return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp);
398 static bool isRegister0(SDOperand Op) {
399 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op))
400 return (R->getReg() == 0);
404 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
405 /// mode it matches can be cost effectively emitted as an LEA instruction.
406 /// For X86, it always is unless it's just a (Reg + const).
407 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand N, SDOperand &Base,
409 SDOperand &Index, SDOperand &Disp) {
410 X86ISelAddressMode AM;
411 if (!MatchAddress(N, AM)) {
412 bool SelectBase = false;
413 bool SelectIndex = false;
415 if (AM.BaseType == X86ISelAddressMode::RegBase) {
416 if (AM.Base.Reg.Val) {
420 AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
424 if (AM.IndexReg.Val) {
427 AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
431 unsigned Complexity = 0;
438 else if (AM.Disp > 1)
445 AM.Base.Reg = Select(AM.Base.Reg);
447 AM.IndexReg = Select(AM.IndexReg);
449 getAddressOperands(AM, Base, Scale, Index, Disp);
455 SDOperand X86DAGToDAGISel::Select(SDOperand N) {
456 SDNode *Node = N.Val;
457 MVT::ValueType NVT = Node->getValueType(0);
459 unsigned Opcode = Node->getOpcode();
461 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER)
462 return N; // Already selected.
464 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);
465 if (CGMI != CodeGenMap.end()) return CGMI->second;
471 if (Opcode == ISD::MULHU)
473 default: assert(0 && "Unsupported VT!");
474 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
475 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
476 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
480 default: assert(0 && "Unsupported VT!");
481 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
482 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
483 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
486 unsigned LoReg, HiReg;
488 default: assert(0 && "Unsupported VT!");
489 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
490 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
491 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
494 SDOperand N0 = Node->getOperand(0);
495 SDOperand N1 = Node->getOperand(1);
497 bool foldedLoad = false;
498 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
499 foldedLoad = TryFoldLoad(N1, Tmp0, Tmp1, Tmp2, Tmp3);
500 // MULHU and MULHS are commmutative
502 foldedLoad = TryFoldLoad(N0, Tmp0, Tmp1, Tmp2, Tmp3);
504 N0 = Node->getOperand(1);
505 N1 = Node->getOperand(0);
509 SDOperand Chain = foldedLoad ? Select(N1.getOperand(0))
510 : CurDAG->getEntryNode();
513 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
515 InFlag = Chain.getValue(1);
518 Chain = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
519 Tmp2, Tmp3, Chain, InFlag);
520 InFlag = Chain.getValue(1);
522 InFlag = CurDAG->getTargetNode(Opc, MVT::Flag, Select(N1), InFlag);
525 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
526 CodeGenMap[N.getValue(0)] = Result;
528 CodeGenMap[N1.getValue(1)] = Result.getValue(1);
536 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
537 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
540 default: assert(0 && "Unsupported VT!");
541 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
542 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
543 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
547 default: assert(0 && "Unsupported VT!");
548 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
549 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
550 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
553 unsigned LoReg, HiReg;
554 unsigned ClrOpcode, SExtOpcode;
556 default: assert(0 && "Unsupported VT!");
558 LoReg = X86::AL; HiReg = X86::AH;
559 ClrOpcode = X86::MOV8ri;
560 SExtOpcode = X86::CBW;
563 LoReg = X86::AX; HiReg = X86::DX;
564 ClrOpcode = X86::MOV16ri;
565 SExtOpcode = X86::CWD;
568 LoReg = X86::EAX; HiReg = X86::EDX;
569 ClrOpcode = X86::MOV32ri;
570 SExtOpcode = X86::CDQ;
574 SDOperand N0 = Node->getOperand(0);
575 SDOperand N1 = Node->getOperand(1);
577 bool foldedLoad = false;
578 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
579 foldedLoad = TryFoldLoad(N1, Tmp0, Tmp1, Tmp2, Tmp3);
580 SDOperand Chain = foldedLoad ? Select(N1.getOperand(0))
581 : CurDAG->getEntryNode();
584 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
586 InFlag = Chain.getValue(1);
589 // Sign extend the low part into the high part.
590 InFlag = CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag);
592 // Zero out the high part, effectively zero extending the input.
594 CurDAG->getTargetNode(ClrOpcode, NVT,
595 CurDAG->getTargetConstant(0, NVT));
596 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
598 InFlag = Chain.getValue(1);
602 Chain = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
603 Tmp2, Tmp3, Chain, InFlag);
604 InFlag = Chain.getValue(1);
606 InFlag = CurDAG->getTargetNode(Opc, MVT::Flag, Select(N1), InFlag);
609 SDOperand Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
611 CodeGenMap[N.getValue(0)] = Result;
613 CodeGenMap[N1.getValue(1)] = Result.getValue(1);
617 case ISD::TRUNCATE: {
620 switch (Node->getOperand(0).getValueType()) {
621 default: assert(0 && "Unknown truncate!");
622 case MVT::i16: Reg = X86::AX; Opc = X86::MOV16rr; VT = MVT::i16; break;
623 case MVT::i32: Reg = X86::EAX; Opc = X86::MOV32rr; VT = MVT::i32; break;
625 SDOperand Tmp0 = Select(Node->getOperand(0));
626 SDOperand Tmp1 = CurDAG->getTargetNode(Opc, VT, Tmp0);
627 SDOperand InFlag = SDOperand(0,0);
628 SDOperand Result = CurDAG->getCopyToReg(CurDAG->getEntryNode(),
630 SDOperand Chain = Result.getValue(0);
631 InFlag = Result.getValue(1);
634 default: assert(0 && "Unknown truncate!");
635 case MVT::i8: Reg = X86::AL; Opc = X86::MOV8rr; VT = MVT::i8; break;
636 case MVT::i16: Reg = X86::AX; Opc = X86::MOV16rr; VT = MVT::i16; break;
639 Result = CurDAG->getCopyFromReg(Chain,
641 if (N.Val->hasOneUse())
642 return CurDAG->SelectNodeTo(N.Val, Opc, VT, Result);
644 return CodeGenMap[N] = CurDAG->getTargetNode(Opc, VT, Result);
649 return SelectCode(N);
652 /// createX86ISelDag - This pass converts a legalized DAG into a
653 /// X86-specific DAG, ready for instruction scheduling.
655 FunctionPass *llvm::createX86ISelDag(TargetMachine &TM) {
656 return new X86DAGToDAGISel(TM);