blob: 97da290ffc90545da558b8eae2b8b3c7a8acfc58 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a DAG pattern matching instruction selector for X86,
11// converting from a legalized dag to a X86 dag.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86.h"
17#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
19#include "X86RegisterInfo.h"
20#include "X86Subtarget.h"
21#include "X86TargetMachine.h"
22#include "llvm/GlobalValue.h"
23#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/Support/CFG.h"
26#include "llvm/Type.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/SSARegMap.h"
32#include "llvm/CodeGen/SelectionDAGISel.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/ADT/Statistic.h"
38#include <queue>
39#include <set>
40using namespace llvm;
41
42STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
43STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
44
45
46//===----------------------------------------------------------------------===//
47// Pattern Matcher Implementation
48//===----------------------------------------------------------------------===//
49
50namespace {
51 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52 /// SDOperand's instead of register numbers for the leaves of the matched
53 /// tree.
54 struct X86ISelAddressMode {
55 enum {
56 RegBase,
57 FrameIndexBase
58 } BaseType;
59
60 struct { // This is really a union, discriminated by BaseType!
61 SDOperand Reg;
62 int FrameIndex;
63 } Base;
64
65 bool isRIPRel; // RIP relative?
66 unsigned Scale;
67 SDOperand IndexReg;
68 unsigned Disp;
69 GlobalValue *GV;
70 Constant *CP;
71 const char *ES;
72 int JT;
73 unsigned Align; // CP alignment.
74
75 X86ISelAddressMode()
76 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
77 GV(0), CP(0), ES(0), JT(-1), Align(0) {
78 }
79 };
80}
81
82namespace {
83 //===--------------------------------------------------------------------===//
84 /// ISel - X86 specific code to select X86 machine instructions for
85 /// SelectionDAG operations.
86 ///
87 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
88 /// ContainsFPCode - Every instruction we select that uses or defines a FP
89 /// register should set this to true.
90 bool ContainsFPCode;
91
92 /// FastISel - Enable fast(er) instruction selection.
93 ///
94 bool FastISel;
95
96 /// TM - Keep a reference to X86TargetMachine.
97 ///
98 X86TargetMachine &TM;
99
100 /// X86Lowering - This object fully describes how to lower LLVM code to an
101 /// X86-specific SelectionDAG.
102 X86TargetLowering X86Lowering;
103
104 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
105 /// make the right decision when generating code for different targets.
106 const X86Subtarget *Subtarget;
107
108 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
109 /// base register.
110 unsigned GlobalBaseReg;
111
112 public:
113 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
114 : SelectionDAGISel(X86Lowering),
115 ContainsFPCode(false), FastISel(fast), TM(tm),
116 X86Lowering(*TM.getTargetLowering()),
117 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
118
119 virtual bool runOnFunction(Function &Fn) {
120 // Make sure we re-emit a set of the global base reg if necessary
121 GlobalBaseReg = 0;
122 return SelectionDAGISel::runOnFunction(Fn);
123 }
124
125 virtual const char *getPassName() const {
126 return "X86 DAG->DAG Instruction Selection";
127 }
128
129 /// InstructionSelectBasicBlock - This callback is invoked by
130 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
131 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
132
133 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
134
Dan Gohmand6098272007-07-24 23:00:27 +0000135 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137// Include the pieces autogenerated from the target description.
138#include "X86GenDAGISel.inc"
139
140 private:
141 SDNode *Select(SDOperand N);
142
143 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
144 bool isRoot = true, unsigned Depth = 0);
145 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
146 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
147 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
148 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
149 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
150 SDOperand N, SDOperand &Base, SDOperand &Scale,
151 SDOperand &Index, SDOperand &Disp,
152 SDOperand &InChain, SDOperand &OutChain);
153 bool TryFoldLoad(SDOperand P, SDOperand N,
154 SDOperand &Base, SDOperand &Scale,
155 SDOperand &Index, SDOperand &Disp);
156 void InstructionSelectPreprocess(SelectionDAG &DAG);
157
158 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
159 /// inline asm expressions.
160 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
161 char ConstraintCode,
162 std::vector<SDOperand> &OutOps,
163 SelectionDAG &DAG);
164
165 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
166
167 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
168 SDOperand &Scale, SDOperand &Index,
169 SDOperand &Disp) {
170 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
171 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
172 AM.Base.Reg;
173 Scale = getI8Imm(AM.Scale);
174 Index = AM.IndexReg;
175 // These are 32-bit even in 64-bit mode since RIP relative offset
176 // is 32-bit.
177 if (AM.GV)
178 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
179 else if (AM.CP)
180 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
181 else if (AM.ES)
182 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
183 else if (AM.JT != -1)
184 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
185 else
186 Disp = getI32Imm(AM.Disp);
187 }
188
189 /// getI8Imm - Return a target constant with the specified value, of type
190 /// i8.
191 inline SDOperand getI8Imm(unsigned Imm) {
192 return CurDAG->getTargetConstant(Imm, MVT::i8);
193 }
194
195 /// getI16Imm - Return a target constant with the specified value, of type
196 /// i16.
197 inline SDOperand getI16Imm(unsigned Imm) {
198 return CurDAG->getTargetConstant(Imm, MVT::i16);
199 }
200
201 /// getI32Imm - Return a target constant with the specified value, of type
202 /// i32.
203 inline SDOperand getI32Imm(unsigned Imm) {
204 return CurDAG->getTargetConstant(Imm, MVT::i32);
205 }
206
207 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
208 /// base register. Return the virtual register that holds this value.
209 SDNode *getGlobalBaseReg();
210
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000211 /// getTruncate - return an SDNode that implements a subreg based truncate
212 /// of the specified operand to the the specified value type.
213 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
214
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215#ifndef NDEBUG
216 unsigned Indent;
217#endif
218 };
219}
220
221static SDNode *findFlagUse(SDNode *N) {
222 unsigned FlagResNo = N->getNumValues()-1;
223 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
224 SDNode *User = *I;
225 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
226 SDOperand Op = User->getOperand(i);
227 if (Op.Val == N && Op.ResNo == FlagResNo)
228 return User;
229 }
230 }
231 return NULL;
232}
233
234static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
235 SDNode *Root, SDNode *Skip, bool &found,
236 std::set<SDNode *> &Visited) {
237 if (found ||
238 Use->getNodeId() > Def->getNodeId() ||
239 !Visited.insert(Use).second)
240 return;
241
242 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
243 SDNode *N = Use->getOperand(i).Val;
244 if (N == Skip)
245 continue;
246 if (N == Def) {
247 if (Use == ImmedUse)
248 continue; // Immediate use is ok.
249 if (Use == Root) {
250 assert(Use->getOpcode() == ISD::STORE ||
251 Use->getOpcode() == X86ISD::CMP);
252 continue;
253 }
254 found = true;
255 break;
256 }
257 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
258 }
259}
260
261/// isNonImmUse - Start searching from Root up the DAG to check is Def can
262/// be reached. Return true if that's the case. However, ignore direct uses
263/// by ImmedUse (which would be U in the example illustrated in
264/// CanBeFoldedBy) and by Root (which can happen in the store case).
265/// FIXME: to be really generic, we should allow direct use by any node
266/// that is being folded. But realisticly since we only fold loads which
267/// have one non-chain use, we only need to watch out for load/op/store
268/// and load/op/cmp case where the root (store / cmp) may reach the load via
269/// its chain operand.
270static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
271 SDNode *Skip = NULL) {
272 std::set<SDNode *> Visited;
273 bool found = false;
274 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
275 return found;
276}
277
278
Dan Gohmand6098272007-07-24 23:00:27 +0000279bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 if (FastISel) return false;
281
282 // If U use can somehow reach N through another path then U can't fold N or
283 // it will create a cycle. e.g. In the following diagram, U can reach N
284 // through X. If N is folded into into U, then X is both a predecessor and
285 // a successor of U.
286 //
287 // [ N ]
288 // ^ ^
289 // | |
290 // / \---
291 // / [X]
292 // | ^
293 // [U]--------|
294
295 if (isNonImmUse(Root, N, U))
296 return false;
297
298 // If U produces a flag, then it gets (even more) interesting. Since it
299 // would have been "glued" together with its flag use, we need to check if
300 // it might reach N:
301 //
302 // [ N ]
303 // ^ ^
304 // | |
305 // [U] \--
306 // ^ [TF]
307 // | ^
308 // | |
309 // \ /
310 // [FU]
311 //
312 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
313 // NU), then TF is a predecessor of FU and a successor of NU. But since
314 // NU and FU are flagged together, this effectively creates a cycle.
315 bool HasFlagUse = false;
316 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
317 while ((VT == MVT::Flag && !Root->use_empty())) {
318 SDNode *FU = findFlagUse(Root);
319 if (FU == NULL)
320 break;
321 else {
322 Root = FU;
323 HasFlagUse = true;
324 }
325 VT = Root->getValueType(Root->getNumValues()-1);
326 }
327
328 if (HasFlagUse)
329 return !isNonImmUse(Root, N, Root, U);
330 return true;
331}
332
333/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
334/// and move load below the TokenFactor. Replace store's chain operand with
335/// load's chain result.
336static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
337 SDOperand Store, SDOperand TF) {
338 std::vector<SDOperand> Ops;
339 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
340 if (Load.Val == TF.Val->getOperand(i).Val)
341 Ops.push_back(Load.Val->getOperand(0));
342 else
343 Ops.push_back(TF.Val->getOperand(i));
344 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
345 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
346 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
347 Store.getOperand(2), Store.getOperand(3));
348}
349
350/// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
351/// selector to pick more load-modify-store instructions. This is a common
352/// case:
353///
354/// [Load chain]
355/// ^
356/// |
357/// [Load]
358/// ^ ^
359/// | |
360/// / \-
361/// / |
362/// [TokenFactor] [Op]
363/// ^ ^
364/// | |
365/// \ /
366/// \ /
367/// [Store]
368///
369/// The fact the store's chain operand != load's chain will prevent the
370/// (store (op (load))) instruction from being selected. We can transform it to:
371///
372/// [Load chain]
373/// ^
374/// |
375/// [TokenFactor]
376/// ^
377/// |
378/// [Load]
379/// ^ ^
380/// | |
381/// | \-
382/// | |
383/// | [Op]
384/// | ^
385/// | |
386/// \ /
387/// \ /
388/// [Store]
389void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
390 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
391 E = DAG.allnodes_end(); I != E; ++I) {
392 if (!ISD::isNON_TRUNCStore(I))
393 continue;
394 SDOperand Chain = I->getOperand(0);
395 if (Chain.Val->getOpcode() != ISD::TokenFactor)
396 continue;
397
398 SDOperand N1 = I->getOperand(1);
399 SDOperand N2 = I->getOperand(2);
400 if (MVT::isFloatingPoint(N1.getValueType()) ||
401 MVT::isVector(N1.getValueType()) ||
402 !N1.hasOneUse())
403 continue;
404
405 bool RModW = false;
406 SDOperand Load;
407 unsigned Opcode = N1.Val->getOpcode();
408 switch (Opcode) {
409 case ISD::ADD:
410 case ISD::MUL:
411 case ISD::AND:
412 case ISD::OR:
413 case ISD::XOR:
414 case ISD::ADDC:
415 case ISD::ADDE: {
416 SDOperand N10 = N1.getOperand(0);
417 SDOperand N11 = N1.getOperand(1);
418 if (ISD::isNON_EXTLoad(N10.Val))
419 RModW = true;
420 else if (ISD::isNON_EXTLoad(N11.Val)) {
421 RModW = true;
422 std::swap(N10, N11);
423 }
424 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
425 (N10.getOperand(1) == N2) &&
426 (N10.Val->getValueType(0) == N1.getValueType());
427 if (RModW)
428 Load = N10;
429 break;
430 }
431 case ISD::SUB:
432 case ISD::SHL:
433 case ISD::SRA:
434 case ISD::SRL:
435 case ISD::ROTL:
436 case ISD::ROTR:
437 case ISD::SUBC:
438 case ISD::SUBE:
439 case X86ISD::SHLD:
440 case X86ISD::SHRD: {
441 SDOperand N10 = N1.getOperand(0);
442 if (ISD::isNON_EXTLoad(N10.Val))
443 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
444 (N10.getOperand(1) == N2) &&
445 (N10.Val->getValueType(0) == N1.getValueType());
446 if (RModW)
447 Load = N10;
448 break;
449 }
450 }
451
452 if (RModW) {
453 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
454 ++NumLoadMoved;
455 }
456 }
457}
458
459/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
460/// when it has created a SelectionDAG for us to codegen.
461void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
462 DEBUG(BB->dump());
463 MachineFunction::iterator FirstMBB = BB;
464
465 if (!FastISel)
466 InstructionSelectPreprocess(DAG);
467
468 // Codegen the basic block.
469#ifndef NDEBUG
470 DOUT << "===== Instruction selection begins:\n";
471 Indent = 0;
472#endif
473 DAG.setRoot(SelectRoot(DAG.getRoot()));
474#ifndef NDEBUG
475 DOUT << "===== Instruction selection ends:\n";
476#endif
477
478 DAG.RemoveDeadNodes();
479
480 // Emit machine code to BB.
481 ScheduleAndEmitDAG(DAG);
482
483 // If we are emitting FP stack code, scan the basic block to determine if this
484 // block defines any FP values. If so, put an FP_REG_KILL instruction before
485 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000486
487 // Note that FP stack instructions *are* used in SSE code for long double,
488 // so we do need this check.
489 bool ContainsFPCode = false;
490
491 // Scan all of the machine instructions in these MBBs, checking for FP
492 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
493 MachineFunction::iterator MBBI = FirstMBB;
494 do {
495 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
496 !ContainsFPCode && I != E; ++I) {
497 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
498 const TargetRegisterClass *clas;
499 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
500 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
501 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
502 ((clas = RegMap->getRegClass(I->getOperand(0).getReg())) ==
503 X86::RFP32RegisterClass ||
504 clas == X86::RFP64RegisterClass ||
505 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 ContainsFPCode = true;
507 break;
508 }
509 }
510 }
511 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000512 } while (!ContainsFPCode && &*(MBBI++) != BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000514 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
515 // a copy of the input value in this block. In SSE mode, we only care about
516 // 80-bit values.
517 if (!ContainsFPCode) {
518 // Final check, check LLVM BB's that are successors to the LLVM BB
519 // corresponding to BB for FP PHI nodes.
520 const BasicBlock *LLVMBB = BB->getBasicBlock();
521 const PHINode *PN;
522 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
523 !ContainsFPCode && SI != E; ++SI) {
524 for (BasicBlock::const_iterator II = SI->begin();
525 (PN = dyn_cast<PHINode>(II)); ++II) {
526 if (PN->getType()==Type::X86_FP80Ty ||
527 (!Subtarget->hasSSE2() && PN->getType()->isFloatingPoint())) {
528 ContainsFPCode = true;
529 break;
530 }
531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 }
533 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000534
535 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
536 if (ContainsFPCode) {
537 BuildMI(*BB, BB->getFirstTerminator(),
538 TM.getInstrInfo()->get(X86::FP_REG_KILL));
539 ++NumFPKill;
540 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541}
542
543/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
544/// the main function.
545void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
546 MachineFrameInfo *MFI) {
547 const TargetInstrInfo *TII = TM.getInstrInfo();
548 if (Subtarget->isTargetCygMing())
549 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
550
551 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
552 int CWFrameIdx = MFI->CreateStackObject(2, 2);
553 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
554
555 // Set the high part to be 64-bit precision.
556 addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
557 CWFrameIdx, 1).addImm(2);
558
559 // Reload the modified control word now.
560 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
561}
562
563void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
564 // If this is main, emit special code for main.
565 MachineBasicBlock *BB = MF.begin();
566 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
567 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
568}
569
570/// MatchAddress - Add the specified node to the specified addressing mode,
571/// returning true if it cannot be done. This just pattern matches for the
572/// addressing mode
573bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
574 bool isRoot, unsigned Depth) {
575 if (Depth > 5) {
576 // Default, generate it as a register.
577 AM.BaseType = X86ISelAddressMode::RegBase;
578 AM.Base.Reg = N;
579 return false;
580 }
581
582 // RIP relative addressing: %rip + 32-bit displacement!
583 if (AM.isRIPRel) {
584 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
585 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
586 if (isInt32(AM.Disp + Val)) {
587 AM.Disp += Val;
588 return false;
589 }
590 }
591 return true;
592 }
593
594 int id = N.Val->getNodeId();
595 bool Available = isSelected(id);
596
597 switch (N.getOpcode()) {
598 default: break;
599 case ISD::Constant: {
600 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
601 if (isInt32(AM.Disp + Val)) {
602 AM.Disp += Val;
603 return false;
604 }
605 break;
606 }
607
608 case X86ISD::Wrapper: {
609 bool is64Bit = Subtarget->is64Bit();
610 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
611 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
612 break;
613 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
614 break;
615 // If value is available in a register both base and index components have
616 // been picked, we can't fit the result available in the register in the
617 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
618 if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
619 bool isStatic = TM.getRelocationModel() == Reloc::Static;
620 SDOperand N0 = N.getOperand(0);
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000621 // Mac OS X X86-64 lower 4G address is not available.
Evan Cheng09e13792007-08-01 23:45:51 +0000622 bool isAbs32 = !is64Bit ||
623 (isStatic && Subtarget->hasLow4GUserSpaceAddress());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
625 GlobalValue *GV = G->getGlobal();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 if (isAbs32 || isRoot) {
627 AM.GV = GV;
628 AM.Disp += G->getOffset();
629 AM.isRIPRel = !isAbs32;
630 return false;
631 }
632 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000633 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 AM.CP = CP->getConstVal();
635 AM.Align = CP->getAlignment();
636 AM.Disp += CP->getOffset();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000637 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 return false;
639 }
640 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000641 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 AM.ES = S->getSymbol();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000643 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 return false;
645 }
646 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000647 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 AM.JT = J->getIndex();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000649 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 return false;
651 }
652 }
653 }
654 break;
655 }
656
657 case ISD::FrameIndex:
658 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
659 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
660 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
661 return false;
662 }
663 break;
664
665 case ISD::SHL:
666 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
667 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
668 unsigned Val = CN->getValue();
669 if (Val == 1 || Val == 2 || Val == 3) {
670 AM.Scale = 1 << Val;
671 SDOperand ShVal = N.Val->getOperand(0);
672
673 // Okay, we know that we have a scale by now. However, if the scaled
674 // value is an add of something and a constant, we can fold the
675 // constant into the disp field here.
676 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
677 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
678 AM.IndexReg = ShVal.Val->getOperand(0);
679 ConstantSDNode *AddVal =
680 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
681 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
682 if (isInt32(Disp))
683 AM.Disp = Disp;
684 else
685 AM.IndexReg = ShVal;
686 } else {
687 AM.IndexReg = ShVal;
688 }
689 return false;
690 }
691 }
692 break;
693
694 case ISD::MUL:
695 // X*[3,5,9] -> X+X*[2,4,8]
696 if (!Available &&
697 AM.BaseType == X86ISelAddressMode::RegBase &&
698 AM.Base.Reg.Val == 0 &&
699 AM.IndexReg.Val == 0) {
700 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
701 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
702 AM.Scale = unsigned(CN->getValue())-1;
703
704 SDOperand MulVal = N.Val->getOperand(0);
705 SDOperand Reg;
706
707 // Okay, we know that we have a scale by now. However, if the scaled
708 // value is an add of something and a constant, we can fold the
709 // constant into the disp field here.
710 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
711 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
712 Reg = MulVal.Val->getOperand(0);
713 ConstantSDNode *AddVal =
714 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
715 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
716 if (isInt32(Disp))
717 AM.Disp = Disp;
718 else
719 Reg = N.Val->getOperand(0);
720 } else {
721 Reg = N.Val->getOperand(0);
722 }
723
724 AM.IndexReg = AM.Base.Reg = Reg;
725 return false;
726 }
727 }
728 break;
729
730 case ISD::ADD:
731 if (!Available) {
732 X86ISelAddressMode Backup = AM;
733 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
734 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
735 return false;
736 AM = Backup;
737 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
738 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
739 return false;
740 AM = Backup;
741 }
742 break;
743
744 case ISD::OR:
745 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
746 if (!Available) {
747 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
748 X86ISelAddressMode Backup = AM;
749 // Start with the LHS as an addr mode.
750 if (!MatchAddress(N.getOperand(0), AM, false) &&
751 // Address could not have picked a GV address for the displacement.
752 AM.GV == NULL &&
753 // On x86-64, the resultant disp must fit in 32-bits.
754 isInt32(AM.Disp + CN->getSignExtended()) &&
755 // Check to see if the LHS & C is zero.
756 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
757 AM.Disp += CN->getValue();
758 return false;
759 }
760 AM = Backup;
761 }
762 }
763 break;
764 }
765
766 // Is the base register already occupied?
767 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
768 // If so, check to see if the scale index register is set.
769 if (AM.IndexReg.Val == 0) {
770 AM.IndexReg = N;
771 AM.Scale = 1;
772 return false;
773 }
774
775 // Otherwise, we cannot select it.
776 return true;
777 }
778
779 // Default, generate it as a register.
780 AM.BaseType = X86ISelAddressMode::RegBase;
781 AM.Base.Reg = N;
782 return false;
783}
784
785/// SelectAddr - returns true if it is able pattern match an addressing mode.
786/// It returns the operands which make up the maximal addressing mode it can
787/// match by reference.
788bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
789 SDOperand &Scale, SDOperand &Index,
790 SDOperand &Disp) {
791 X86ISelAddressMode AM;
792 if (MatchAddress(N, AM))
793 return false;
794
795 MVT::ValueType VT = N.getValueType();
796 if (AM.BaseType == X86ISelAddressMode::RegBase) {
797 if (!AM.Base.Reg.Val)
798 AM.Base.Reg = CurDAG->getRegister(0, VT);
799 }
800
801 if (!AM.IndexReg.Val)
802 AM.IndexReg = CurDAG->getRegister(0, VT);
803
804 getAddressOperands(AM, Base, Scale, Index, Disp);
805 return true;
806}
807
808/// isZeroNode - Returns true if Elt is a constant zero or a floating point
809/// constant +0.0.
810static inline bool isZeroNode(SDOperand Elt) {
811 return ((isa<ConstantSDNode>(Elt) &&
812 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
813 (isa<ConstantFPSDNode>(Elt) &&
814 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
815}
816
817
818/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
819/// match a load whose top elements are either undef or zeros. The load flavor
820/// is derived from the type of N, which is either v4f32 or v2f64.
821bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
822 SDOperand N, SDOperand &Base,
823 SDOperand &Scale, SDOperand &Index,
824 SDOperand &Disp, SDOperand &InChain,
825 SDOperand &OutChain) {
826 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
827 InChain = N.getOperand(0).getValue(1);
828 if (ISD::isNON_EXTLoad(InChain.Val) &&
829 InChain.getValue(0).hasOneUse() &&
830 N.hasOneUse() &&
831 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
832 LoadSDNode *LD = cast<LoadSDNode>(InChain);
833 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
834 return false;
835 OutChain = LD->getChain();
836 return true;
837 }
838 }
839
840 // Also handle the case where we explicitly require zeros in the top
841 // elements. This is a vector shuffle from the zero vector.
842 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
843 N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
844 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
845 N.getOperand(1).Val->hasOneUse() &&
846 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
847 N.getOperand(1).getOperand(0).hasOneUse()) {
848 // Check to see if the BUILD_VECTOR is building a zero vector.
849 SDOperand BV = N.getOperand(0);
850 for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
851 if (!isZeroNode(BV.getOperand(i)) &&
852 BV.getOperand(i).getOpcode() != ISD::UNDEF)
853 return false; // Not a zero/undef vector.
854 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
855 // from the LHS.
856 unsigned VecWidth = BV.getNumOperands();
857 SDOperand ShufMask = N.getOperand(2);
858 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
860 if (C->getValue() == VecWidth) {
861 for (unsigned i = 1; i != VecWidth; ++i) {
862 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
863 // ok.
864 } else {
865 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
866 if (C->getValue() >= VecWidth) return false;
867 }
868 }
869 }
870
871 // Okay, this is a zero extending load. Fold it.
872 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
873 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
874 return false;
875 OutChain = LD->getChain();
876 InChain = SDOperand(LD, 1);
877 return true;
878 }
879 }
880 return false;
881}
882
883
884/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
885/// mode it matches can be cost effectively emitted as an LEA instruction.
886bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
887 SDOperand &Base, SDOperand &Scale,
888 SDOperand &Index, SDOperand &Disp) {
889 X86ISelAddressMode AM;
890 if (MatchAddress(N, AM))
891 return false;
892
893 MVT::ValueType VT = N.getValueType();
894 unsigned Complexity = 0;
895 if (AM.BaseType == X86ISelAddressMode::RegBase)
896 if (AM.Base.Reg.Val)
897 Complexity = 1;
898 else
899 AM.Base.Reg = CurDAG->getRegister(0, VT);
900 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
901 Complexity = 4;
902
903 if (AM.IndexReg.Val)
904 Complexity++;
905 else
906 AM.IndexReg = CurDAG->getRegister(0, VT);
907
908 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
909 // a simple shift.
910 if (AM.Scale > 1)
911 Complexity++;
912
913 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
914 // to a LEA. This is determined with some expermentation but is by no means
915 // optimal (especially for code size consideration). LEA is nice because of
916 // its three-address nature. Tweak the cost function again when we can run
917 // convertToThreeAddress() at register allocation time.
918 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
919 // For X86-64, we should always use lea to materialize RIP relative
920 // addresses.
921 if (Subtarget->is64Bit())
922 Complexity = 4;
923 else
924 Complexity += 2;
925 }
926
927 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
928 Complexity++;
929
930 if (Complexity > 2) {
931 getAddressOperands(AM, Base, Scale, Index, Disp);
932 return true;
933 }
934 return false;
935}
936
937bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
938 SDOperand &Base, SDOperand &Scale,
939 SDOperand &Index, SDOperand &Disp) {
940 if (ISD::isNON_EXTLoad(N.Val) &&
941 N.hasOneUse() &&
942 CanBeFoldedBy(N.Val, P.Val, P.Val))
943 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
944 return false;
945}
946
947/// getGlobalBaseReg - Output the instructions required to put the
948/// base address to use for accessing globals into a register.
949///
950SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
951 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
952 if (!GlobalBaseReg) {
953 // Insert the set of GlobalBaseReg into the first MBB of the function
954 MachineBasicBlock &FirstMBB = BB->getParent()->front();
955 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
956 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
957 unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
958
959 const TargetInstrInfo *TII = TM.getInstrInfo();
960 BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
961 BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
962
963 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
964 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
965 if (TM.getRelocationModel() == Reloc::PIC_ &&
966 Subtarget->isPICStyleGOT()) {
967 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
968 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
969 addReg(PC).
970 addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
971 } else {
972 GlobalBaseReg = PC;
973 }
974
975 }
976 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
977}
978
979static SDNode *FindCallStartFromCall(SDNode *Node) {
980 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
981 assert(Node->getOperand(0).getValueType() == MVT::Other &&
982 "Node doesn't have a token chain argument!");
983 return FindCallStartFromCall(Node->getOperand(0).Val);
984}
985
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000986SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
987 SDOperand SRIdx;
988 switch (VT) {
989 case MVT::i8:
990 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
991 // Ensure that the source register has an 8-bit subreg on 32-bit targets
992 if (!Subtarget->is64Bit()) {
993 unsigned Opc;
994 MVT::ValueType VT;
995 switch (N0.getValueType()) {
996 default: assert(0 && "Unknown truncate!");
997 case MVT::i16:
998 Opc = X86::MOV16to16_;
999 VT = MVT::i16;
1000 break;
1001 case MVT::i32:
1002 Opc = X86::MOV32to32_;
1003 VT = MVT::i32;
1004 break;
1005 }
1006 N0 =
1007 SDOperand(CurDAG->getTargetNode(Opc, VT, N0), 0);
1008 }
1009 break;
1010 case MVT::i16:
1011 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1012 break;
1013 case MVT::i32:
1014 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1015 break;
1016 default: assert(0 && "Unknown truncate!");
1017 }
1018 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1019 VT,
1020 N0, SRIdx);
1021}
1022
1023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1025 SDNode *Node = N.Val;
1026 MVT::ValueType NVT = Node->getValueType(0);
1027 unsigned Opc, MOpc;
1028 unsigned Opcode = Node->getOpcode();
1029
1030#ifndef NDEBUG
1031 DOUT << std::string(Indent, ' ') << "Selecting: ";
1032 DEBUG(Node->dump(CurDAG));
1033 DOUT << "\n";
1034 Indent += 2;
1035#endif
1036
1037 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1038#ifndef NDEBUG
1039 DOUT << std::string(Indent-2, ' ') << "== ";
1040 DEBUG(Node->dump(CurDAG));
1041 DOUT << "\n";
1042 Indent -= 2;
1043#endif
1044 return NULL; // Already selected.
1045 }
1046
1047 switch (Opcode) {
1048 default: break;
1049 case X86ISD::GlobalBaseReg:
1050 return getGlobalBaseReg();
1051
1052 case ISD::ADD: {
1053 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1054 // code and is matched first so to prevent it from being turned into
1055 // LEA32r X+c.
1056 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1057 MVT::ValueType PtrVT = TLI.getPointerTy();
1058 SDOperand N0 = N.getOperand(0);
1059 SDOperand N1 = N.getOperand(1);
1060 if (N.Val->getValueType(0) == PtrVT &&
1061 N0.getOpcode() == X86ISD::Wrapper &&
1062 N1.getOpcode() == ISD::Constant) {
1063 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1064 SDOperand C(0, 0);
1065 // TODO: handle ExternalSymbolSDNode.
1066 if (GlobalAddressSDNode *G =
1067 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1068 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1069 G->getOffset() + Offset);
1070 } else if (ConstantPoolSDNode *CP =
1071 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1072 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1073 CP->getAlignment(),
1074 CP->getOffset()+Offset);
1075 }
1076
1077 if (C.Val) {
1078 if (Subtarget->is64Bit()) {
1079 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1080 CurDAG->getRegister(0, PtrVT), C };
1081 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1082 } else
1083 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1084 }
1085 }
1086
1087 // Other cases are handled by auto-generated code.
1088 break;
1089 }
1090
Evan Cheng508fe8b2007-08-02 05:48:35 +00001091 case ISD::MUL: {
1092 if (NVT == MVT::i8) {
1093 SDOperand N0 = Node->getOperand(0);
1094 SDOperand N1 = Node->getOperand(1);
1095 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1096 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1097 if (!foldedLoad) {
1098 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1099 if (foldedLoad)
1100 std::swap(N0, N1);
1101 }
1102
1103 SDNode *ResNode;
1104 if (foldedLoad) {
1105 SDOperand Chain = N1.getOperand(0);
1106 AddToISelQueue(N0);
1107 AddToISelQueue(Chain);
1108 AddToISelQueue(Tmp0);
1109 AddToISelQueue(Tmp1);
1110 AddToISelQueue(Tmp2);
1111 AddToISelQueue(Tmp3);
1112 SDOperand InFlag(0, 0);
1113 Chain = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag);
1114 InFlag = Chain.getValue(1);
1115 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1116 ResNode = CurDAG->getTargetNode(X86::MUL8m, MVT::i8, MVT::i8,
1117 MVT::Other, Ops, 6);
1118 ReplaceUses(N1.getValue(1), SDOperand(ResNode, 2));
1119 } else {
1120 SDOperand Chain = CurDAG->getEntryNode();
1121 AddToISelQueue(N0);
1122 AddToISelQueue(N1);
1123 SDOperand InFlag(0, 0);
1124 InFlag = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag).getValue(1);
1125 ResNode = CurDAG->getTargetNode(X86::MUL8r, MVT::i8, MVT::i8,
1126 N1, InFlag);
1127 }
1128
1129 ReplaceUses(N.getValue(0), SDOperand(ResNode, 0));
1130 return NULL;
1131 }
1132 break;
1133 }
1134
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 case ISD::MULHU:
1136 case ISD::MULHS: {
1137 if (Opcode == ISD::MULHU)
1138 switch (NVT) {
1139 default: assert(0 && "Unsupported VT!");
1140 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1141 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1142 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1143 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1144 }
1145 else
1146 switch (NVT) {
1147 default: assert(0 && "Unsupported VT!");
1148 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1149 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1150 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1151 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1152 }
1153
1154 unsigned LoReg, HiReg;
1155 switch (NVT) {
1156 default: assert(0 && "Unsupported VT!");
1157 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1158 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1159 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1160 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1161 }
1162
1163 SDOperand N0 = Node->getOperand(0);
1164 SDOperand N1 = Node->getOperand(1);
1165
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001167 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 // MULHU and MULHS are commmutative
1169 if (!foldedLoad) {
1170 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001171 if (foldedLoad)
1172 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 }
1174
1175 SDOperand Chain;
1176 if (foldedLoad) {
1177 Chain = N1.getOperand(0);
1178 AddToISelQueue(Chain);
1179 } else
1180 Chain = CurDAG->getEntryNode();
1181
1182 SDOperand InFlag(0, 0);
1183 AddToISelQueue(N0);
1184 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1185 N0, InFlag);
1186 InFlag = Chain.getValue(1);
1187
1188 if (foldedLoad) {
1189 AddToISelQueue(Tmp0);
1190 AddToISelQueue(Tmp1);
1191 AddToISelQueue(Tmp2);
1192 AddToISelQueue(Tmp3);
1193 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1194 SDNode *CNode =
1195 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1196 Chain = SDOperand(CNode, 0);
1197 InFlag = SDOperand(CNode, 1);
1198 } else {
1199 AddToISelQueue(N1);
1200 InFlag =
1201 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1202 }
1203
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001204 SDOperand Result;
1205 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1206 // Prevent use of AH in a REX instruction by referencing AX instead.
1207 // Shift it down 8 bits.
1208 Result = CurDAG->getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
1209 Chain = Result.getValue(1);
1210 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1211 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1212 // Then truncate it down to i8.
1213 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1214 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1215 MVT::i8, Result, SRIdx), 0);
1216 } else {
1217 Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1218 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 ReplaceUses(N.getValue(0), Result);
1220 if (foldedLoad)
1221 ReplaceUses(N1.getValue(1), Result.getValue(1));
1222
1223#ifndef NDEBUG
1224 DOUT << std::string(Indent-2, ' ') << "=> ";
1225 DEBUG(Result.Val->dump(CurDAG));
1226 DOUT << "\n";
1227 Indent -= 2;
1228#endif
1229 return NULL;
1230 }
1231
1232 case ISD::SDIV:
1233 case ISD::UDIV:
1234 case ISD::SREM:
1235 case ISD::UREM: {
1236 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1237 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1238 if (!isSigned)
1239 switch (NVT) {
1240 default: assert(0 && "Unsupported VT!");
1241 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1242 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1243 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1244 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1245 }
1246 else
1247 switch (NVT) {
1248 default: assert(0 && "Unsupported VT!");
1249 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1250 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1251 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1252 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1253 }
1254
1255 unsigned LoReg, HiReg;
1256 unsigned ClrOpcode, SExtOpcode;
1257 switch (NVT) {
1258 default: assert(0 && "Unsupported VT!");
1259 case MVT::i8:
1260 LoReg = X86::AL; HiReg = X86::AH;
1261 ClrOpcode = 0;
1262 SExtOpcode = X86::CBW;
1263 break;
1264 case MVT::i16:
1265 LoReg = X86::AX; HiReg = X86::DX;
1266 ClrOpcode = X86::MOV16r0;
1267 SExtOpcode = X86::CWD;
1268 break;
1269 case MVT::i32:
1270 LoReg = X86::EAX; HiReg = X86::EDX;
1271 ClrOpcode = X86::MOV32r0;
1272 SExtOpcode = X86::CDQ;
1273 break;
1274 case MVT::i64:
1275 LoReg = X86::RAX; HiReg = X86::RDX;
1276 ClrOpcode = X86::MOV64r0;
1277 SExtOpcode = X86::CQO;
1278 break;
1279 }
1280
1281 SDOperand N0 = Node->getOperand(0);
1282 SDOperand N1 = Node->getOperand(1);
1283 SDOperand InFlag(0, 0);
1284 if (NVT == MVT::i8 && !isSigned) {
1285 // Special case for div8, just use a move with zero extension to AX to
1286 // clear the upper 8 bits (AH).
1287 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1288 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1289 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1290 AddToISelQueue(N0.getOperand(0));
1291 AddToISelQueue(Tmp0);
1292 AddToISelQueue(Tmp1);
1293 AddToISelQueue(Tmp2);
1294 AddToISelQueue(Tmp3);
1295 Move =
1296 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1297 Ops, 5), 0);
1298 Chain = Move.getValue(1);
1299 ReplaceUses(N0.getValue(1), Chain);
1300 } else {
1301 AddToISelQueue(N0);
1302 Move =
1303 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1304 Chain = CurDAG->getEntryNode();
1305 }
1306 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1307 InFlag = Chain.getValue(1);
1308 } else {
1309 AddToISelQueue(N0);
1310 InFlag =
1311 CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1312 InFlag).getValue(1);
1313 if (isSigned) {
1314 // Sign extend the low part into the high part.
1315 InFlag =
1316 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1317 } else {
1318 // Zero out the high part, effectively zero extending the input.
1319 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1320 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1321 InFlag).getValue(1);
1322 }
1323 }
1324
1325 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1326 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1327 if (foldedLoad) {
1328 AddToISelQueue(N1.getOperand(0));
1329 AddToISelQueue(Tmp0);
1330 AddToISelQueue(Tmp1);
1331 AddToISelQueue(Tmp2);
1332 AddToISelQueue(Tmp3);
1333 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1334 SDNode *CNode =
1335 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1336 Chain = SDOperand(CNode, 0);
1337 InFlag = SDOperand(CNode, 1);
1338 } else {
1339 AddToISelQueue(N1);
1340 Chain = CurDAG->getEntryNode();
1341 InFlag =
1342 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1343 }
1344
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001345 unsigned Reg = isDiv ? LoReg : HiReg;
1346 SDOperand Result;
1347 if (Reg == X86::AH && Subtarget->is64Bit()) {
1348 // Prevent use of AH in a REX instruction by referencing AX instead.
1349 // Shift it down 8 bits.
1350 Result = CurDAG->getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
1351 Chain = Result.getValue(1);
1352 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1353 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1354 // Then truncate it down to i8.
1355 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1356 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1357 MVT::i8, Result, SRIdx), 0);
1358 } else {
1359 Result = CurDAG->getCopyFromReg(Chain, Reg, NVT, InFlag);
1360 Chain = Result.getValue(1);
1361 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 ReplaceUses(N.getValue(0), Result);
1363 if (foldedLoad)
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001364 ReplaceUses(N1.getValue(1), Chain);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365
1366#ifndef NDEBUG
1367 DOUT << std::string(Indent-2, ' ') << "=> ";
1368 DEBUG(Result.Val->dump(CurDAG));
1369 DOUT << "\n";
1370 Indent -= 2;
1371#endif
1372
1373 return NULL;
1374 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001375
1376 case ISD::SIGN_EXTEND_INREG: {
1377 SDOperand N0 = Node->getOperand(0);
1378 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001380 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1381 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1382 unsigned Opc;
Christopher Lamb444336c2007-07-29 01:24:57 +00001383 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001384 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001385 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1386 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001387 break;
1388 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001389 switch (SVT) {
1390 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1391 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1392 default: assert(0 && "Unknown sign_extend_inreg!");
1393 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001394 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001395 case MVT::i64:
1396 switch (SVT) {
1397 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1398 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1399 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1400 default: assert(0 && "Unknown sign_extend_inreg!");
1401 }
1402 break;
1403 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001404 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001405
1406 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1407
1408#ifndef NDEBUG
1409 DOUT << std::string(Indent-2, ' ') << "=> ";
1410 DEBUG(TruncOp.Val->dump(CurDAG));
1411 DOUT << "\n";
1412 DOUT << std::string(Indent-2, ' ') << "=> ";
1413 DEBUG(ResNode->dump(CurDAG));
1414 DOUT << "\n";
1415 Indent -= 2;
1416#endif
1417 return ResNode;
1418 break;
1419 }
1420
1421 case ISD::TRUNCATE: {
1422 SDOperand Input = Node->getOperand(0);
1423 AddToISelQueue(Node->getOperand(0));
1424 SDNode *ResNode = getTruncate(Input, NVT);
1425
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426#ifndef NDEBUG
1427 DOUT << std::string(Indent-2, ' ') << "=> ";
1428 DEBUG(ResNode->dump(CurDAG));
1429 DOUT << "\n";
1430 Indent -= 2;
1431#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001432 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 break;
1434 }
1435 }
1436
1437 SDNode *ResNode = SelectCode(N);
1438
1439#ifndef NDEBUG
1440 DOUT << std::string(Indent-2, ' ') << "=> ";
1441 if (ResNode == NULL || ResNode == N.Val)
1442 DEBUG(N.Val->dump(CurDAG));
1443 else
1444 DEBUG(ResNode->dump(CurDAG));
1445 DOUT << "\n";
1446 Indent -= 2;
1447#endif
1448
1449 return ResNode;
1450}
1451
1452bool X86DAGToDAGISel::
1453SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1454 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1455 SDOperand Op0, Op1, Op2, Op3;
1456 switch (ConstraintCode) {
1457 case 'o': // offsetable ??
1458 case 'v': // not offsetable ??
1459 default: return true;
1460 case 'm': // memory
1461 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1462 return true;
1463 break;
1464 }
1465
1466 OutOps.push_back(Op0);
1467 OutOps.push_back(Op1);
1468 OutOps.push_back(Op2);
1469 OutOps.push_back(Op3);
1470 AddToISelQueue(Op0);
1471 AddToISelQueue(Op1);
1472 AddToISelQueue(Op2);
1473 AddToISelQueue(Op3);
1474 return false;
1475}
1476
1477/// createX86ISelDag - This pass converts a legalized DAG into a
1478/// X86-specific DAG, ready for instruction scheduling.
1479///
1480FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1481 return new X86DAGToDAGISel(TM, Fast);
1482}