blob: 9bf9d122637c0d82178fbb5a7d4732f2937bee50 [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"
Evan Chengd5bf2ca2008-02-19 23:36:51 +000035#include "llvm/Support/CommandLine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/MathExtras.h"
39#include "llvm/ADT/Statistic.h"
40#include <queue>
41#include <set>
42using namespace llvm;
43
44STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
45STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047//===----------------------------------------------------------------------===//
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) {
Roman Levenstein05650fd2008-04-07 10:06:32 +0000228 SDNode *User = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 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 ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000255 Use->getOpcode() == X86ISD::CMP ||
256 Use->getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
257 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
258 Use->getOpcode() == ISD::INTRINSIC_VOID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 continue;
260 }
261 found = true;
262 break;
263 }
264 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
265 }
266}
267
268/// isNonImmUse - Start searching from Root up the DAG to check is Def can
269/// be reached. Return true if that's the case. However, ignore direct uses
270/// by ImmedUse (which would be U in the example illustrated in
271/// CanBeFoldedBy) and by Root (which can happen in the store case).
272/// FIXME: to be really generic, we should allow direct use by any node
273/// that is being folded. But realisticly since we only fold loads which
274/// have one non-chain use, we only need to watch out for load/op/store
275/// and load/op/cmp case where the root (store / cmp) may reach the load via
276/// its chain operand.
277static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
278 SDNode *Skip = NULL) {
279 std::set<SDNode *> Visited;
280 bool found = false;
281 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
282 return found;
283}
284
285
Dan Gohmand6098272007-07-24 23:00:27 +0000286bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 if (FastISel) return false;
288
289 // If U use can somehow reach N through another path then U can't fold N or
290 // it will create a cycle. e.g. In the following diagram, U can reach N
291 // through X. If N is folded into into U, then X is both a predecessor and
292 // a successor of U.
293 //
294 // [ N ]
295 // ^ ^
296 // | |
297 // / \---
298 // / [X]
299 // | ^
300 // [U]--------|
301
302 if (isNonImmUse(Root, N, U))
303 return false;
304
305 // If U produces a flag, then it gets (even more) interesting. Since it
306 // would have been "glued" together with its flag use, we need to check if
307 // it might reach N:
308 //
309 // [ N ]
310 // ^ ^
311 // | |
312 // [U] \--
313 // ^ [TF]
314 // | ^
315 // | |
316 // \ /
317 // [FU]
318 //
319 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
320 // NU), then TF is a predecessor of FU and a successor of NU. But since
321 // NU and FU are flagged together, this effectively creates a cycle.
322 bool HasFlagUse = false;
323 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
324 while ((VT == MVT::Flag && !Root->use_empty())) {
325 SDNode *FU = findFlagUse(Root);
326 if (FU == NULL)
327 break;
328 else {
329 Root = FU;
330 HasFlagUse = true;
331 }
332 VT = Root->getValueType(Root->getNumValues()-1);
333 }
334
335 if (HasFlagUse)
336 return !isNonImmUse(Root, N, Root, U);
337 return true;
338}
339
340/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
341/// and move load below the TokenFactor. Replace store's chain operand with
342/// load's chain result.
343static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
344 SDOperand Store, SDOperand TF) {
345 std::vector<SDOperand> Ops;
346 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
347 if (Load.Val == TF.Val->getOperand(i).Val)
348 Ops.push_back(Load.Val->getOperand(0));
349 else
350 Ops.push_back(TF.Val->getOperand(i));
351 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
352 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
353 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
354 Store.getOperand(2), Store.getOperand(3));
355}
356
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000357/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
358/// This is only run if not in -fast mode (aka -O0).
359/// This allows the instruction selector to pick more read-modify-write
360/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361///
362/// [Load chain]
363/// ^
364/// |
365/// [Load]
366/// ^ ^
367/// | |
368/// / \-
369/// / |
370/// [TokenFactor] [Op]
371/// ^ ^
372/// | |
373/// \ /
374/// \ /
375/// [Store]
376///
377/// The fact the store's chain operand != load's chain will prevent the
378/// (store (op (load))) instruction from being selected. We can transform it to:
379///
380/// [Load chain]
381/// ^
382/// |
383/// [TokenFactor]
384/// ^
385/// |
386/// [Load]
387/// ^ ^
388/// | |
389/// | \-
390/// | |
391/// | [Op]
392/// | ^
393/// | |
394/// \ /
395/// \ /
396/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000397void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
399 E = DAG.allnodes_end(); I != E; ++I) {
400 if (!ISD::isNON_TRUNCStore(I))
401 continue;
402 SDOperand Chain = I->getOperand(0);
403 if (Chain.Val->getOpcode() != ISD::TokenFactor)
404 continue;
405
406 SDOperand N1 = I->getOperand(1);
407 SDOperand N2 = I->getOperand(2);
408 if (MVT::isFloatingPoint(N1.getValueType()) ||
409 MVT::isVector(N1.getValueType()) ||
410 !N1.hasOneUse())
411 continue;
412
413 bool RModW = false;
414 SDOperand Load;
415 unsigned Opcode = N1.Val->getOpcode();
416 switch (Opcode) {
417 case ISD::ADD:
418 case ISD::MUL:
419 case ISD::AND:
420 case ISD::OR:
421 case ISD::XOR:
422 case ISD::ADDC:
423 case ISD::ADDE: {
424 SDOperand N10 = N1.getOperand(0);
425 SDOperand N11 = N1.getOperand(1);
426 if (ISD::isNON_EXTLoad(N10.Val))
427 RModW = true;
428 else if (ISD::isNON_EXTLoad(N11.Val)) {
429 RModW = true;
430 std::swap(N10, N11);
431 }
Evan Cheng9123cfa2008-03-04 00:40:35 +0000432 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 (N10.getOperand(1) == N2) &&
434 (N10.Val->getValueType(0) == N1.getValueType());
435 if (RModW)
436 Load = N10;
437 break;
438 }
439 case ISD::SUB:
440 case ISD::SHL:
441 case ISD::SRA:
442 case ISD::SRL:
443 case ISD::ROTL:
444 case ISD::ROTR:
445 case ISD::SUBC:
446 case ISD::SUBE:
447 case X86ISD::SHLD:
448 case X86ISD::SHRD: {
449 SDOperand N10 = N1.getOperand(0);
450 if (ISD::isNON_EXTLoad(N10.Val))
Evan Cheng9123cfa2008-03-04 00:40:35 +0000451 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 (N10.getOperand(1) == N2) &&
453 (N10.Val->getValueType(0) == N1.getValueType());
454 if (RModW)
455 Load = N10;
456 break;
457 }
458 }
459
460 if (RModW) {
461 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
462 ++NumLoadMoved;
463 }
464 }
465}
466
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000467
468/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
469/// nodes that target the FP stack to be store and load to the stack. This is a
470/// gross hack. We would like to simply mark these as being illegal, but when
471/// we do that, legalize produces these when it expands calls, then expands
472/// these in the same legalize pass. We would like dag combine to be able to
473/// hack on these between the call expansion and the node legalization. As such
474/// this pass basically does "really late" legalization of these inline with the
475/// X86 isel pass.
476void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
477 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
478 E = DAG.allnodes_end(); I != E; ) {
479 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
480 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
481 continue;
482
483 // If the source and destination are SSE registers, then this is a legal
484 // conversion that should not be lowered.
485 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
486 MVT::ValueType DstVT = N->getValueType(0);
487 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
488 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
489 if (SrcIsSSE && DstIsSSE)
490 continue;
491
Chris Lattner5d294e52008-03-09 07:05:32 +0000492 if (!SrcIsSSE && !DstIsSSE) {
493 // If this is an FPStack extension, it is a noop.
494 if (N->getOpcode() == ISD::FP_EXTEND)
495 continue;
496 // If this is a value-preserving FPStack truncation, it is a noop.
497 if (N->getConstantOperandVal(1))
498 continue;
499 }
500
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000501 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
502 // FPStack has extload and truncstore. SSE can fold direct loads into other
503 // operations. Based on this, decide what we want to do.
504 MVT::ValueType MemVT;
505 if (N->getOpcode() == ISD::FP_ROUND)
506 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
507 else
508 MemVT = SrcIsSSE ? SrcVT : DstVT;
509
510 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
511
512 // FIXME: optimize the case where the src/dest is a load or store?
513 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
514 MemTmp, NULL, 0, MemVT);
515 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
516 NULL, 0, MemVT);
517
518 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
519 // extload we created. This will cause general havok on the dag because
520 // anything below the conversion could be folded into other existing nodes.
521 // To avoid invalidating 'I', back it up to the convert node.
522 --I;
523 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
524
525 // Now that we did that, the node is dead. Increment the iterator to the
526 // next node to process, then delete N.
527 ++I;
528 DAG.DeleteNode(N);
529 }
530}
531
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
533/// when it has created a SelectionDAG for us to codegen.
534void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
535 DEBUG(BB->dump());
536 MachineFunction::iterator FirstMBB = BB;
537
538 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000539 PreprocessForRMW(DAG);
540
541 // FIXME: This should only happen when not -fast.
542 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543
544 // Codegen the basic block.
545#ifndef NDEBUG
546 DOUT << "===== Instruction selection begins:\n";
547 Indent = 0;
548#endif
549 DAG.setRoot(SelectRoot(DAG.getRoot()));
550#ifndef NDEBUG
551 DOUT << "===== Instruction selection ends:\n";
552#endif
553
554 DAG.RemoveDeadNodes();
555
Chris Lattner04d64b22008-03-10 23:34:12 +0000556 // Emit machine code to BB. This can change 'BB' to the last block being
557 // inserted into.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 ScheduleAndEmitDAG(DAG);
559
560 // If we are emitting FP stack code, scan the basic block to determine if this
561 // block defines any FP values. If so, put an FP_REG_KILL instruction before
562 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000563
Dale Johannesen684887e2007-09-24 22:52:39 +0000564 // Note that FP stack instructions are used in all modes for long double,
565 // so we always need to do this check.
566 // Also note that it's possible for an FP stack register to be live across
567 // an instruction that produces multiple basic blocks (SSE CMOV) so we
568 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000569
570 // Scan all of the machine instructions in these MBBs, checking for FP
571 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
572 MachineFunction::iterator MBBI = FirstMBB;
Chris Lattner04d64b22008-03-10 23:34:12 +0000573 MachineFunction::iterator EndMBB = BB; ++EndMBB;
574 for (; MBBI != EndMBB; ++MBBI) {
575 MachineBasicBlock *MBB = MBBI;
576
577 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
578 // before the return.
579 if (!MBB->empty()) {
580 MachineBasicBlock::iterator EndI = MBB->end();
581 --EndI;
582 if (EndI->getDesc().isReturn())
583 continue;
584 }
585
Dale Johannesen684887e2007-09-24 22:52:39 +0000586 bool ContainsFPCode = false;
Chris Lattner04d64b22008-03-10 23:34:12 +0000587 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000588 !ContainsFPCode && I != E; ++I) {
589 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
590 const TargetRegisterClass *clas;
591 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
592 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Chris Lattner04d64b22008-03-10 23:34:12 +0000593 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000594 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000595 X86::RFP32RegisterClass ||
596 clas == X86::RFP64RegisterClass ||
597 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 ContainsFPCode = true;
599 break;
600 }
601 }
602 }
603 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000604 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
605 // a copy of the input value in this block. In SSE mode, we only care about
606 // 80-bit values.
607 if (!ContainsFPCode) {
608 // Final check, check LLVM BB's that are successors to the LLVM BB
609 // corresponding to BB for FP PHI nodes.
610 const BasicBlock *LLVMBB = BB->getBasicBlock();
611 const PHINode *PN;
612 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
613 !ContainsFPCode && SI != E; ++SI) {
614 for (BasicBlock::const_iterator II = SI->begin();
615 (PN = dyn_cast<PHINode>(II)); ++II) {
616 if (PN->getType()==Type::X86_FP80Ty ||
617 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
618 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
619 ContainsFPCode = true;
620 break;
621 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000622 }
623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000625 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
626 if (ContainsFPCode) {
Chris Lattner04d64b22008-03-10 23:34:12 +0000627 BuildMI(*MBB, MBBI->getFirstTerminator(),
Dale Johannesen684887e2007-09-24 22:52:39 +0000628 TM.getInstrInfo()->get(X86::FP_REG_KILL));
629 ++NumFPKill;
630 }
Chris Lattner04d64b22008-03-10 23:34:12 +0000631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632}
633
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000634/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
635/// the main function.
636void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
637 MachineFrameInfo *MFI) {
638 const TargetInstrInfo *TII = TM.getInstrInfo();
639 if (Subtarget->isTargetCygMing())
640 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
641}
642
643void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
644 // If this is main, emit special code for main.
645 MachineBasicBlock *BB = MF.begin();
646 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
647 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
648}
649
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650/// MatchAddress - Add the specified node to the specified addressing mode,
651/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000652/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
654 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000655 // Limit recursion.
656 if (Depth > 5)
657 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658
659 // RIP relative addressing: %rip + 32-bit displacement!
660 if (AM.isRIPRel) {
661 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
662 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
663 if (isInt32(AM.Disp + Val)) {
664 AM.Disp += Val;
665 return false;
666 }
667 }
668 return true;
669 }
670
671 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000672 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673
674 switch (N.getOpcode()) {
675 default: break;
676 case ISD::Constant: {
677 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
678 if (isInt32(AM.Disp + Val)) {
679 AM.Disp += Val;
680 return false;
681 }
682 break;
683 }
684
685 case X86ISD::Wrapper: {
686 bool is64Bit = Subtarget->is64Bit();
687 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000688 // Also, base and index reg must be 0 in order to use rip as base.
689 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
690 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 break;
692 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
693 break;
694 // If value is available in a register both base and index components have
695 // been picked, we can't fit the result available in the register in the
696 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000697 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 SDOperand N0 = N.getOperand(0);
699 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
700 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000701 AM.GV = GV;
702 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000703 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
704 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000705 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000707 AM.CP = CP->getConstVal();
708 AM.Align = CP->getAlignment();
709 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000710 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
711 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000712 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000714 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000715 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
716 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000717 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000719 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000720 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
721 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000722 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 }
724 }
725 break;
726 }
727
728 case ISD::FrameIndex:
729 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
730 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
731 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
732 return false;
733 }
734 break;
735
736 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000737 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000738 break;
739
740 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
741 unsigned Val = CN->getValue();
742 if (Val == 1 || Val == 2 || Val == 3) {
743 AM.Scale = 1 << Val;
744 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745
Chris Lattner7f06edd2007-12-08 07:22:58 +0000746 // Okay, we know that we have a scale by now. However, if the scaled
747 // value is an add of something and a constant, we can fold the
748 // constant into the disp field here.
749 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
750 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
751 AM.IndexReg = ShVal.Val->getOperand(0);
752 ConstantSDNode *AddVal =
753 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
754 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
755 if (isInt32(Disp))
756 AM.Disp = Disp;
757 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000759 } else {
760 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000762 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 }
764 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000765 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766
Dan Gohman35b99222007-10-22 20:22:24 +0000767 case ISD::SMUL_LOHI:
768 case ISD::UMUL_LOHI:
769 // A mul_lohi where we need the low part can be folded as a plain multiply.
770 if (N.ResNo != 0) break;
771 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 case ISD::MUL:
773 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000774 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 AM.BaseType == X86ISelAddressMode::RegBase &&
776 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000777 AM.IndexReg.Val == 0 &&
778 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
780 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
781 AM.Scale = unsigned(CN->getValue())-1;
782
783 SDOperand MulVal = N.Val->getOperand(0);
784 SDOperand Reg;
785
786 // Okay, we know that we have a scale by now. However, if the scaled
787 // value is an add of something and a constant, we can fold the
788 // constant into the disp field here.
789 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
790 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
791 Reg = MulVal.Val->getOperand(0);
792 ConstantSDNode *AddVal =
793 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
794 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
795 if (isInt32(Disp))
796 AM.Disp = Disp;
797 else
798 Reg = N.Val->getOperand(0);
799 } else {
800 Reg = N.Val->getOperand(0);
801 }
802
803 AM.IndexReg = AM.Base.Reg = Reg;
804 return false;
805 }
806 }
807 break;
808
809 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000810 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 X86ISelAddressMode Backup = AM;
812 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
813 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
814 return false;
815 AM = Backup;
816 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
817 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
818 return false;
819 AM = Backup;
820 }
821 break;
822
823 case ISD::OR:
824 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000825 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000826
827 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
828 X86ISelAddressMode Backup = AM;
829 // Start with the LHS as an addr mode.
830 if (!MatchAddress(N.getOperand(0), AM, false) &&
831 // Address could not have picked a GV address for the displacement.
832 AM.GV == NULL &&
833 // On x86-64, the resultant disp must fit in 32-bits.
834 isInt32(AM.Disp + CN->getSignExtended()) &&
835 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000836 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000837 AM.Disp += CN->getValue();
838 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000840 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 }
842 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000843
844 case ISD::AND: {
845 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
846 // allows us to fold the shift into this addressing mode.
847 if (AlreadySelected) break;
848 SDOperand Shift = N.getOperand(0);
849 if (Shift.getOpcode() != ISD::SHL) break;
850
851 // Scale must not be used already.
852 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000853
854 // Not when RIP is used as the base.
855 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000856
857 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
858 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
859 if (!C1 || !C2) break;
860
861 // Not likely to be profitable if either the AND or SHIFT node has more
862 // than one use (unless all uses are for address computation). Besides,
863 // isel mechanism requires their node ids to be reused.
864 if (!N.hasOneUse() || !Shift.hasOneUse())
865 break;
866
867 // Verify that the shift amount is something we can fold.
868 unsigned ShiftCst = C1->getValue();
869 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
870 break;
871
872 // Get the new AND mask, this folds to a constant.
873 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
874 SDOperand(C2, 0), SDOperand(C1, 0));
875 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
876 Shift.getOperand(0), NewANDMask);
877 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
878 NewAND.Val->setNodeId(N.Val->getNodeId());
879
880 AM.Scale = 1 << ShiftCst;
881 AM.IndexReg = NewAND;
882 return false;
883 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 }
885
Dan Gohmana60c1b32007-08-13 20:03:06 +0000886 return MatchAddressBase(N, AM, isRoot, Depth);
887}
888
889/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
890/// specified addressing mode without any further recursion.
891bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
892 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 // Is the base register already occupied?
894 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
895 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000896 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 AM.IndexReg = N;
898 AM.Scale = 1;
899 return false;
900 }
901
902 // Otherwise, we cannot select it.
903 return true;
904 }
905
906 // Default, generate it as a register.
907 AM.BaseType = X86ISelAddressMode::RegBase;
908 AM.Base.Reg = N;
909 return false;
910}
911
912/// SelectAddr - returns true if it is able pattern match an addressing mode.
913/// It returns the operands which make up the maximal addressing mode it can
914/// match by reference.
915bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
916 SDOperand &Scale, SDOperand &Index,
917 SDOperand &Disp) {
918 X86ISelAddressMode AM;
919 if (MatchAddress(N, AM))
920 return false;
921
922 MVT::ValueType VT = N.getValueType();
923 if (AM.BaseType == X86ISelAddressMode::RegBase) {
924 if (!AM.Base.Reg.Val)
925 AM.Base.Reg = CurDAG->getRegister(0, VT);
926 }
927
928 if (!AM.IndexReg.Val)
929 AM.IndexReg = CurDAG->getRegister(0, VT);
930
931 getAddressOperands(AM, Base, Scale, Index, Disp);
932 return true;
933}
934
935/// isZeroNode - Returns true if Elt is a constant zero or a floating point
936/// constant +0.0.
937static inline bool isZeroNode(SDOperand Elt) {
938 return ((isa<ConstantSDNode>(Elt) &&
939 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
940 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000941 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942}
943
944
945/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
946/// match a load whose top elements are either undef or zeros. The load flavor
947/// is derived from the type of N, which is either v4f32 or v2f64.
948bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
949 SDOperand N, SDOperand &Base,
950 SDOperand &Scale, SDOperand &Index,
951 SDOperand &Disp, SDOperand &InChain,
952 SDOperand &OutChain) {
953 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
954 InChain = N.getOperand(0).getValue(1);
955 if (ISD::isNON_EXTLoad(InChain.Val) &&
956 InChain.getValue(0).hasOneUse() &&
957 N.hasOneUse() &&
958 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
959 LoadSDNode *LD = cast<LoadSDNode>(InChain);
960 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
961 return false;
962 OutChain = LD->getChain();
963 return true;
964 }
965 }
966
967 // Also handle the case where we explicitly require zeros in the top
968 // elements. This is a vector shuffle from the zero vector.
969 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000970 // Check to see if the top elements are all zeros (or bitcast of zeros).
971 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
973 N.getOperand(1).Val->hasOneUse() &&
974 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
975 N.getOperand(1).getOperand(0).hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
977 // from the LHS.
Chris Lattnere6aa3862007-11-25 00:24:49 +0000978 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979 SDOperand ShufMask = N.getOperand(2);
980 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
982 if (C->getValue() == VecWidth) {
983 for (unsigned i = 1; i != VecWidth; ++i) {
984 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
985 // ok.
986 } else {
987 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
988 if (C->getValue() >= VecWidth) return false;
989 }
990 }
991 }
992
993 // Okay, this is a zero extending load. Fold it.
994 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
995 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
996 return false;
997 OutChain = LD->getChain();
998 InChain = SDOperand(LD, 1);
999 return true;
1000 }
1001 }
1002 return false;
1003}
1004
1005
1006/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1007/// mode it matches can be cost effectively emitted as an LEA instruction.
1008bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1009 SDOperand &Base, SDOperand &Scale,
1010 SDOperand &Index, SDOperand &Disp) {
1011 X86ISelAddressMode AM;
1012 if (MatchAddress(N, AM))
1013 return false;
1014
1015 MVT::ValueType VT = N.getValueType();
1016 unsigned Complexity = 0;
1017 if (AM.BaseType == X86ISelAddressMode::RegBase)
1018 if (AM.Base.Reg.Val)
1019 Complexity = 1;
1020 else
1021 AM.Base.Reg = CurDAG->getRegister(0, VT);
1022 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1023 Complexity = 4;
1024
1025 if (AM.IndexReg.Val)
1026 Complexity++;
1027 else
1028 AM.IndexReg = CurDAG->getRegister(0, VT);
1029
1030 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1031 // a simple shift.
1032 if (AM.Scale > 1)
1033 Complexity++;
1034
1035 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1036 // to a LEA. This is determined with some expermentation but is by no means
1037 // optimal (especially for code size consideration). LEA is nice because of
1038 // its three-address nature. Tweak the cost function again when we can run
1039 // convertToThreeAddress() at register allocation time.
1040 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1041 // For X86-64, we should always use lea to materialize RIP relative
1042 // addresses.
1043 if (Subtarget->is64Bit())
1044 Complexity = 4;
1045 else
1046 Complexity += 2;
1047 }
1048
1049 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1050 Complexity++;
1051
1052 if (Complexity > 2) {
1053 getAddressOperands(AM, Base, Scale, Index, Disp);
1054 return true;
1055 }
1056 return false;
1057}
1058
1059bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1060 SDOperand &Base, SDOperand &Scale,
1061 SDOperand &Index, SDOperand &Disp) {
1062 if (ISD::isNON_EXTLoad(N.Val) &&
1063 N.hasOneUse() &&
1064 CanBeFoldedBy(N.Val, P.Val, P.Val))
1065 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1066 return false;
1067}
1068
1069/// getGlobalBaseReg - Output the instructions required to put the
1070/// base address to use for accessing globals into a register.
1071///
1072SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1073 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1074 if (!GlobalBaseReg) {
1075 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001076 MachineFunction *MF = BB->getParent();
1077 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001079 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001080 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081
1082 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001083 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1084 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001085 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086
1087 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1088 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1089 if (TM.getRelocationModel() == Reloc::PIC_ &&
1090 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001091 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001092 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1093 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 } else {
1095 GlobalBaseReg = PC;
1096 }
1097
1098 }
1099 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1100}
1101
1102static SDNode *FindCallStartFromCall(SDNode *Node) {
1103 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1104 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1105 "Node doesn't have a token chain argument!");
1106 return FindCallStartFromCall(Node->getOperand(0).Val);
1107}
1108
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001109SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1110 SDOperand SRIdx;
1111 switch (VT) {
1112 case MVT::i8:
1113 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1114 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1115 if (!Subtarget->is64Bit()) {
1116 unsigned Opc;
1117 MVT::ValueType VT;
1118 switch (N0.getValueType()) {
1119 default: assert(0 && "Unknown truncate!");
1120 case MVT::i16:
1121 Opc = X86::MOV16to16_;
1122 VT = MVT::i16;
1123 break;
1124 case MVT::i32:
1125 Opc = X86::MOV32to32_;
1126 VT = MVT::i32;
1127 break;
1128 }
Evan Chenge1f39552007-10-12 07:55:53 +00001129 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1130 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1131 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001132 }
1133 break;
1134 case MVT::i16:
1135 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1136 break;
1137 case MVT::i32:
1138 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1139 break;
Evan Chenge1f39552007-10-12 07:55:53 +00001140 default: assert(0 && "Unknown truncate!"); break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001141 }
Evan Chenge1f39552007-10-12 07:55:53 +00001142 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001143}
1144
1145
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1147 SDNode *Node = N.Val;
1148 MVT::ValueType NVT = Node->getValueType(0);
1149 unsigned Opc, MOpc;
1150 unsigned Opcode = Node->getOpcode();
1151
1152#ifndef NDEBUG
1153 DOUT << std::string(Indent, ' ') << "Selecting: ";
1154 DEBUG(Node->dump(CurDAG));
1155 DOUT << "\n";
1156 Indent += 2;
1157#endif
1158
1159 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1160#ifndef NDEBUG
1161 DOUT << std::string(Indent-2, ' ') << "== ";
1162 DEBUG(Node->dump(CurDAG));
1163 DOUT << "\n";
1164 Indent -= 2;
1165#endif
1166 return NULL; // Already selected.
1167 }
1168
1169 switch (Opcode) {
1170 default: break;
1171 case X86ISD::GlobalBaseReg:
1172 return getGlobalBaseReg();
1173
Chris Lattnerb56cc342008-03-11 03:23:40 +00001174 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1175 case X86ISD::RET_FLAG:
1176 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1177 if (Amt->getSignExtended() != 0) break;
1178
1179 // Match (X86retflag 0).
1180 SDOperand Chain = N.getOperand(0);
1181 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1182 == MVT::Flag;
1183 SmallVector<SDOperand, 8> Ops0;
1184 AddToISelQueue(Chain);
1185 SDOperand InFlag(0, 0);
1186 if (HasInFlag) {
1187 InFlag = N.getOperand(N.getNumOperands()-1);
1188 AddToISelQueue(InFlag);
1189 }
1190 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1191 ++i) {
1192 AddToISelQueue(N.getOperand(i));
1193 Ops0.push_back(N.getOperand(i));
1194 }
1195 Ops0.push_back(Chain);
1196 if (HasInFlag)
1197 Ops0.push_back(InFlag);
1198 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1199 &Ops0[0], Ops0.size());
1200 }
1201 break;
1202
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 case ISD::ADD: {
1204 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1205 // code and is matched first so to prevent it from being turned into
1206 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001207 // In 64-bit small code size mode, use LEA to take advantage of
1208 // RIP-relative addressing.
1209 if (TM.getCodeModel() != CodeModel::Small)
1210 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 MVT::ValueType PtrVT = TLI.getPointerTy();
1212 SDOperand N0 = N.getOperand(0);
1213 SDOperand N1 = N.getOperand(1);
1214 if (N.Val->getValueType(0) == PtrVT &&
1215 N0.getOpcode() == X86ISD::Wrapper &&
1216 N1.getOpcode() == ISD::Constant) {
1217 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1218 SDOperand C(0, 0);
1219 // TODO: handle ExternalSymbolSDNode.
1220 if (GlobalAddressSDNode *G =
1221 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1222 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1223 G->getOffset() + Offset);
1224 } else if (ConstantPoolSDNode *CP =
1225 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1226 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1227 CP->getAlignment(),
1228 CP->getOffset()+Offset);
1229 }
1230
1231 if (C.Val) {
1232 if (Subtarget->is64Bit()) {
1233 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1234 CurDAG->getRegister(0, PtrVT), C };
1235 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1236 } else
1237 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1238 }
1239 }
1240
1241 // Other cases are handled by auto-generated code.
1242 break;
1243 }
1244
Dan Gohman5a199552007-10-08 18:33:35 +00001245 case ISD::SMUL_LOHI:
1246 case ISD::UMUL_LOHI: {
1247 SDOperand N0 = Node->getOperand(0);
1248 SDOperand N1 = Node->getOperand(1);
1249
Dan Gohman5a199552007-10-08 18:33:35 +00001250 bool isSigned = Opcode == ISD::SMUL_LOHI;
1251 if (!isSigned)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 switch (NVT) {
1253 default: assert(0 && "Unsupported VT!");
1254 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1255 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1256 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1257 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1258 }
1259 else
1260 switch (NVT) {
1261 default: assert(0 && "Unsupported VT!");
1262 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1263 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1264 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1265 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1266 }
1267
1268 unsigned LoReg, HiReg;
1269 switch (NVT) {
1270 default: assert(0 && "Unsupported VT!");
1271 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1272 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1273 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1274 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1275 }
1276
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001278 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001279 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 if (!foldedLoad) {
1281 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001282 if (foldedLoad)
1283 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 }
1285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001287 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1288 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289
1290 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001291 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 AddToISelQueue(Tmp0);
1293 AddToISelQueue(Tmp1);
1294 AddToISelQueue(Tmp2);
1295 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001296 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 SDNode *CNode =
1298 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001300 // Update the chain.
1301 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 } else {
1303 AddToISelQueue(N1);
1304 InFlag =
1305 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1306 }
1307
Dan Gohman5a199552007-10-08 18:33:35 +00001308 // Copy the low half of the result, if it is needed.
1309 if (!N.getValue(0).use_empty()) {
1310 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1311 LoReg, NVT, InFlag);
1312 InFlag = Result.getValue(2);
1313 ReplaceUses(N.getValue(0), Result);
1314#ifndef NDEBUG
1315 DOUT << std::string(Indent-2, ' ') << "=> ";
1316 DEBUG(Result.Val->dump(CurDAG));
1317 DOUT << "\n";
1318#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001319 }
Dan Gohman5a199552007-10-08 18:33:35 +00001320 // Copy the high half of the result, if it is needed.
1321 if (!N.getValue(1).use_empty()) {
1322 SDOperand Result;
1323 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1324 // Prevent use of AH in a REX instruction by referencing AX instead.
1325 // Shift it down 8 bits.
1326 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1327 X86::AX, MVT::i16, InFlag);
1328 InFlag = Result.getValue(2);
1329 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1330 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1331 // Then truncate it down to i8.
1332 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1333 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1334 MVT::i8, Result, SRIdx), 0);
1335 } else {
1336 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1337 HiReg, NVT, InFlag);
1338 InFlag = Result.getValue(2);
1339 }
1340 ReplaceUses(N.getValue(1), Result);
1341#ifndef NDEBUG
1342 DOUT << std::string(Indent-2, ' ') << "=> ";
1343 DEBUG(Result.Val->dump(CurDAG));
1344 DOUT << "\n";
1345#endif
1346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347
1348#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 Indent -= 2;
1350#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001351
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 return NULL;
1353 }
1354
Dan Gohman5a199552007-10-08 18:33:35 +00001355 case ISD::SDIVREM:
1356 case ISD::UDIVREM: {
1357 SDOperand N0 = Node->getOperand(0);
1358 SDOperand N1 = Node->getOperand(1);
1359
1360 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 if (!isSigned)
1362 switch (NVT) {
1363 default: assert(0 && "Unsupported VT!");
1364 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1365 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1366 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1367 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1368 }
1369 else
1370 switch (NVT) {
1371 default: assert(0 && "Unsupported VT!");
1372 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1373 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1374 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1375 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1376 }
1377
1378 unsigned LoReg, HiReg;
1379 unsigned ClrOpcode, SExtOpcode;
1380 switch (NVT) {
1381 default: assert(0 && "Unsupported VT!");
1382 case MVT::i8:
1383 LoReg = X86::AL; HiReg = X86::AH;
1384 ClrOpcode = 0;
1385 SExtOpcode = X86::CBW;
1386 break;
1387 case MVT::i16:
1388 LoReg = X86::AX; HiReg = X86::DX;
1389 ClrOpcode = X86::MOV16r0;
1390 SExtOpcode = X86::CWD;
1391 break;
1392 case MVT::i32:
1393 LoReg = X86::EAX; HiReg = X86::EDX;
1394 ClrOpcode = X86::MOV32r0;
1395 SExtOpcode = X86::CDQ;
1396 break;
1397 case MVT::i64:
1398 LoReg = X86::RAX; HiReg = X86::RDX;
1399 ClrOpcode = X86::MOV64r0;
1400 SExtOpcode = X86::CQO;
1401 break;
1402 }
1403
Dan Gohman5a199552007-10-08 18:33:35 +00001404 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1405 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1406
1407 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 if (NVT == MVT::i8 && !isSigned) {
1409 // Special case for div8, just use a move with zero extension to AX to
1410 // clear the upper 8 bits (AH).
1411 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1412 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1413 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1414 AddToISelQueue(N0.getOperand(0));
1415 AddToISelQueue(Tmp0);
1416 AddToISelQueue(Tmp1);
1417 AddToISelQueue(Tmp2);
1418 AddToISelQueue(Tmp3);
1419 Move =
1420 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1421 Ops, 5), 0);
1422 Chain = Move.getValue(1);
1423 ReplaceUses(N0.getValue(1), Chain);
1424 } else {
1425 AddToISelQueue(N0);
1426 Move =
1427 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1428 Chain = CurDAG->getEntryNode();
1429 }
Dan Gohman5a199552007-10-08 18:33:35 +00001430 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 InFlag = Chain.getValue(1);
1432 } else {
1433 AddToISelQueue(N0);
1434 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001435 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1436 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 if (isSigned) {
1438 // Sign extend the low part into the high part.
1439 InFlag =
1440 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1441 } else {
1442 // Zero out the high part, effectively zero extending the input.
1443 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001444 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1445 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 }
1447 }
1448
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 if (foldedLoad) {
1450 AddToISelQueue(N1.getOperand(0));
1451 AddToISelQueue(Tmp0);
1452 AddToISelQueue(Tmp1);
1453 AddToISelQueue(Tmp2);
1454 AddToISelQueue(Tmp3);
1455 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1456 SDNode *CNode =
1457 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001459 // Update the chain.
1460 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001461 } else {
1462 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 InFlag =
1464 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1465 }
1466
Dan Gohman242a5ba2007-09-25 18:23:27 +00001467 // Copy the division (low) result, if it is needed.
1468 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001469 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1470 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001471 InFlag = Result.getValue(2);
1472 ReplaceUses(N.getValue(0), Result);
1473#ifndef NDEBUG
1474 DOUT << std::string(Indent-2, ' ') << "=> ";
1475 DEBUG(Result.Val->dump(CurDAG));
1476 DOUT << "\n";
1477#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001478 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001479 // Copy the remainder (high) result, if it is needed.
1480 if (!N.getValue(1).use_empty()) {
1481 SDOperand Result;
1482 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1483 // Prevent use of AH in a REX instruction by referencing AX instead.
1484 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001485 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1486 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001487 InFlag = Result.getValue(2);
1488 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1489 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1490 // Then truncate it down to i8.
1491 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1492 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1493 MVT::i8, Result, SRIdx), 0);
1494 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001495 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1496 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001497 InFlag = Result.getValue(2);
1498 }
1499 ReplaceUses(N.getValue(1), Result);
1500#ifndef NDEBUG
1501 DOUT << std::string(Indent-2, ' ') << "=> ";
1502 DEBUG(Result.Val->dump(CurDAG));
1503 DOUT << "\n";
1504#endif
1505 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001506
1507#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508 Indent -= 2;
1509#endif
1510
1511 return NULL;
1512 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001513
1514 case ISD::ANY_EXTEND: {
Christopher Lamb76d72da2008-03-16 03:12:01 +00001515 // Check if the type extended to supports subregs.
1516 if (NVT == MVT::i8)
1517 break;
1518
Christopher Lamb422213d2007-08-10 22:22:41 +00001519 SDOperand N0 = Node->getOperand(0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001520 // Get the subregsiter index for the type to extend.
1521 MVT::ValueType N0VT = N0.getValueType();
1522 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1523 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1524 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1525
1526 // If we don't have a subreg Idx, let generated ISel have a try.
1527 if (Idx == 0)
1528 break;
1529
1530 // If we have an index, generate an insert_subreg into undef.
Christopher Lamb422213d2007-08-10 22:22:41 +00001531 AddToISelQueue(N0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001532 SDOperand Undef =
Evan Cheng55a2dd02008-04-03 07:45:18 +00001533 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001534 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1535 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
Evan Cheng55a2dd02008-04-03 07:45:18 +00001536 NVT, Undef, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001537
1538#ifndef NDEBUG
Christopher Lamb76d72da2008-03-16 03:12:01 +00001539 DOUT << std::string(Indent-2, ' ') << "=> ";
1540 DEBUG(ResNode->dump(CurDAG));
1541 DOUT << "\n";
1542 Indent -= 2;
Christopher Lamb422213d2007-08-10 22:22:41 +00001543#endif
Christopher Lamb76d72da2008-03-16 03:12:01 +00001544 return ResNode;
Christopher Lamb422213d2007-08-10 22:22:41 +00001545 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001546
1547 case ISD::SIGN_EXTEND_INREG: {
1548 SDOperand N0 = Node->getOperand(0);
1549 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001551 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1552 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001553 unsigned Opc = 0;
Christopher Lamb444336c2007-07-29 01:24:57 +00001554 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001555 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001556 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1557 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001558 break;
1559 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001560 switch (SVT) {
1561 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1562 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1563 default: assert(0 && "Unknown sign_extend_inreg!");
1564 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001565 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001566 case MVT::i64:
1567 switch (SVT) {
1568 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1569 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1570 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1571 default: assert(0 && "Unknown sign_extend_inreg!");
1572 }
1573 break;
1574 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001575 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001576
1577 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1578
1579#ifndef NDEBUG
1580 DOUT << std::string(Indent-2, ' ') << "=> ";
1581 DEBUG(TruncOp.Val->dump(CurDAG));
1582 DOUT << "\n";
1583 DOUT << std::string(Indent-2, ' ') << "=> ";
1584 DEBUG(ResNode->dump(CurDAG));
1585 DOUT << "\n";
1586 Indent -= 2;
1587#endif
1588 return ResNode;
1589 break;
1590 }
1591
1592 case ISD::TRUNCATE: {
1593 SDOperand Input = Node->getOperand(0);
1594 AddToISelQueue(Node->getOperand(0));
1595 SDNode *ResNode = getTruncate(Input, NVT);
1596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597#ifndef NDEBUG
1598 DOUT << std::string(Indent-2, ' ') << "=> ";
1599 DEBUG(ResNode->dump(CurDAG));
1600 DOUT << "\n";
1601 Indent -= 2;
1602#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001603 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001604 break;
1605 }
1606 }
1607
1608 SDNode *ResNode = SelectCode(N);
1609
1610#ifndef NDEBUG
1611 DOUT << std::string(Indent-2, ' ') << "=> ";
1612 if (ResNode == NULL || ResNode == N.Val)
1613 DEBUG(N.Val->dump(CurDAG));
1614 else
1615 DEBUG(ResNode->dump(CurDAG));
1616 DOUT << "\n";
1617 Indent -= 2;
1618#endif
1619
1620 return ResNode;
1621}
1622
1623bool X86DAGToDAGISel::
1624SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1625 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1626 SDOperand Op0, Op1, Op2, Op3;
1627 switch (ConstraintCode) {
1628 case 'o': // offsetable ??
1629 case 'v': // not offsetable ??
1630 default: return true;
1631 case 'm': // memory
1632 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1633 return true;
1634 break;
1635 }
1636
1637 OutOps.push_back(Op0);
1638 OutOps.push_back(Op1);
1639 OutOps.push_back(Op2);
1640 OutOps.push_back(Op3);
1641 AddToISelQueue(Op0);
1642 AddToISelQueue(Op1);
1643 AddToISelQueue(Op2);
1644 AddToISelQueue(Op3);
1645 return false;
1646}
1647
1648/// createX86ISelDag - This pass converts a legalized DAG into a
1649/// X86-specific DAG, ready for instruction scheduling.
1650///
1651FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1652 return new X86DAGToDAGISel(TM, Fast);
1653}