blob: 53de9d86447061e8c846d61e1658ea07dd0ea7f6 [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//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Evan Cheng0729ccf2008-01-05 00:41:47 +000019#include "X86MachineFunctionInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "X86RegisterInfo.h"
21#include "X86Subtarget.h"
22#include "X86TargetMachine.h"
23#include "llvm/GlobalValue.h"
24#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Support/CFG.h"
27#include "llvm/Type.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner1b989192007-12-31 04:13:23 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/CodeGen/SelectionDAGISel.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/MathExtras.h"
38#include "llvm/ADT/Statistic.h"
39#include <queue>
40#include <set>
41using namespace llvm;
42
43STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
44STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45
46
47//===----------------------------------------------------------------------===//
48// Pattern Matcher Implementation
49//===----------------------------------------------------------------------===//
50
51namespace {
52 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
53 /// SDOperand's instead of register numbers for the leaves of the matched
54 /// tree.
55 struct X86ISelAddressMode {
56 enum {
57 RegBase,
58 FrameIndexBase
59 } BaseType;
60
61 struct { // This is really a union, discriminated by BaseType!
62 SDOperand Reg;
63 int FrameIndex;
64 } Base;
65
Evan Cheng3b5a1272008-02-07 08:53:49 +000066 bool isRIPRel; // RIP as base?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067 unsigned Scale;
68 SDOperand IndexReg;
69 unsigned Disp;
70 GlobalValue *GV;
71 Constant *CP;
72 const char *ES;
73 int JT;
74 unsigned Align; // CP alignment.
75
76 X86ISelAddressMode()
77 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
78 GV(0), CP(0), ES(0), JT(-1), Align(0) {
79 }
80 };
81}
82
83namespace {
84 //===--------------------------------------------------------------------===//
85 /// ISel - X86 specific code to select X86 machine instructions for
86 /// SelectionDAG operations.
87 ///
88 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
89 /// ContainsFPCode - Every instruction we select that uses or defines a FP
90 /// register should set this to true.
91 bool ContainsFPCode;
92
93 /// FastISel - Enable fast(er) instruction selection.
94 ///
95 bool FastISel;
96
97 /// TM - Keep a reference to X86TargetMachine.
98 ///
99 X86TargetMachine &TM;
100
101 /// X86Lowering - This object fully describes how to lower LLVM code to an
102 /// X86-specific SelectionDAG.
103 X86TargetLowering X86Lowering;
104
105 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const X86Subtarget *Subtarget;
108
109 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
110 /// base register.
111 unsigned GlobalBaseReg;
112
113 public:
114 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
115 : SelectionDAGISel(X86Lowering),
116 ContainsFPCode(false), FastISel(fast), TM(tm),
117 X86Lowering(*TM.getTargetLowering()),
118 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
119
120 virtual bool runOnFunction(Function &Fn) {
121 // Make sure we re-emit a set of the global base reg if necessary
122 GlobalBaseReg = 0;
123 return SelectionDAGISel::runOnFunction(Fn);
124 }
125
126 virtual const char *getPassName() const {
127 return "X86 DAG->DAG Instruction Selection";
128 }
129
130 /// InstructionSelectBasicBlock - This callback is invoked by
131 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
133
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000134 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
135
Dan Gohmand6098272007-07-24 23:00:27 +0000136 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138// Include the pieces autogenerated from the target description.
139#include "X86GenDAGISel.inc"
140
141 private:
142 SDNode *Select(SDOperand N);
143
144 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
145 bool isRoot = true, unsigned Depth = 0);
Dan Gohmana60c1b32007-08-13 20:03:06 +0000146 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
147 bool isRoot, unsigned Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
149 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
150 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
151 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
152 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
153 SDOperand N, SDOperand &Base, SDOperand &Scale,
154 SDOperand &Index, SDOperand &Disp,
155 SDOperand &InChain, SDOperand &OutChain);
156 bool TryFoldLoad(SDOperand P, SDOperand N,
157 SDOperand &Base, SDOperand &Scale,
158 SDOperand &Index, SDOperand &Disp);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000159 void PreprocessForRMW(SelectionDAG &DAG);
160 void PreprocessForFPConvert(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
162 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
163 /// inline asm expressions.
164 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
165 char ConstraintCode,
166 std::vector<SDOperand> &OutOps,
167 SelectionDAG &DAG);
168
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000169 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
170
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
172 SDOperand &Scale, SDOperand &Index,
173 SDOperand &Disp) {
174 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
175 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
176 AM.Base.Reg;
177 Scale = getI8Imm(AM.Scale);
178 Index = AM.IndexReg;
179 // These are 32-bit even in 64-bit mode since RIP relative offset
180 // is 32-bit.
181 if (AM.GV)
182 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
183 else if (AM.CP)
184 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
185 else if (AM.ES)
186 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
187 else if (AM.JT != -1)
188 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
189 else
190 Disp = getI32Imm(AM.Disp);
191 }
192
193 /// getI8Imm - Return a target constant with the specified value, of type
194 /// i8.
195 inline SDOperand getI8Imm(unsigned Imm) {
196 return CurDAG->getTargetConstant(Imm, MVT::i8);
197 }
198
199 /// getI16Imm - Return a target constant with the specified value, of type
200 /// i16.
201 inline SDOperand getI16Imm(unsigned Imm) {
202 return CurDAG->getTargetConstant(Imm, MVT::i16);
203 }
204
205 /// getI32Imm - Return a target constant with the specified value, of type
206 /// i32.
207 inline SDOperand getI32Imm(unsigned Imm) {
208 return CurDAG->getTargetConstant(Imm, MVT::i32);
209 }
210
211 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
212 /// base register. Return the virtual register that holds this value.
213 SDNode *getGlobalBaseReg();
214
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000215 /// getTruncate - return an SDNode that implements a subreg based truncate
216 /// of the specified operand to the the specified value type.
217 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
218
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219#ifndef NDEBUG
220 unsigned Indent;
221#endif
222 };
223}
224
225static SDNode *findFlagUse(SDNode *N) {
226 unsigned FlagResNo = N->getNumValues()-1;
227 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
228 SDNode *User = *I;
229 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
230 SDOperand Op = User->getOperand(i);
231 if (Op.Val == N && Op.ResNo == FlagResNo)
232 return User;
233 }
234 }
235 return NULL;
236}
237
238static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
239 SDNode *Root, SDNode *Skip, bool &found,
240 std::set<SDNode *> &Visited) {
241 if (found ||
242 Use->getNodeId() > Def->getNodeId() ||
243 !Visited.insert(Use).second)
244 return;
245
246 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
247 SDNode *N = Use->getOperand(i).Val;
248 if (N == Skip)
249 continue;
250 if (N == Def) {
251 if (Use == ImmedUse)
252 continue; // Immediate use is ok.
253 if (Use == Root) {
254 assert(Use->getOpcode() == ISD::STORE ||
255 Use->getOpcode() == X86ISD::CMP);
256 continue;
257 }
258 found = true;
259 break;
260 }
261 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
262 }
263}
264
265/// isNonImmUse - Start searching from Root up the DAG to check is Def can
266/// be reached. Return true if that's the case. However, ignore direct uses
267/// by ImmedUse (which would be U in the example illustrated in
268/// CanBeFoldedBy) and by Root (which can happen in the store case).
269/// FIXME: to be really generic, we should allow direct use by any node
270/// that is being folded. But realisticly since we only fold loads which
271/// have one non-chain use, we only need to watch out for load/op/store
272/// and load/op/cmp case where the root (store / cmp) may reach the load via
273/// its chain operand.
274static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
275 SDNode *Skip = NULL) {
276 std::set<SDNode *> Visited;
277 bool found = false;
278 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
279 return found;
280}
281
282
Dan Gohmand6098272007-07-24 23:00:27 +0000283bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 if (FastISel) return false;
285
286 // If U use can somehow reach N through another path then U can't fold N or
287 // it will create a cycle. e.g. In the following diagram, U can reach N
288 // through X. If N is folded into into U, then X is both a predecessor and
289 // a successor of U.
290 //
291 // [ N ]
292 // ^ ^
293 // | |
294 // / \---
295 // / [X]
296 // | ^
297 // [U]--------|
298
299 if (isNonImmUse(Root, N, U))
300 return false;
301
302 // If U produces a flag, then it gets (even more) interesting. Since it
303 // would have been "glued" together with its flag use, we need to check if
304 // it might reach N:
305 //
306 // [ N ]
307 // ^ ^
308 // | |
309 // [U] \--
310 // ^ [TF]
311 // | ^
312 // | |
313 // \ /
314 // [FU]
315 //
316 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
317 // NU), then TF is a predecessor of FU and a successor of NU. But since
318 // NU and FU are flagged together, this effectively creates a cycle.
319 bool HasFlagUse = false;
320 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
321 while ((VT == MVT::Flag && !Root->use_empty())) {
322 SDNode *FU = findFlagUse(Root);
323 if (FU == NULL)
324 break;
325 else {
326 Root = FU;
327 HasFlagUse = true;
328 }
329 VT = Root->getValueType(Root->getNumValues()-1);
330 }
331
332 if (HasFlagUse)
333 return !isNonImmUse(Root, N, Root, U);
334 return true;
335}
336
337/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
338/// and move load below the TokenFactor. Replace store's chain operand with
339/// load's chain result.
340static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
341 SDOperand Store, SDOperand TF) {
342 std::vector<SDOperand> Ops;
343 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
344 if (Load.Val == TF.Val->getOperand(i).Val)
345 Ops.push_back(Load.Val->getOperand(0));
346 else
347 Ops.push_back(TF.Val->getOperand(i));
348 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
349 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
350 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
351 Store.getOperand(2), Store.getOperand(3));
352}
353
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000354/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
355/// This is only run if not in -fast mode (aka -O0).
356/// This allows the instruction selector to pick more read-modify-write
357/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358///
359/// [Load chain]
360/// ^
361/// |
362/// [Load]
363/// ^ ^
364/// | |
365/// / \-
366/// / |
367/// [TokenFactor] [Op]
368/// ^ ^
369/// | |
370/// \ /
371/// \ /
372/// [Store]
373///
374/// The fact the store's chain operand != load's chain will prevent the
375/// (store (op (load))) instruction from being selected. We can transform it to:
376///
377/// [Load chain]
378/// ^
379/// |
380/// [TokenFactor]
381/// ^
382/// |
383/// [Load]
384/// ^ ^
385/// | |
386/// | \-
387/// | |
388/// | [Op]
389/// | ^
390/// | |
391/// \ /
392/// \ /
393/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000394void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
396 E = DAG.allnodes_end(); I != E; ++I) {
397 if (!ISD::isNON_TRUNCStore(I))
398 continue;
399 SDOperand Chain = I->getOperand(0);
400 if (Chain.Val->getOpcode() != ISD::TokenFactor)
401 continue;
402
403 SDOperand N1 = I->getOperand(1);
404 SDOperand N2 = I->getOperand(2);
405 if (MVT::isFloatingPoint(N1.getValueType()) ||
406 MVT::isVector(N1.getValueType()) ||
407 !N1.hasOneUse())
408 continue;
409
410 bool RModW = false;
411 SDOperand Load;
412 unsigned Opcode = N1.Val->getOpcode();
413 switch (Opcode) {
414 case ISD::ADD:
415 case ISD::MUL:
416 case ISD::AND:
417 case ISD::OR:
418 case ISD::XOR:
419 case ISD::ADDC:
420 case ISD::ADDE: {
421 SDOperand N10 = N1.getOperand(0);
422 SDOperand N11 = N1.getOperand(1);
423 if (ISD::isNON_EXTLoad(N10.Val))
424 RModW = true;
425 else if (ISD::isNON_EXTLoad(N11.Val)) {
426 RModW = true;
427 std::swap(N10, N11);
428 }
429 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
430 (N10.getOperand(1) == N2) &&
431 (N10.Val->getValueType(0) == N1.getValueType());
432 if (RModW)
433 Load = N10;
434 break;
435 }
436 case ISD::SUB:
437 case ISD::SHL:
438 case ISD::SRA:
439 case ISD::SRL:
440 case ISD::ROTL:
441 case ISD::ROTR:
442 case ISD::SUBC:
443 case ISD::SUBE:
444 case X86ISD::SHLD:
445 case X86ISD::SHRD: {
446 SDOperand N10 = N1.getOperand(0);
447 if (ISD::isNON_EXTLoad(N10.Val))
448 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
449 (N10.getOperand(1) == N2) &&
450 (N10.Val->getValueType(0) == N1.getValueType());
451 if (RModW)
452 Load = N10;
453 break;
454 }
455 }
456
457 if (RModW) {
458 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
459 ++NumLoadMoved;
460 }
461 }
462}
463
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000464
465/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
466/// nodes that target the FP stack to be store and load to the stack. This is a
467/// gross hack. We would like to simply mark these as being illegal, but when
468/// we do that, legalize produces these when it expands calls, then expands
469/// these in the same legalize pass. We would like dag combine to be able to
470/// hack on these between the call expansion and the node legalization. As such
471/// this pass basically does "really late" legalization of these inline with the
472/// X86 isel pass.
473void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
474 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
475 E = DAG.allnodes_end(); I != E; ) {
476 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
477 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
478 continue;
479
480 // If the source and destination are SSE registers, then this is a legal
481 // conversion that should not be lowered.
482 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
483 MVT::ValueType DstVT = N->getValueType(0);
484 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
485 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
486 if (SrcIsSSE && DstIsSSE)
487 continue;
488
489 // If this is an FPStack extension (but not a truncation), it is a noop.
490 if (!SrcIsSSE && !DstIsSSE && N->getOpcode() == ISD::FP_EXTEND)
491 continue;
492
493 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
494 // FPStack has extload and truncstore. SSE can fold direct loads into other
495 // operations. Based on this, decide what we want to do.
496 MVT::ValueType MemVT;
497 if (N->getOpcode() == ISD::FP_ROUND)
498 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
499 else
500 MemVT = SrcIsSSE ? SrcVT : DstVT;
501
502 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
503
504 // FIXME: optimize the case where the src/dest is a load or store?
505 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
506 MemTmp, NULL, 0, MemVT);
507 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
508 NULL, 0, MemVT);
509
510 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
511 // extload we created. This will cause general havok on the dag because
512 // anything below the conversion could be folded into other existing nodes.
513 // To avoid invalidating 'I', back it up to the convert node.
514 --I;
515 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
516
517 // Now that we did that, the node is dead. Increment the iterator to the
518 // next node to process, then delete N.
519 ++I;
520 DAG.DeleteNode(N);
521 }
522}
523
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
525/// when it has created a SelectionDAG for us to codegen.
526void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
527 DEBUG(BB->dump());
528 MachineFunction::iterator FirstMBB = BB;
529
530 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000531 PreprocessForRMW(DAG);
532
533 // FIXME: This should only happen when not -fast.
534 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535
536 // Codegen the basic block.
537#ifndef NDEBUG
538 DOUT << "===== Instruction selection begins:\n";
539 Indent = 0;
540#endif
541 DAG.setRoot(SelectRoot(DAG.getRoot()));
542#ifndef NDEBUG
543 DOUT << "===== Instruction selection ends:\n";
544#endif
545
546 DAG.RemoveDeadNodes();
547
548 // Emit machine code to BB.
549 ScheduleAndEmitDAG(DAG);
550
551 // If we are emitting FP stack code, scan the basic block to determine if this
552 // block defines any FP values. If so, put an FP_REG_KILL instruction before
553 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000554
Dale Johannesen684887e2007-09-24 22:52:39 +0000555 // Note that FP stack instructions are used in all modes for long double,
556 // so we always need to do this check.
557 // Also note that it's possible for an FP stack register to be live across
558 // an instruction that produces multiple basic blocks (SSE CMOV) so we
559 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000560
561 // Scan all of the machine instructions in these MBBs, checking for FP
562 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
563 MachineFunction::iterator MBBI = FirstMBB;
564 do {
Dale Johannesen684887e2007-09-24 22:52:39 +0000565 bool ContainsFPCode = false;
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000566 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
567 !ContainsFPCode && I != E; ++I) {
568 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
569 const TargetRegisterClass *clas;
570 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
571 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000572 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000573 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000574 X86::RFP32RegisterClass ||
575 clas == X86::RFP64RegisterClass ||
576 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 ContainsFPCode = true;
578 break;
579 }
580 }
581 }
582 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000583 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
584 // a copy of the input value in this block. In SSE mode, we only care about
585 // 80-bit values.
586 if (!ContainsFPCode) {
587 // Final check, check LLVM BB's that are successors to the LLVM BB
588 // corresponding to BB for FP PHI nodes.
589 const BasicBlock *LLVMBB = BB->getBasicBlock();
590 const PHINode *PN;
591 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
592 !ContainsFPCode && SI != E; ++SI) {
593 for (BasicBlock::const_iterator II = SI->begin();
594 (PN = dyn_cast<PHINode>(II)); ++II) {
595 if (PN->getType()==Type::X86_FP80Ty ||
596 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
597 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
598 ContainsFPCode = true;
599 break;
600 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000601 }
602 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000604 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
605 if (ContainsFPCode) {
606 BuildMI(*MBBI, MBBI->getFirstTerminator(),
607 TM.getInstrInfo()->get(X86::FP_REG_KILL));
608 ++NumFPKill;
609 }
610 } while (&*(MBBI++) != BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611}
612
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000613/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
614/// the main function.
615void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
616 MachineFrameInfo *MFI) {
617 const TargetInstrInfo *TII = TM.getInstrInfo();
618 if (Subtarget->isTargetCygMing())
619 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
620}
621
622void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
623 // If this is main, emit special code for main.
624 MachineBasicBlock *BB = MF.begin();
625 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
626 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
627}
628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629/// MatchAddress - Add the specified node to the specified addressing mode,
630/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000631/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
633 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000634 // Limit recursion.
635 if (Depth > 5)
636 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637
638 // RIP relative addressing: %rip + 32-bit displacement!
639 if (AM.isRIPRel) {
640 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
641 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
642 if (isInt32(AM.Disp + Val)) {
643 AM.Disp += Val;
644 return false;
645 }
646 }
647 return true;
648 }
649
650 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000651 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652
653 switch (N.getOpcode()) {
654 default: break;
655 case ISD::Constant: {
656 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
657 if (isInt32(AM.Disp + Val)) {
658 AM.Disp += Val;
659 return false;
660 }
661 break;
662 }
663
664 case X86ISD::Wrapper: {
665 bool is64Bit = Subtarget->is64Bit();
666 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000667 // Also, base and index reg must be 0 in order to use rip as base.
668 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
669 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 break;
671 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
672 break;
673 // If value is available in a register both base and index components have
674 // been picked, we can't fit the result available in the register in the
675 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000676 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 SDOperand N0 = N.getOperand(0);
678 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
679 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000680 AM.GV = GV;
681 AM.Disp += G->getOffset();
682 AM.isRIPRel = is64Bit;
683 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000685 AM.CP = CP->getConstVal();
686 AM.Align = CP->getAlignment();
687 AM.Disp += CP->getOffset();
688 AM.isRIPRel = is64Bit;
689 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000691 AM.ES = S->getSymbol();
692 AM.isRIPRel = is64Bit;
693 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000695 AM.JT = J->getIndex();
696 AM.isRIPRel = is64Bit;
697 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 }
699 }
700 break;
701 }
702
703 case ISD::FrameIndex:
704 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
705 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
706 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
707 return false;
708 }
709 break;
710
711 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000712 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000713 break;
714
715 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
716 unsigned Val = CN->getValue();
717 if (Val == 1 || Val == 2 || Val == 3) {
718 AM.Scale = 1 << Val;
719 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720
Chris Lattner7f06edd2007-12-08 07:22:58 +0000721 // Okay, we know that we have a scale by now. However, if the scaled
722 // value is an add of something and a constant, we can fold the
723 // constant into the disp field here.
724 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
725 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
726 AM.IndexReg = ShVal.Val->getOperand(0);
727 ConstantSDNode *AddVal =
728 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
729 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
730 if (isInt32(Disp))
731 AM.Disp = Disp;
732 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000734 } else {
735 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000737 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 }
739 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000740 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741
Dan Gohman35b99222007-10-22 20:22:24 +0000742 case ISD::SMUL_LOHI:
743 case ISD::UMUL_LOHI:
744 // A mul_lohi where we need the low part can be folded as a plain multiply.
745 if (N.ResNo != 0) break;
746 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 case ISD::MUL:
748 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000749 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 AM.BaseType == X86ISelAddressMode::RegBase &&
751 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000752 AM.IndexReg.Val == 0 &&
753 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
755 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
756 AM.Scale = unsigned(CN->getValue())-1;
757
758 SDOperand MulVal = N.Val->getOperand(0);
759 SDOperand Reg;
760
761 // Okay, we know that we have a scale by now. However, if the scaled
762 // value is an add of something and a constant, we can fold the
763 // constant into the disp field here.
764 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
765 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
766 Reg = MulVal.Val->getOperand(0);
767 ConstantSDNode *AddVal =
768 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
769 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
770 if (isInt32(Disp))
771 AM.Disp = Disp;
772 else
773 Reg = N.Val->getOperand(0);
774 } else {
775 Reg = N.Val->getOperand(0);
776 }
777
778 AM.IndexReg = AM.Base.Reg = Reg;
779 return false;
780 }
781 }
782 break;
783
784 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000785 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 X86ISelAddressMode Backup = AM;
787 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
788 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
789 return false;
790 AM = Backup;
791 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
792 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
793 return false;
794 AM = Backup;
795 }
796 break;
797
798 case ISD::OR:
799 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000800 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000801
802 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
803 X86ISelAddressMode Backup = AM;
804 // Start with the LHS as an addr mode.
805 if (!MatchAddress(N.getOperand(0), AM, false) &&
806 // Address could not have picked a GV address for the displacement.
807 AM.GV == NULL &&
808 // On x86-64, the resultant disp must fit in 32-bits.
809 isInt32(AM.Disp + CN->getSignExtended()) &&
810 // Check to see if the LHS & C is zero.
811 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
812 AM.Disp += CN->getValue();
813 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000815 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 }
817 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000818
819 case ISD::AND: {
820 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
821 // allows us to fold the shift into this addressing mode.
822 if (AlreadySelected) break;
823 SDOperand Shift = N.getOperand(0);
824 if (Shift.getOpcode() != ISD::SHL) break;
825
826 // Scale must not be used already.
827 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000828
829 // Not when RIP is used as the base.
830 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000831
832 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
833 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
834 if (!C1 || !C2) break;
835
836 // Not likely to be profitable if either the AND or SHIFT node has more
837 // than one use (unless all uses are for address computation). Besides,
838 // isel mechanism requires their node ids to be reused.
839 if (!N.hasOneUse() || !Shift.hasOneUse())
840 break;
841
842 // Verify that the shift amount is something we can fold.
843 unsigned ShiftCst = C1->getValue();
844 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
845 break;
846
847 // Get the new AND mask, this folds to a constant.
848 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
849 SDOperand(C2, 0), SDOperand(C1, 0));
850 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
851 Shift.getOperand(0), NewANDMask);
852 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
853 NewAND.Val->setNodeId(N.Val->getNodeId());
854
855 AM.Scale = 1 << ShiftCst;
856 AM.IndexReg = NewAND;
857 return false;
858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 }
860
Dan Gohmana60c1b32007-08-13 20:03:06 +0000861 return MatchAddressBase(N, AM, isRoot, Depth);
862}
863
864/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
865/// specified addressing mode without any further recursion.
866bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
867 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 // Is the base register already occupied?
869 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
870 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000871 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 AM.IndexReg = N;
873 AM.Scale = 1;
874 return false;
875 }
876
877 // Otherwise, we cannot select it.
878 return true;
879 }
880
881 // Default, generate it as a register.
882 AM.BaseType = X86ISelAddressMode::RegBase;
883 AM.Base.Reg = N;
884 return false;
885}
886
887/// SelectAddr - returns true if it is able pattern match an addressing mode.
888/// It returns the operands which make up the maximal addressing mode it can
889/// match by reference.
890bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
891 SDOperand &Scale, SDOperand &Index,
892 SDOperand &Disp) {
893 X86ISelAddressMode AM;
894 if (MatchAddress(N, AM))
895 return false;
896
897 MVT::ValueType VT = N.getValueType();
898 if (AM.BaseType == X86ISelAddressMode::RegBase) {
899 if (!AM.Base.Reg.Val)
900 AM.Base.Reg = CurDAG->getRegister(0, VT);
901 }
902
903 if (!AM.IndexReg.Val)
904 AM.IndexReg = CurDAG->getRegister(0, VT);
905
906 getAddressOperands(AM, Base, Scale, Index, Disp);
907 return true;
908}
909
910/// isZeroNode - Returns true if Elt is a constant zero or a floating point
911/// constant +0.0.
912static inline bool isZeroNode(SDOperand Elt) {
913 return ((isa<ConstantSDNode>(Elt) &&
914 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
915 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000916 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917}
918
919
920/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
921/// match a load whose top elements are either undef or zeros. The load flavor
922/// is derived from the type of N, which is either v4f32 or v2f64.
923bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
924 SDOperand N, SDOperand &Base,
925 SDOperand &Scale, SDOperand &Index,
926 SDOperand &Disp, SDOperand &InChain,
927 SDOperand &OutChain) {
928 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
929 InChain = N.getOperand(0).getValue(1);
930 if (ISD::isNON_EXTLoad(InChain.Val) &&
931 InChain.getValue(0).hasOneUse() &&
932 N.hasOneUse() &&
933 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
934 LoadSDNode *LD = cast<LoadSDNode>(InChain);
935 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
936 return false;
937 OutChain = LD->getChain();
938 return true;
939 }
940 }
941
942 // Also handle the case where we explicitly require zeros in the top
943 // elements. This is a vector shuffle from the zero vector.
944 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000945 // Check to see if the top elements are all zeros (or bitcast of zeros).
946 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
948 N.getOperand(1).Val->hasOneUse() &&
949 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
950 N.getOperand(1).getOperand(0).hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
952 // from the LHS.
Chris Lattnere6aa3862007-11-25 00:24:49 +0000953 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 SDOperand ShufMask = N.getOperand(2);
955 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
957 if (C->getValue() == VecWidth) {
958 for (unsigned i = 1; i != VecWidth; ++i) {
959 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
960 // ok.
961 } else {
962 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
963 if (C->getValue() >= VecWidth) return false;
964 }
965 }
966 }
967
968 // Okay, this is a zero extending load. Fold it.
969 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
970 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
971 return false;
972 OutChain = LD->getChain();
973 InChain = SDOperand(LD, 1);
974 return true;
975 }
976 }
977 return false;
978}
979
980
981/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
982/// mode it matches can be cost effectively emitted as an LEA instruction.
983bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
984 SDOperand &Base, SDOperand &Scale,
985 SDOperand &Index, SDOperand &Disp) {
986 X86ISelAddressMode AM;
987 if (MatchAddress(N, AM))
988 return false;
989
990 MVT::ValueType VT = N.getValueType();
991 unsigned Complexity = 0;
992 if (AM.BaseType == X86ISelAddressMode::RegBase)
993 if (AM.Base.Reg.Val)
994 Complexity = 1;
995 else
996 AM.Base.Reg = CurDAG->getRegister(0, VT);
997 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
998 Complexity = 4;
999
1000 if (AM.IndexReg.Val)
1001 Complexity++;
1002 else
1003 AM.IndexReg = CurDAG->getRegister(0, VT);
1004
1005 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1006 // a simple shift.
1007 if (AM.Scale > 1)
1008 Complexity++;
1009
1010 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1011 // to a LEA. This is determined with some expermentation but is by no means
1012 // optimal (especially for code size consideration). LEA is nice because of
1013 // its three-address nature. Tweak the cost function again when we can run
1014 // convertToThreeAddress() at register allocation time.
1015 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1016 // For X86-64, we should always use lea to materialize RIP relative
1017 // addresses.
1018 if (Subtarget->is64Bit())
1019 Complexity = 4;
1020 else
1021 Complexity += 2;
1022 }
1023
1024 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1025 Complexity++;
1026
1027 if (Complexity > 2) {
1028 getAddressOperands(AM, Base, Scale, Index, Disp);
1029 return true;
1030 }
1031 return false;
1032}
1033
1034bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1035 SDOperand &Base, SDOperand &Scale,
1036 SDOperand &Index, SDOperand &Disp) {
1037 if (ISD::isNON_EXTLoad(N.Val) &&
1038 N.hasOneUse() &&
1039 CanBeFoldedBy(N.Val, P.Val, P.Val))
1040 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1041 return false;
1042}
1043
1044/// getGlobalBaseReg - Output the instructions required to put the
1045/// base address to use for accessing globals into a register.
1046///
1047SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1048 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1049 if (!GlobalBaseReg) {
1050 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001051 MachineFunction *MF = BB->getParent();
1052 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001054 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001055 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056
1057 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001058 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1059 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001060 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
1062 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1063 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1064 if (TM.getRelocationModel() == Reloc::PIC_ &&
1065 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001066 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001067 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1068 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 } else {
1070 GlobalBaseReg = PC;
1071 }
1072
1073 }
1074 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1075}
1076
1077static SDNode *FindCallStartFromCall(SDNode *Node) {
1078 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1079 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1080 "Node doesn't have a token chain argument!");
1081 return FindCallStartFromCall(Node->getOperand(0).Val);
1082}
1083
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001084SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1085 SDOperand SRIdx;
1086 switch (VT) {
1087 case MVT::i8:
1088 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1089 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1090 if (!Subtarget->is64Bit()) {
1091 unsigned Opc;
1092 MVT::ValueType VT;
1093 switch (N0.getValueType()) {
1094 default: assert(0 && "Unknown truncate!");
1095 case MVT::i16:
1096 Opc = X86::MOV16to16_;
1097 VT = MVT::i16;
1098 break;
1099 case MVT::i32:
1100 Opc = X86::MOV32to32_;
1101 VT = MVT::i32;
1102 break;
1103 }
Evan Chenge1f39552007-10-12 07:55:53 +00001104 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1105 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1106 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001107 }
1108 break;
1109 case MVT::i16:
1110 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1111 break;
1112 case MVT::i32:
1113 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1114 break;
Evan Chenge1f39552007-10-12 07:55:53 +00001115 default: assert(0 && "Unknown truncate!"); break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001116 }
Evan Chenge1f39552007-10-12 07:55:53 +00001117 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001118}
1119
1120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1122 SDNode *Node = N.Val;
1123 MVT::ValueType NVT = Node->getValueType(0);
1124 unsigned Opc, MOpc;
1125 unsigned Opcode = Node->getOpcode();
1126
1127#ifndef NDEBUG
1128 DOUT << std::string(Indent, ' ') << "Selecting: ";
1129 DEBUG(Node->dump(CurDAG));
1130 DOUT << "\n";
1131 Indent += 2;
1132#endif
1133
1134 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1135#ifndef NDEBUG
1136 DOUT << std::string(Indent-2, ' ') << "== ";
1137 DEBUG(Node->dump(CurDAG));
1138 DOUT << "\n";
1139 Indent -= 2;
1140#endif
1141 return NULL; // Already selected.
1142 }
1143
1144 switch (Opcode) {
1145 default: break;
1146 case X86ISD::GlobalBaseReg:
1147 return getGlobalBaseReg();
1148
Evan Cheng931a8f42008-01-29 19:34:22 +00001149 case X86ISD::FP_GET_RESULT2: {
1150 SDOperand Chain = N.getOperand(0);
1151 SDOperand InFlag = N.getOperand(1);
1152 AddToISelQueue(Chain);
1153 AddToISelQueue(InFlag);
1154 std::vector<MVT::ValueType> Tys;
1155 Tys.push_back(MVT::f80);
1156 Tys.push_back(MVT::f80);
1157 Tys.push_back(MVT::Other);
1158 Tys.push_back(MVT::Flag);
1159 SDOperand Ops[] = { Chain, InFlag };
1160 SDNode *ResNode = CurDAG->getTargetNode(X86::FpGETRESULT80x2, Tys,
1161 Ops, 2);
1162 Chain = SDOperand(ResNode, 2);
1163 InFlag = SDOperand(ResNode, 3);
1164 ReplaceUses(SDOperand(N.Val, 2), Chain);
1165 ReplaceUses(SDOperand(N.Val, 3), InFlag);
1166 return ResNode;
1167 }
1168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 case ISD::ADD: {
1170 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1171 // code and is matched first so to prevent it from being turned into
1172 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001173 // In 64-bit small code size mode, use LEA to take advantage of
1174 // RIP-relative addressing.
1175 if (TM.getCodeModel() != CodeModel::Small)
1176 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177 MVT::ValueType PtrVT = TLI.getPointerTy();
1178 SDOperand N0 = N.getOperand(0);
1179 SDOperand N1 = N.getOperand(1);
1180 if (N.Val->getValueType(0) == PtrVT &&
1181 N0.getOpcode() == X86ISD::Wrapper &&
1182 N1.getOpcode() == ISD::Constant) {
1183 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1184 SDOperand C(0, 0);
1185 // TODO: handle ExternalSymbolSDNode.
1186 if (GlobalAddressSDNode *G =
1187 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1188 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1189 G->getOffset() + Offset);
1190 } else if (ConstantPoolSDNode *CP =
1191 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1192 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1193 CP->getAlignment(),
1194 CP->getOffset()+Offset);
1195 }
1196
1197 if (C.Val) {
1198 if (Subtarget->is64Bit()) {
1199 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1200 CurDAG->getRegister(0, PtrVT), C };
1201 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1202 } else
1203 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1204 }
1205 }
1206
1207 // Other cases are handled by auto-generated code.
1208 break;
1209 }
1210
Dan Gohman5a199552007-10-08 18:33:35 +00001211 case ISD::SMUL_LOHI:
1212 case ISD::UMUL_LOHI: {
1213 SDOperand N0 = Node->getOperand(0);
1214 SDOperand N1 = Node->getOperand(1);
1215
Dan Gohmana5685ba2007-10-09 15:44:37 +00001216 // There are several forms of IMUL that just return the low part and
1217 // don't have fixed-register operands. If we don't need the high part,
1218 // use these instead. They can be selected with the generated ISel code.
Dan Gohman5a199552007-10-08 18:33:35 +00001219 if (NVT != MVT::i8 &&
1220 N.getValue(1).use_empty()) {
1221 N = CurDAG->getNode(ISD::MUL, NVT, N0, N1);
1222 break;
1223 }
1224
1225 bool isSigned = Opcode == ISD::SMUL_LOHI;
1226 if (!isSigned)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 switch (NVT) {
1228 default: assert(0 && "Unsupported VT!");
1229 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1230 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1231 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1232 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1233 }
1234 else
1235 switch (NVT) {
1236 default: assert(0 && "Unsupported VT!");
1237 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1238 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1239 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1240 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1241 }
1242
1243 unsigned LoReg, HiReg;
1244 switch (NVT) {
1245 default: assert(0 && "Unsupported VT!");
1246 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1247 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1248 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1249 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1250 }
1251
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001253 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001254 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 if (!foldedLoad) {
1256 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001257 if (foldedLoad)
1258 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 }
1260
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001262 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1263 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264
1265 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001266 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 AddToISelQueue(Tmp0);
1268 AddToISelQueue(Tmp1);
1269 AddToISelQueue(Tmp2);
1270 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001271 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 SDNode *CNode =
1273 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001275 // Update the chain.
1276 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 } else {
1278 AddToISelQueue(N1);
1279 InFlag =
1280 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1281 }
1282
Dan Gohman5a199552007-10-08 18:33:35 +00001283 // Copy the low half of the result, if it is needed.
1284 if (!N.getValue(0).use_empty()) {
1285 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1286 LoReg, NVT, InFlag);
1287 InFlag = Result.getValue(2);
1288 ReplaceUses(N.getValue(0), Result);
1289#ifndef NDEBUG
1290 DOUT << std::string(Indent-2, ' ') << "=> ";
1291 DEBUG(Result.Val->dump(CurDAG));
1292 DOUT << "\n";
1293#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001294 }
Dan Gohman5a199552007-10-08 18:33:35 +00001295 // Copy the high half of the result, if it is needed.
1296 if (!N.getValue(1).use_empty()) {
1297 SDOperand Result;
1298 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1299 // Prevent use of AH in a REX instruction by referencing AX instead.
1300 // Shift it down 8 bits.
1301 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1302 X86::AX, MVT::i16, InFlag);
1303 InFlag = Result.getValue(2);
1304 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1305 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1306 // Then truncate it down to i8.
1307 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1308 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1309 MVT::i8, Result, SRIdx), 0);
1310 } else {
1311 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1312 HiReg, NVT, InFlag);
1313 InFlag = Result.getValue(2);
1314 }
1315 ReplaceUses(N.getValue(1), Result);
1316#ifndef NDEBUG
1317 DOUT << std::string(Indent-2, ' ') << "=> ";
1318 DEBUG(Result.Val->dump(CurDAG));
1319 DOUT << "\n";
1320#endif
1321 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322
1323#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 Indent -= 2;
1325#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001326
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 return NULL;
1328 }
1329
Dan Gohman5a199552007-10-08 18:33:35 +00001330 case ISD::SDIVREM:
1331 case ISD::UDIVREM: {
1332 SDOperand N0 = Node->getOperand(0);
1333 SDOperand N1 = Node->getOperand(1);
1334
1335 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 if (!isSigned)
1337 switch (NVT) {
1338 default: assert(0 && "Unsupported VT!");
1339 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1340 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1341 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1342 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1343 }
1344 else
1345 switch (NVT) {
1346 default: assert(0 && "Unsupported VT!");
1347 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1348 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1349 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1350 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1351 }
1352
1353 unsigned LoReg, HiReg;
1354 unsigned ClrOpcode, SExtOpcode;
1355 switch (NVT) {
1356 default: assert(0 && "Unsupported VT!");
1357 case MVT::i8:
1358 LoReg = X86::AL; HiReg = X86::AH;
1359 ClrOpcode = 0;
1360 SExtOpcode = X86::CBW;
1361 break;
1362 case MVT::i16:
1363 LoReg = X86::AX; HiReg = X86::DX;
1364 ClrOpcode = X86::MOV16r0;
1365 SExtOpcode = X86::CWD;
1366 break;
1367 case MVT::i32:
1368 LoReg = X86::EAX; HiReg = X86::EDX;
1369 ClrOpcode = X86::MOV32r0;
1370 SExtOpcode = X86::CDQ;
1371 break;
1372 case MVT::i64:
1373 LoReg = X86::RAX; HiReg = X86::RDX;
1374 ClrOpcode = X86::MOV64r0;
1375 SExtOpcode = X86::CQO;
1376 break;
1377 }
1378
Dan Gohman5a199552007-10-08 18:33:35 +00001379 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1380 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1381
1382 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 if (NVT == MVT::i8 && !isSigned) {
1384 // Special case for div8, just use a move with zero extension to AX to
1385 // clear the upper 8 bits (AH).
1386 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1387 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1388 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1389 AddToISelQueue(N0.getOperand(0));
1390 AddToISelQueue(Tmp0);
1391 AddToISelQueue(Tmp1);
1392 AddToISelQueue(Tmp2);
1393 AddToISelQueue(Tmp3);
1394 Move =
1395 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1396 Ops, 5), 0);
1397 Chain = Move.getValue(1);
1398 ReplaceUses(N0.getValue(1), Chain);
1399 } else {
1400 AddToISelQueue(N0);
1401 Move =
1402 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1403 Chain = CurDAG->getEntryNode();
1404 }
Dan Gohman5a199552007-10-08 18:33:35 +00001405 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 InFlag = Chain.getValue(1);
1407 } else {
1408 AddToISelQueue(N0);
1409 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001410 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1411 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 if (isSigned) {
1413 // Sign extend the low part into the high part.
1414 InFlag =
1415 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1416 } else {
1417 // Zero out the high part, effectively zero extending the input.
1418 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001419 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1420 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 }
1422 }
1423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 if (foldedLoad) {
1425 AddToISelQueue(N1.getOperand(0));
1426 AddToISelQueue(Tmp0);
1427 AddToISelQueue(Tmp1);
1428 AddToISelQueue(Tmp2);
1429 AddToISelQueue(Tmp3);
1430 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1431 SDNode *CNode =
1432 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001434 // Update the chain.
1435 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 } else {
1437 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 InFlag =
1439 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1440 }
1441
Dan Gohman242a5ba2007-09-25 18:23:27 +00001442 // Copy the division (low) result, if it is needed.
1443 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001444 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1445 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001446 InFlag = Result.getValue(2);
1447 ReplaceUses(N.getValue(0), Result);
1448#ifndef NDEBUG
1449 DOUT << std::string(Indent-2, ' ') << "=> ";
1450 DEBUG(Result.Val->dump(CurDAG));
1451 DOUT << "\n";
1452#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001453 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001454 // Copy the remainder (high) result, if it is needed.
1455 if (!N.getValue(1).use_empty()) {
1456 SDOperand Result;
1457 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1458 // Prevent use of AH in a REX instruction by referencing AX instead.
1459 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001460 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1461 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001462 InFlag = Result.getValue(2);
1463 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1464 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1465 // Then truncate it down to i8.
1466 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1467 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1468 MVT::i8, Result, SRIdx), 0);
1469 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001470 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1471 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001472 InFlag = Result.getValue(2);
1473 }
1474 ReplaceUses(N.getValue(1), Result);
1475#ifndef NDEBUG
1476 DOUT << std::string(Indent-2, ' ') << "=> ";
1477 DEBUG(Result.Val->dump(CurDAG));
1478 DOUT << "\n";
1479#endif
1480 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001481
1482#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 Indent -= 2;
1484#endif
1485
1486 return NULL;
1487 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001488
1489 case ISD::ANY_EXTEND: {
1490 SDOperand N0 = Node->getOperand(0);
1491 AddToISelQueue(N0);
1492 if (NVT == MVT::i64 || NVT == MVT::i32 || NVT == MVT::i16) {
1493 SDOperand SRIdx;
1494 switch(N0.getValueType()) {
1495 case MVT::i32:
1496 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1497 break;
1498 case MVT::i16:
1499 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1500 break;
1501 case MVT::i8:
1502 if (Subtarget->is64Bit())
1503 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1504 break;
1505 default: assert(0 && "Unknown any_extend!");
1506 }
1507 if (SRIdx.Val) {
Evan Chenge1f39552007-10-12 07:55:53 +00001508 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1509 NVT, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001510
1511#ifndef NDEBUG
1512 DOUT << std::string(Indent-2, ' ') << "=> ";
1513 DEBUG(ResNode->dump(CurDAG));
1514 DOUT << "\n";
1515 Indent -= 2;
1516#endif
1517 return ResNode;
1518 } // Otherwise let generated ISel handle it.
1519 }
1520 break;
1521 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001522
1523 case ISD::SIGN_EXTEND_INREG: {
1524 SDOperand N0 = Node->getOperand(0);
1525 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001527 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1528 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001529 unsigned Opc = 0;
Christopher Lamb444336c2007-07-29 01:24:57 +00001530 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001531 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001532 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1533 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001534 break;
1535 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001536 switch (SVT) {
1537 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1538 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1539 default: assert(0 && "Unknown sign_extend_inreg!");
1540 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001541 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001542 case MVT::i64:
1543 switch (SVT) {
1544 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1545 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1546 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1547 default: assert(0 && "Unknown sign_extend_inreg!");
1548 }
1549 break;
1550 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001551 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001552
1553 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1554
1555#ifndef NDEBUG
1556 DOUT << std::string(Indent-2, ' ') << "=> ";
1557 DEBUG(TruncOp.Val->dump(CurDAG));
1558 DOUT << "\n";
1559 DOUT << std::string(Indent-2, ' ') << "=> ";
1560 DEBUG(ResNode->dump(CurDAG));
1561 DOUT << "\n";
1562 Indent -= 2;
1563#endif
1564 return ResNode;
1565 break;
1566 }
1567
1568 case ISD::TRUNCATE: {
1569 SDOperand Input = Node->getOperand(0);
1570 AddToISelQueue(Node->getOperand(0));
1571 SDNode *ResNode = getTruncate(Input, NVT);
1572
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001573#ifndef NDEBUG
1574 DOUT << std::string(Indent-2, ' ') << "=> ";
1575 DEBUG(ResNode->dump(CurDAG));
1576 DOUT << "\n";
1577 Indent -= 2;
1578#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001579 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 break;
1581 }
1582 }
1583
1584 SDNode *ResNode = SelectCode(N);
1585
1586#ifndef NDEBUG
1587 DOUT << std::string(Indent-2, ' ') << "=> ";
1588 if (ResNode == NULL || ResNode == N.Val)
1589 DEBUG(N.Val->dump(CurDAG));
1590 else
1591 DEBUG(ResNode->dump(CurDAG));
1592 DOUT << "\n";
1593 Indent -= 2;
1594#endif
1595
1596 return ResNode;
1597}
1598
1599bool X86DAGToDAGISel::
1600SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1601 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1602 SDOperand Op0, Op1, Op2, Op3;
1603 switch (ConstraintCode) {
1604 case 'o': // offsetable ??
1605 case 'v': // not offsetable ??
1606 default: return true;
1607 case 'm': // memory
1608 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1609 return true;
1610 break;
1611 }
1612
1613 OutOps.push_back(Op0);
1614 OutOps.push_back(Op1);
1615 OutOps.push_back(Op2);
1616 OutOps.push_back(Op3);
1617 AddToISelQueue(Op0);
1618 AddToISelQueue(Op1);
1619 AddToISelQueue(Op2);
1620 AddToISelQueue(Op3);
1621 return false;
1622}
1623
1624/// createX86ISelDag - This pass converts a legalized DAG into a
1625/// X86-specific DAG, ready for instruction scheduling.
1626///
1627FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1628 return new X86DAGToDAGISel(TM, Fast);
1629}