blob: 0caf7a5bd3d596898bfb609ac3fd658c36effa49 [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
211#ifndef NDEBUG
212 unsigned Indent;
213#endif
214 };
215}
216
217static SDNode *findFlagUse(SDNode *N) {
218 unsigned FlagResNo = N->getNumValues()-1;
219 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
220 SDNode *User = *I;
221 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
222 SDOperand Op = User->getOperand(i);
223 if (Op.Val == N && Op.ResNo == FlagResNo)
224 return User;
225 }
226 }
227 return NULL;
228}
229
230static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
231 SDNode *Root, SDNode *Skip, bool &found,
232 std::set<SDNode *> &Visited) {
233 if (found ||
234 Use->getNodeId() > Def->getNodeId() ||
235 !Visited.insert(Use).second)
236 return;
237
238 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
239 SDNode *N = Use->getOperand(i).Val;
240 if (N == Skip)
241 continue;
242 if (N == Def) {
243 if (Use == ImmedUse)
244 continue; // Immediate use is ok.
245 if (Use == Root) {
246 assert(Use->getOpcode() == ISD::STORE ||
247 Use->getOpcode() == X86ISD::CMP);
248 continue;
249 }
250 found = true;
251 break;
252 }
253 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
254 }
255}
256
257/// isNonImmUse - Start searching from Root up the DAG to check is Def can
258/// be reached. Return true if that's the case. However, ignore direct uses
259/// by ImmedUse (which would be U in the example illustrated in
260/// CanBeFoldedBy) and by Root (which can happen in the store case).
261/// FIXME: to be really generic, we should allow direct use by any node
262/// that is being folded. But realisticly since we only fold loads which
263/// have one non-chain use, we only need to watch out for load/op/store
264/// and load/op/cmp case where the root (store / cmp) may reach the load via
265/// its chain operand.
266static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
267 SDNode *Skip = NULL) {
268 std::set<SDNode *> Visited;
269 bool found = false;
270 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
271 return found;
272}
273
274
Dan Gohmand6098272007-07-24 23:00:27 +0000275bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 if (FastISel) return false;
277
278 // If U use can somehow reach N through another path then U can't fold N or
279 // it will create a cycle. e.g. In the following diagram, U can reach N
280 // through X. If N is folded into into U, then X is both a predecessor and
281 // a successor of U.
282 //
283 // [ N ]
284 // ^ ^
285 // | |
286 // / \---
287 // / [X]
288 // | ^
289 // [U]--------|
290
291 if (isNonImmUse(Root, N, U))
292 return false;
293
294 // If U produces a flag, then it gets (even more) interesting. Since it
295 // would have been "glued" together with its flag use, we need to check if
296 // it might reach N:
297 //
298 // [ N ]
299 // ^ ^
300 // | |
301 // [U] \--
302 // ^ [TF]
303 // | ^
304 // | |
305 // \ /
306 // [FU]
307 //
308 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
309 // NU), then TF is a predecessor of FU and a successor of NU. But since
310 // NU and FU are flagged together, this effectively creates a cycle.
311 bool HasFlagUse = false;
312 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
313 while ((VT == MVT::Flag && !Root->use_empty())) {
314 SDNode *FU = findFlagUse(Root);
315 if (FU == NULL)
316 break;
317 else {
318 Root = FU;
319 HasFlagUse = true;
320 }
321 VT = Root->getValueType(Root->getNumValues()-1);
322 }
323
324 if (HasFlagUse)
325 return !isNonImmUse(Root, N, Root, U);
326 return true;
327}
328
329/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
330/// and move load below the TokenFactor. Replace store's chain operand with
331/// load's chain result.
332static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
333 SDOperand Store, SDOperand TF) {
334 std::vector<SDOperand> Ops;
335 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
336 if (Load.Val == TF.Val->getOperand(i).Val)
337 Ops.push_back(Load.Val->getOperand(0));
338 else
339 Ops.push_back(TF.Val->getOperand(i));
340 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
341 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
342 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
343 Store.getOperand(2), Store.getOperand(3));
344}
345
346/// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
347/// selector to pick more load-modify-store instructions. This is a common
348/// case:
349///
350/// [Load chain]
351/// ^
352/// |
353/// [Load]
354/// ^ ^
355/// | |
356/// / \-
357/// / |
358/// [TokenFactor] [Op]
359/// ^ ^
360/// | |
361/// \ /
362/// \ /
363/// [Store]
364///
365/// The fact the store's chain operand != load's chain will prevent the
366/// (store (op (load))) instruction from being selected. We can transform it to:
367///
368/// [Load chain]
369/// ^
370/// |
371/// [TokenFactor]
372/// ^
373/// |
374/// [Load]
375/// ^ ^
376/// | |
377/// | \-
378/// | |
379/// | [Op]
380/// | ^
381/// | |
382/// \ /
383/// \ /
384/// [Store]
385void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
386 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
387 E = DAG.allnodes_end(); I != E; ++I) {
388 if (!ISD::isNON_TRUNCStore(I))
389 continue;
390 SDOperand Chain = I->getOperand(0);
391 if (Chain.Val->getOpcode() != ISD::TokenFactor)
392 continue;
393
394 SDOperand N1 = I->getOperand(1);
395 SDOperand N2 = I->getOperand(2);
396 if (MVT::isFloatingPoint(N1.getValueType()) ||
397 MVT::isVector(N1.getValueType()) ||
398 !N1.hasOneUse())
399 continue;
400
401 bool RModW = false;
402 SDOperand Load;
403 unsigned Opcode = N1.Val->getOpcode();
404 switch (Opcode) {
405 case ISD::ADD:
406 case ISD::MUL:
407 case ISD::AND:
408 case ISD::OR:
409 case ISD::XOR:
410 case ISD::ADDC:
411 case ISD::ADDE: {
412 SDOperand N10 = N1.getOperand(0);
413 SDOperand N11 = N1.getOperand(1);
414 if (ISD::isNON_EXTLoad(N10.Val))
415 RModW = true;
416 else if (ISD::isNON_EXTLoad(N11.Val)) {
417 RModW = true;
418 std::swap(N10, N11);
419 }
420 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
421 (N10.getOperand(1) == N2) &&
422 (N10.Val->getValueType(0) == N1.getValueType());
423 if (RModW)
424 Load = N10;
425 break;
426 }
427 case ISD::SUB:
428 case ISD::SHL:
429 case ISD::SRA:
430 case ISD::SRL:
431 case ISD::ROTL:
432 case ISD::ROTR:
433 case ISD::SUBC:
434 case ISD::SUBE:
435 case X86ISD::SHLD:
436 case X86ISD::SHRD: {
437 SDOperand N10 = N1.getOperand(0);
438 if (ISD::isNON_EXTLoad(N10.Val))
439 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
440 (N10.getOperand(1) == N2) &&
441 (N10.Val->getValueType(0) == N1.getValueType());
442 if (RModW)
443 Load = N10;
444 break;
445 }
446 }
447
448 if (RModW) {
449 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
450 ++NumLoadMoved;
451 }
452 }
453}
454
455/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
456/// when it has created a SelectionDAG for us to codegen.
457void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
458 DEBUG(BB->dump());
459 MachineFunction::iterator FirstMBB = BB;
460
461 if (!FastISel)
462 InstructionSelectPreprocess(DAG);
463
464 // Codegen the basic block.
465#ifndef NDEBUG
466 DOUT << "===== Instruction selection begins:\n";
467 Indent = 0;
468#endif
469 DAG.setRoot(SelectRoot(DAG.getRoot()));
470#ifndef NDEBUG
471 DOUT << "===== Instruction selection ends:\n";
472#endif
473
474 DAG.RemoveDeadNodes();
475
476 // Emit machine code to BB.
477 ScheduleAndEmitDAG(DAG);
478
479 // If we are emitting FP stack code, scan the basic block to determine if this
480 // block defines any FP values. If so, put an FP_REG_KILL instruction before
481 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000482
483 // Note that FP stack instructions *are* used in SSE code for long double,
484 // so we do need this check.
485 bool ContainsFPCode = false;
486
487 // Scan all of the machine instructions in these MBBs, checking for FP
488 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
489 MachineFunction::iterator MBBI = FirstMBB;
490 do {
491 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
492 !ContainsFPCode && I != E; ++I) {
493 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
494 const TargetRegisterClass *clas;
495 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
496 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
497 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
498 ((clas = RegMap->getRegClass(I->getOperand(0).getReg())) ==
499 X86::RFP32RegisterClass ||
500 clas == X86::RFP64RegisterClass ||
501 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 ContainsFPCode = true;
503 break;
504 }
505 }
506 }
507 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000508 } while (!ContainsFPCode && &*(MBBI++) != BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000510 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
511 // a copy of the input value in this block. In SSE mode, we only care about
512 // 80-bit values.
513 if (!ContainsFPCode) {
514 // Final check, check LLVM BB's that are successors to the LLVM BB
515 // corresponding to BB for FP PHI nodes.
516 const BasicBlock *LLVMBB = BB->getBasicBlock();
517 const PHINode *PN;
518 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
519 !ContainsFPCode && SI != E; ++SI) {
520 for (BasicBlock::const_iterator II = SI->begin();
521 (PN = dyn_cast<PHINode>(II)); ++II) {
522 if (PN->getType()==Type::X86_FP80Ty ||
523 (!Subtarget->hasSSE2() && PN->getType()->isFloatingPoint())) {
524 ContainsFPCode = true;
525 break;
526 }
527 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 }
529 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000530
531 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
532 if (ContainsFPCode) {
533 BuildMI(*BB, BB->getFirstTerminator(),
534 TM.getInstrInfo()->get(X86::FP_REG_KILL));
535 ++NumFPKill;
536 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537}
538
539/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
540/// the main function.
541void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
542 MachineFrameInfo *MFI) {
543 const TargetInstrInfo *TII = TM.getInstrInfo();
544 if (Subtarget->isTargetCygMing())
545 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
546
547 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
548 int CWFrameIdx = MFI->CreateStackObject(2, 2);
549 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
550
551 // Set the high part to be 64-bit precision.
552 addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
553 CWFrameIdx, 1).addImm(2);
554
555 // Reload the modified control word now.
556 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
557}
558
559void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
560 // If this is main, emit special code for main.
561 MachineBasicBlock *BB = MF.begin();
562 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
563 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
564}
565
566/// MatchAddress - Add the specified node to the specified addressing mode,
567/// returning true if it cannot be done. This just pattern matches for the
568/// addressing mode
569bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
570 bool isRoot, unsigned Depth) {
571 if (Depth > 5) {
572 // Default, generate it as a register.
573 AM.BaseType = X86ISelAddressMode::RegBase;
574 AM.Base.Reg = N;
575 return false;
576 }
577
578 // RIP relative addressing: %rip + 32-bit displacement!
579 if (AM.isRIPRel) {
580 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
581 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
582 if (isInt32(AM.Disp + Val)) {
583 AM.Disp += Val;
584 return false;
585 }
586 }
587 return true;
588 }
589
590 int id = N.Val->getNodeId();
591 bool Available = isSelected(id);
592
593 switch (N.getOpcode()) {
594 default: break;
595 case ISD::Constant: {
596 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
597 if (isInt32(AM.Disp + Val)) {
598 AM.Disp += Val;
599 return false;
600 }
601 break;
602 }
603
604 case X86ISD::Wrapper: {
605 bool is64Bit = Subtarget->is64Bit();
606 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
607 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
608 break;
609 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
610 break;
611 // If value is available in a register both base and index components have
612 // been picked, we can't fit the result available in the register in the
613 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
614 if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
615 bool isStatic = TM.getRelocationModel() == Reloc::Static;
616 SDOperand N0 = N.getOperand(0);
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000617 // Mac OS X X86-64 lower 4G address is not available.
Evan Cheng09e13792007-08-01 23:45:51 +0000618 bool isAbs32 = !is64Bit ||
619 (isStatic && Subtarget->hasLow4GUserSpaceAddress());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
621 GlobalValue *GV = G->getGlobal();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 if (isAbs32 || isRoot) {
623 AM.GV = GV;
624 AM.Disp += G->getOffset();
625 AM.isRIPRel = !isAbs32;
626 return false;
627 }
628 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000629 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 AM.CP = CP->getConstVal();
631 AM.Align = CP->getAlignment();
632 AM.Disp += CP->getOffset();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000633 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 return false;
635 }
636 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000637 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 AM.ES = S->getSymbol();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000639 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 return false;
641 }
642 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Chenga2f7d4e2007-07-26 07:35:15 +0000643 if (isAbs32 || isRoot) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 AM.JT = J->getIndex();
Evan Chengeda2f2b2007-07-26 17:02:45 +0000645 AM.isRIPRel = !isAbs32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 return false;
647 }
648 }
649 }
650 break;
651 }
652
653 case ISD::FrameIndex:
654 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
655 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
656 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
657 return false;
658 }
659 break;
660
661 case ISD::SHL:
662 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
663 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
664 unsigned Val = CN->getValue();
665 if (Val == 1 || Val == 2 || Val == 3) {
666 AM.Scale = 1 << Val;
667 SDOperand ShVal = N.Val->getOperand(0);
668
669 // Okay, we know that we have a scale by now. However, if the scaled
670 // value is an add of something and a constant, we can fold the
671 // constant into the disp field here.
672 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
673 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
674 AM.IndexReg = ShVal.Val->getOperand(0);
675 ConstantSDNode *AddVal =
676 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
677 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
678 if (isInt32(Disp))
679 AM.Disp = Disp;
680 else
681 AM.IndexReg = ShVal;
682 } else {
683 AM.IndexReg = ShVal;
684 }
685 return false;
686 }
687 }
688 break;
689
690 case ISD::MUL:
691 // X*[3,5,9] -> X+X*[2,4,8]
692 if (!Available &&
693 AM.BaseType == X86ISelAddressMode::RegBase &&
694 AM.Base.Reg.Val == 0 &&
695 AM.IndexReg.Val == 0) {
696 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
697 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
698 AM.Scale = unsigned(CN->getValue())-1;
699
700 SDOperand MulVal = N.Val->getOperand(0);
701 SDOperand Reg;
702
703 // Okay, we know that we have a scale by now. However, if the scaled
704 // value is an add of something and a constant, we can fold the
705 // constant into the disp field here.
706 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
707 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
708 Reg = MulVal.Val->getOperand(0);
709 ConstantSDNode *AddVal =
710 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
711 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
712 if (isInt32(Disp))
713 AM.Disp = Disp;
714 else
715 Reg = N.Val->getOperand(0);
716 } else {
717 Reg = N.Val->getOperand(0);
718 }
719
720 AM.IndexReg = AM.Base.Reg = Reg;
721 return false;
722 }
723 }
724 break;
725
726 case ISD::ADD:
727 if (!Available) {
728 X86ISelAddressMode Backup = AM;
729 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
730 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
731 return false;
732 AM = Backup;
733 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
734 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
735 return false;
736 AM = Backup;
737 }
738 break;
739
740 case ISD::OR:
741 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
742 if (!Available) {
743 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
744 X86ISelAddressMode Backup = AM;
745 // Start with the LHS as an addr mode.
746 if (!MatchAddress(N.getOperand(0), AM, false) &&
747 // Address could not have picked a GV address for the displacement.
748 AM.GV == NULL &&
749 // On x86-64, the resultant disp must fit in 32-bits.
750 isInt32(AM.Disp + CN->getSignExtended()) &&
751 // Check to see if the LHS & C is zero.
752 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
753 AM.Disp += CN->getValue();
754 return false;
755 }
756 AM = Backup;
757 }
758 }
759 break;
760 }
761
762 // Is the base register already occupied?
763 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
764 // If so, check to see if the scale index register is set.
765 if (AM.IndexReg.Val == 0) {
766 AM.IndexReg = N;
767 AM.Scale = 1;
768 return false;
769 }
770
771 // Otherwise, we cannot select it.
772 return true;
773 }
774
775 // Default, generate it as a register.
776 AM.BaseType = X86ISelAddressMode::RegBase;
777 AM.Base.Reg = N;
778 return false;
779}
780
781/// SelectAddr - returns true if it is able pattern match an addressing mode.
782/// It returns the operands which make up the maximal addressing mode it can
783/// match by reference.
784bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
785 SDOperand &Scale, SDOperand &Index,
786 SDOperand &Disp) {
787 X86ISelAddressMode AM;
788 if (MatchAddress(N, AM))
789 return false;
790
791 MVT::ValueType VT = N.getValueType();
792 if (AM.BaseType == X86ISelAddressMode::RegBase) {
793 if (!AM.Base.Reg.Val)
794 AM.Base.Reg = CurDAG->getRegister(0, VT);
795 }
796
797 if (!AM.IndexReg.Val)
798 AM.IndexReg = CurDAG->getRegister(0, VT);
799
800 getAddressOperands(AM, Base, Scale, Index, Disp);
801 return true;
802}
803
804/// isZeroNode - Returns true if Elt is a constant zero or a floating point
805/// constant +0.0.
806static inline bool isZeroNode(SDOperand Elt) {
807 return ((isa<ConstantSDNode>(Elt) &&
808 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
809 (isa<ConstantFPSDNode>(Elt) &&
810 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
811}
812
813
814/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
815/// match a load whose top elements are either undef or zeros. The load flavor
816/// is derived from the type of N, which is either v4f32 or v2f64.
817bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
818 SDOperand N, SDOperand &Base,
819 SDOperand &Scale, SDOperand &Index,
820 SDOperand &Disp, SDOperand &InChain,
821 SDOperand &OutChain) {
822 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
823 InChain = N.getOperand(0).getValue(1);
824 if (ISD::isNON_EXTLoad(InChain.Val) &&
825 InChain.getValue(0).hasOneUse() &&
826 N.hasOneUse() &&
827 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
828 LoadSDNode *LD = cast<LoadSDNode>(InChain);
829 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
830 return false;
831 OutChain = LD->getChain();
832 return true;
833 }
834 }
835
836 // Also handle the case where we explicitly require zeros in the top
837 // elements. This is a vector shuffle from the zero vector.
838 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
839 N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
840 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
841 N.getOperand(1).Val->hasOneUse() &&
842 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
843 N.getOperand(1).getOperand(0).hasOneUse()) {
844 // Check to see if the BUILD_VECTOR is building a zero vector.
845 SDOperand BV = N.getOperand(0);
846 for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
847 if (!isZeroNode(BV.getOperand(i)) &&
848 BV.getOperand(i).getOpcode() != ISD::UNDEF)
849 return false; // Not a zero/undef vector.
850 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
851 // from the LHS.
852 unsigned VecWidth = BV.getNumOperands();
853 SDOperand ShufMask = N.getOperand(2);
854 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
856 if (C->getValue() == VecWidth) {
857 for (unsigned i = 1; i != VecWidth; ++i) {
858 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
859 // ok.
860 } else {
861 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
862 if (C->getValue() >= VecWidth) return false;
863 }
864 }
865 }
866
867 // Okay, this is a zero extending load. Fold it.
868 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
869 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
870 return false;
871 OutChain = LD->getChain();
872 InChain = SDOperand(LD, 1);
873 return true;
874 }
875 }
876 return false;
877}
878
879
880/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
881/// mode it matches can be cost effectively emitted as an LEA instruction.
882bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
883 SDOperand &Base, SDOperand &Scale,
884 SDOperand &Index, SDOperand &Disp) {
885 X86ISelAddressMode AM;
886 if (MatchAddress(N, AM))
887 return false;
888
889 MVT::ValueType VT = N.getValueType();
890 unsigned Complexity = 0;
891 if (AM.BaseType == X86ISelAddressMode::RegBase)
892 if (AM.Base.Reg.Val)
893 Complexity = 1;
894 else
895 AM.Base.Reg = CurDAG->getRegister(0, VT);
896 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
897 Complexity = 4;
898
899 if (AM.IndexReg.Val)
900 Complexity++;
901 else
902 AM.IndexReg = CurDAG->getRegister(0, VT);
903
904 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
905 // a simple shift.
906 if (AM.Scale > 1)
907 Complexity++;
908
909 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
910 // to a LEA. This is determined with some expermentation but is by no means
911 // optimal (especially for code size consideration). LEA is nice because of
912 // its three-address nature. Tweak the cost function again when we can run
913 // convertToThreeAddress() at register allocation time.
914 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
915 // For X86-64, we should always use lea to materialize RIP relative
916 // addresses.
917 if (Subtarget->is64Bit())
918 Complexity = 4;
919 else
920 Complexity += 2;
921 }
922
923 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
924 Complexity++;
925
926 if (Complexity > 2) {
927 getAddressOperands(AM, Base, Scale, Index, Disp);
928 return true;
929 }
930 return false;
931}
932
933bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
934 SDOperand &Base, SDOperand &Scale,
935 SDOperand &Index, SDOperand &Disp) {
936 if (ISD::isNON_EXTLoad(N.Val) &&
937 N.hasOneUse() &&
938 CanBeFoldedBy(N.Val, P.Val, P.Val))
939 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
940 return false;
941}
942
943/// getGlobalBaseReg - Output the instructions required to put the
944/// base address to use for accessing globals into a register.
945///
946SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
947 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
948 if (!GlobalBaseReg) {
949 // Insert the set of GlobalBaseReg into the first MBB of the function
950 MachineBasicBlock &FirstMBB = BB->getParent()->front();
951 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
952 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
953 unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
954
955 const TargetInstrInfo *TII = TM.getInstrInfo();
956 BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
957 BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
958
959 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
960 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
961 if (TM.getRelocationModel() == Reloc::PIC_ &&
962 Subtarget->isPICStyleGOT()) {
963 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
964 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
965 addReg(PC).
966 addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
967 } else {
968 GlobalBaseReg = PC;
969 }
970
971 }
972 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
973}
974
975static SDNode *FindCallStartFromCall(SDNode *Node) {
976 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
977 assert(Node->getOperand(0).getValueType() == MVT::Other &&
978 "Node doesn't have a token chain argument!");
979 return FindCallStartFromCall(Node->getOperand(0).Val);
980}
981
982SDNode *X86DAGToDAGISel::Select(SDOperand N) {
983 SDNode *Node = N.Val;
984 MVT::ValueType NVT = Node->getValueType(0);
985 unsigned Opc, MOpc;
986 unsigned Opcode = Node->getOpcode();
987
988#ifndef NDEBUG
989 DOUT << std::string(Indent, ' ') << "Selecting: ";
990 DEBUG(Node->dump(CurDAG));
991 DOUT << "\n";
992 Indent += 2;
993#endif
994
995 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
996#ifndef NDEBUG
997 DOUT << std::string(Indent-2, ' ') << "== ";
998 DEBUG(Node->dump(CurDAG));
999 DOUT << "\n";
1000 Indent -= 2;
1001#endif
1002 return NULL; // Already selected.
1003 }
1004
1005 switch (Opcode) {
1006 default: break;
1007 case X86ISD::GlobalBaseReg:
1008 return getGlobalBaseReg();
1009
1010 case ISD::ADD: {
1011 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1012 // code and is matched first so to prevent it from being turned into
1013 // LEA32r X+c.
1014 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1015 MVT::ValueType PtrVT = TLI.getPointerTy();
1016 SDOperand N0 = N.getOperand(0);
1017 SDOperand N1 = N.getOperand(1);
1018 if (N.Val->getValueType(0) == PtrVT &&
1019 N0.getOpcode() == X86ISD::Wrapper &&
1020 N1.getOpcode() == ISD::Constant) {
1021 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1022 SDOperand C(0, 0);
1023 // TODO: handle ExternalSymbolSDNode.
1024 if (GlobalAddressSDNode *G =
1025 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1026 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1027 G->getOffset() + Offset);
1028 } else if (ConstantPoolSDNode *CP =
1029 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1030 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1031 CP->getAlignment(),
1032 CP->getOffset()+Offset);
1033 }
1034
1035 if (C.Val) {
1036 if (Subtarget->is64Bit()) {
1037 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1038 CurDAG->getRegister(0, PtrVT), C };
1039 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1040 } else
1041 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1042 }
1043 }
1044
1045 // Other cases are handled by auto-generated code.
1046 break;
1047 }
1048
Evan Cheng508fe8b2007-08-02 05:48:35 +00001049 case ISD::MUL: {
1050 if (NVT == MVT::i8) {
1051 SDOperand N0 = Node->getOperand(0);
1052 SDOperand N1 = Node->getOperand(1);
1053 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1054 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1055 if (!foldedLoad) {
1056 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1057 if (foldedLoad)
1058 std::swap(N0, N1);
1059 }
1060
1061 SDNode *ResNode;
1062 if (foldedLoad) {
1063 SDOperand Chain = N1.getOperand(0);
1064 AddToISelQueue(N0);
1065 AddToISelQueue(Chain);
1066 AddToISelQueue(Tmp0);
1067 AddToISelQueue(Tmp1);
1068 AddToISelQueue(Tmp2);
1069 AddToISelQueue(Tmp3);
1070 SDOperand InFlag(0, 0);
1071 Chain = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag);
1072 InFlag = Chain.getValue(1);
1073 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1074 ResNode = CurDAG->getTargetNode(X86::MUL8m, MVT::i8, MVT::i8,
1075 MVT::Other, Ops, 6);
1076 ReplaceUses(N1.getValue(1), SDOperand(ResNode, 2));
1077 } else {
1078 SDOperand Chain = CurDAG->getEntryNode();
1079 AddToISelQueue(N0);
1080 AddToISelQueue(N1);
1081 SDOperand InFlag(0, 0);
1082 InFlag = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag).getValue(1);
1083 ResNode = CurDAG->getTargetNode(X86::MUL8r, MVT::i8, MVT::i8,
1084 N1, InFlag);
1085 }
1086
1087 ReplaceUses(N.getValue(0), SDOperand(ResNode, 0));
1088 return NULL;
1089 }
1090 break;
1091 }
1092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 case ISD::MULHU:
1094 case ISD::MULHS: {
1095 if (Opcode == ISD::MULHU)
1096 switch (NVT) {
1097 default: assert(0 && "Unsupported VT!");
1098 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1099 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1100 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1101 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1102 }
1103 else
1104 switch (NVT) {
1105 default: assert(0 && "Unsupported VT!");
1106 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1107 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1108 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1109 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1110 }
1111
1112 unsigned LoReg, HiReg;
1113 switch (NVT) {
1114 default: assert(0 && "Unsupported VT!");
1115 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1116 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1117 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1118 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1119 }
1120
1121 SDOperand N0 = Node->getOperand(0);
1122 SDOperand N1 = Node->getOperand(1);
1123
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001125 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 // MULHU and MULHS are commmutative
1127 if (!foldedLoad) {
1128 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001129 if (foldedLoad)
1130 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 }
1132
1133 SDOperand Chain;
1134 if (foldedLoad) {
1135 Chain = N1.getOperand(0);
1136 AddToISelQueue(Chain);
1137 } else
1138 Chain = CurDAG->getEntryNode();
1139
1140 SDOperand InFlag(0, 0);
1141 AddToISelQueue(N0);
1142 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1143 N0, InFlag);
1144 InFlag = Chain.getValue(1);
1145
1146 if (foldedLoad) {
1147 AddToISelQueue(Tmp0);
1148 AddToISelQueue(Tmp1);
1149 AddToISelQueue(Tmp2);
1150 AddToISelQueue(Tmp3);
1151 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1152 SDNode *CNode =
1153 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1154 Chain = SDOperand(CNode, 0);
1155 InFlag = SDOperand(CNode, 1);
1156 } else {
1157 AddToISelQueue(N1);
1158 InFlag =
1159 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1160 }
1161
1162 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1163 ReplaceUses(N.getValue(0), Result);
1164 if (foldedLoad)
1165 ReplaceUses(N1.getValue(1), Result.getValue(1));
1166
1167#ifndef NDEBUG
1168 DOUT << std::string(Indent-2, ' ') << "=> ";
1169 DEBUG(Result.Val->dump(CurDAG));
1170 DOUT << "\n";
1171 Indent -= 2;
1172#endif
1173 return NULL;
1174 }
1175
1176 case ISD::SDIV:
1177 case ISD::UDIV:
1178 case ISD::SREM:
1179 case ISD::UREM: {
1180 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1181 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1182 if (!isSigned)
1183 switch (NVT) {
1184 default: assert(0 && "Unsupported VT!");
1185 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1186 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1187 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1188 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1189 }
1190 else
1191 switch (NVT) {
1192 default: assert(0 && "Unsupported VT!");
1193 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1194 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1195 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1196 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1197 }
1198
1199 unsigned LoReg, HiReg;
1200 unsigned ClrOpcode, SExtOpcode;
1201 switch (NVT) {
1202 default: assert(0 && "Unsupported VT!");
1203 case MVT::i8:
1204 LoReg = X86::AL; HiReg = X86::AH;
1205 ClrOpcode = 0;
1206 SExtOpcode = X86::CBW;
1207 break;
1208 case MVT::i16:
1209 LoReg = X86::AX; HiReg = X86::DX;
1210 ClrOpcode = X86::MOV16r0;
1211 SExtOpcode = X86::CWD;
1212 break;
1213 case MVT::i32:
1214 LoReg = X86::EAX; HiReg = X86::EDX;
1215 ClrOpcode = X86::MOV32r0;
1216 SExtOpcode = X86::CDQ;
1217 break;
1218 case MVT::i64:
1219 LoReg = X86::RAX; HiReg = X86::RDX;
1220 ClrOpcode = X86::MOV64r0;
1221 SExtOpcode = X86::CQO;
1222 break;
1223 }
1224
1225 SDOperand N0 = Node->getOperand(0);
1226 SDOperand N1 = Node->getOperand(1);
1227 SDOperand InFlag(0, 0);
1228 if (NVT == MVT::i8 && !isSigned) {
1229 // Special case for div8, just use a move with zero extension to AX to
1230 // clear the upper 8 bits (AH).
1231 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1232 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1233 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1234 AddToISelQueue(N0.getOperand(0));
1235 AddToISelQueue(Tmp0);
1236 AddToISelQueue(Tmp1);
1237 AddToISelQueue(Tmp2);
1238 AddToISelQueue(Tmp3);
1239 Move =
1240 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1241 Ops, 5), 0);
1242 Chain = Move.getValue(1);
1243 ReplaceUses(N0.getValue(1), Chain);
1244 } else {
1245 AddToISelQueue(N0);
1246 Move =
1247 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1248 Chain = CurDAG->getEntryNode();
1249 }
1250 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1251 InFlag = Chain.getValue(1);
1252 } else {
1253 AddToISelQueue(N0);
1254 InFlag =
1255 CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1256 InFlag).getValue(1);
1257 if (isSigned) {
1258 // Sign extend the low part into the high part.
1259 InFlag =
1260 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1261 } else {
1262 // Zero out the high part, effectively zero extending the input.
1263 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1264 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1265 InFlag).getValue(1);
1266 }
1267 }
1268
1269 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1270 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1271 if (foldedLoad) {
1272 AddToISelQueue(N1.getOperand(0));
1273 AddToISelQueue(Tmp0);
1274 AddToISelQueue(Tmp1);
1275 AddToISelQueue(Tmp2);
1276 AddToISelQueue(Tmp3);
1277 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1278 SDNode *CNode =
1279 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1280 Chain = SDOperand(CNode, 0);
1281 InFlag = SDOperand(CNode, 1);
1282 } else {
1283 AddToISelQueue(N1);
1284 Chain = CurDAG->getEntryNode();
1285 InFlag =
1286 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1287 }
1288
1289 SDOperand Result =
1290 CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1291 ReplaceUses(N.getValue(0), Result);
1292 if (foldedLoad)
1293 ReplaceUses(N1.getValue(1), Result.getValue(1));
1294
1295#ifndef NDEBUG
1296 DOUT << std::string(Indent-2, ' ') << "=> ";
1297 DEBUG(Result.Val->dump(CurDAG));
1298 DOUT << "\n";
1299 Indent -= 2;
1300#endif
1301
1302 return NULL;
1303 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304
Christopher Lamb444336c2007-07-29 01:24:57 +00001305 case ISD::TRUNCATE: {
1306 SDOperand Tmp;
1307 SDOperand Input = Node->getOperand(0);
1308 AddToISelQueue(Node->getOperand(0));
1309 switch (NVT) {
1310 case MVT::i8:
1311 Tmp = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1312 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1313 if (!Subtarget->is64Bit()) {
1314 unsigned Opc;
1315 MVT::ValueType VT;
1316 switch (Node->getOperand(0).getValueType()) {
1317 default: assert(0 && "Unknown truncate!");
1318 case MVT::i16:
1319 Opc = X86::MOV16to16_;
1320 VT = MVT::i16;
1321 break;
1322 case MVT::i32:
1323 Opc = X86::MOV32to32_;
1324 VT = MVT::i32;
1325 break;
1326 }
1327 Input =
1328 SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1329 }
1330 break;
1331 case MVT::i16:
1332 Tmp = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1333 break;
1334 case MVT::i32:
1335 Tmp = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1336 break;
1337 default: assert(0 && "Unknown truncate!");
1338 }
1339 SDNode *ResNode = CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1340 NVT,
1341 Input, Tmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342#ifndef NDEBUG
1343 DOUT << std::string(Indent-2, ' ') << "=> ";
1344 DEBUG(ResNode->dump(CurDAG));
1345 DOUT << "\n";
1346 Indent -= 2;
1347#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001348 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 break;
1350 }
1351 }
1352
1353 SDNode *ResNode = SelectCode(N);
1354
1355#ifndef NDEBUG
1356 DOUT << std::string(Indent-2, ' ') << "=> ";
1357 if (ResNode == NULL || ResNode == N.Val)
1358 DEBUG(N.Val->dump(CurDAG));
1359 else
1360 DEBUG(ResNode->dump(CurDAG));
1361 DOUT << "\n";
1362 Indent -= 2;
1363#endif
1364
1365 return ResNode;
1366}
1367
1368bool X86DAGToDAGISel::
1369SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1370 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1371 SDOperand Op0, Op1, Op2, Op3;
1372 switch (ConstraintCode) {
1373 case 'o': // offsetable ??
1374 case 'v': // not offsetable ??
1375 default: return true;
1376 case 'm': // memory
1377 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1378 return true;
1379 break;
1380 }
1381
1382 OutOps.push_back(Op0);
1383 OutOps.push_back(Op1);
1384 OutOps.push_back(Op2);
1385 OutOps.push_back(Op3);
1386 AddToISelQueue(Op0);
1387 AddToISelQueue(Op1);
1388 AddToISelQueue(Op2);
1389 AddToISelQueue(Op3);
1390 return false;
1391}
1392
1393/// createX86ISelDag - This pass converts a legalized DAG into a
1394/// X86-specific DAG, ready for instruction scheduling.
1395///
1396FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1397 return new X86DAGToDAGISel(TM, Fast);
1398}