blob: 895c2cf514086f2c82ef60bb2acc84fc1029588b [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"
Evan Cheng656269e2008-04-25 08:22:20 +000038#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#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
Evan Cheng34fd4f32008-06-30 20:45:06 +0000113 /// CurBB - Current BB being isel'd.
114 ///
115 MachineBasicBlock *CurBB;
116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 public:
118 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
119 : SelectionDAGISel(X86Lowering),
120 ContainsFPCode(false), FastISel(fast), TM(tm),
121 X86Lowering(*TM.getTargetLowering()),
122 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
123
124 virtual bool runOnFunction(Function &Fn) {
125 // Make sure we re-emit a set of the global base reg if necessary
126 GlobalBaseReg = 0;
127 return SelectionDAGISel::runOnFunction(Fn);
128 }
129
130 virtual const char *getPassName() const {
131 return "X86 DAG->DAG Instruction Selection";
132 }
133
Evan Cheng34fd4f32008-06-30 20:45:06 +0000134 /// InstructionSelect - This callback is invoked by
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
Evan Cheng34fd4f32008-06-30 20:45:06 +0000136 virtual void InstructionSelect(SelectionDAG &DAG);
137
138 /// InstructionSelectPostProcessing - Post processing of selected and
139 /// scheduled basic blocks.
140 virtual void InstructionSelectPostProcessing(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000142 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
143
Dan Gohmand6098272007-07-24 23:00:27 +0000144 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145
146// Include the pieces autogenerated from the target description.
147#include "X86GenDAGISel.inc"
148
149 private:
150 SDNode *Select(SDOperand N);
151
152 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
153 bool isRoot = true, unsigned Depth = 0);
Dan Gohmana60c1b32007-08-13 20:03:06 +0000154 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
155 bool isRoot, unsigned Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
157 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
158 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
159 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
160 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
161 SDOperand N, SDOperand &Base, SDOperand &Scale,
162 SDOperand &Index, SDOperand &Disp,
163 SDOperand &InChain, SDOperand &OutChain);
164 bool TryFoldLoad(SDOperand P, SDOperand N,
165 SDOperand &Base, SDOperand &Scale,
166 SDOperand &Index, SDOperand &Disp);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000167 void PreprocessForRMW(SelectionDAG &DAG);
168 void PreprocessForFPConvert(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169
170 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
171 /// inline asm expressions.
172 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
173 char ConstraintCode,
174 std::vector<SDOperand> &OutOps,
175 SelectionDAG &DAG);
176
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000177 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
178
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
180 SDOperand &Scale, SDOperand &Index,
181 SDOperand &Disp) {
182 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
183 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
184 AM.Base.Reg;
185 Scale = getI8Imm(AM.Scale);
186 Index = AM.IndexReg;
187 // These are 32-bit even in 64-bit mode since RIP relative offset
188 // is 32-bit.
189 if (AM.GV)
190 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
191 else if (AM.CP)
192 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
193 else if (AM.ES)
194 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
195 else if (AM.JT != -1)
196 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
197 else
198 Disp = getI32Imm(AM.Disp);
199 }
200
201 /// getI8Imm - Return a target constant with the specified value, of type
202 /// i8.
203 inline SDOperand getI8Imm(unsigned Imm) {
204 return CurDAG->getTargetConstant(Imm, MVT::i8);
205 }
206
207 /// getI16Imm - Return a target constant with the specified value, of type
208 /// i16.
209 inline SDOperand getI16Imm(unsigned Imm) {
210 return CurDAG->getTargetConstant(Imm, MVT::i16);
211 }
212
213 /// getI32Imm - Return a target constant with the specified value, of type
214 /// i32.
215 inline SDOperand getI32Imm(unsigned Imm) {
216 return CurDAG->getTargetConstant(Imm, MVT::i32);
217 }
218
219 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
220 /// base register. Return the virtual register that holds this value.
221 SDNode *getGlobalBaseReg();
222
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000223 /// getTruncate - return an SDNode that implements a subreg based truncate
224 /// of the specified operand to the the specified value type.
Duncan Sands92c43912008-06-06 12:08:01 +0000225 SDNode *getTruncate(SDOperand N0, MVT VT);
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000226
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227#ifndef NDEBUG
228 unsigned Indent;
229#endif
230 };
231}
232
Evan Cheng656269e2008-04-25 08:22:20 +0000233/// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
234///
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235static SDNode *findFlagUse(SDNode *N) {
236 unsigned FlagResNo = N->getNumValues()-1;
237 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +0000238 SDNode *User = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
240 SDOperand Op = User->getOperand(i);
241 if (Op.Val == N && Op.ResNo == FlagResNo)
242 return User;
243 }
244 }
245 return NULL;
246}
247
Evan Cheng656269e2008-04-25 08:22:20 +0000248/// findNonImmUse - Return true by reference in "found" if "Use" is an
249/// non-immediate use of "Def". This function recursively traversing
250/// up the operand chain ignoring certain nodes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
252 SDNode *Root, SDNode *Skip, bool &found,
Evan Cheng656269e2008-04-25 08:22:20 +0000253 SmallPtrSet<SDNode*, 16> &Visited) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 if (found ||
255 Use->getNodeId() > Def->getNodeId() ||
Evan Cheng656269e2008-04-25 08:22:20 +0000256 !Visited.insert(Use))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 return;
Evan Cheng656269e2008-04-25 08:22:20 +0000258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
260 SDNode *N = Use->getOperand(i).Val;
261 if (N == Skip)
262 continue;
263 if (N == Def) {
264 if (Use == ImmedUse)
Evan Cheng9ea310c2008-04-25 08:55:28 +0000265 continue; // We are not looking for immediate use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 if (Use == Root) {
Evan Cheng9ea310c2008-04-25 08:55:28 +0000267 // Must be a chain reading node where it is possible to reach its own
268 // chain operand through a path started from another operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 assert(Use->getOpcode() == ISD::STORE ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000270 Use->getOpcode() == X86ISD::CMP ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000271 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
272 Use->getOpcode() == ISD::INTRINSIC_VOID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 continue;
274 }
275 found = true;
276 break;
277 }
Evan Cheng656269e2008-04-25 08:22:20 +0000278
279 // Traverse up the operand chain.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
281 }
282}
283
284/// isNonImmUse - Start searching from Root up the DAG to check is Def can
285/// be reached. Return true if that's the case. However, ignore direct uses
286/// by ImmedUse (which would be U in the example illustrated in
287/// CanBeFoldedBy) and by Root (which can happen in the store case).
288/// FIXME: to be really generic, we should allow direct use by any node
289/// that is being folded. But realisticly since we only fold loads which
290/// have one non-chain use, we only need to watch out for load/op/store
291/// and load/op/cmp case where the root (store / cmp) may reach the load via
292/// its chain operand.
293static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
294 SDNode *Skip = NULL) {
Evan Cheng656269e2008-04-25 08:22:20 +0000295 SmallPtrSet<SDNode*, 16> Visited;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 bool found = false;
297 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
298 return found;
299}
300
301
Dan Gohmand6098272007-07-24 23:00:27 +0000302bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 if (FastISel) return false;
304
305 // If U use can somehow reach N through another path then U can't fold N or
306 // it will create a cycle. e.g. In the following diagram, U can reach N
307 // through X. If N is folded into into U, then X is both a predecessor and
308 // a successor of U.
309 //
310 // [ N ]
311 // ^ ^
312 // | |
313 // / \---
314 // / [X]
315 // | ^
316 // [U]--------|
317
318 if (isNonImmUse(Root, N, U))
319 return false;
320
321 // If U produces a flag, then it gets (even more) interesting. Since it
322 // would have been "glued" together with its flag use, we need to check if
323 // it might reach N:
324 //
325 // [ N ]
326 // ^ ^
327 // | |
328 // [U] \--
329 // ^ [TF]
330 // | ^
331 // | |
332 // \ /
333 // [FU]
334 //
335 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
336 // NU), then TF is a predecessor of FU and a successor of NU. But since
337 // NU and FU are flagged together, this effectively creates a cycle.
338 bool HasFlagUse = false;
Duncan Sands92c43912008-06-06 12:08:01 +0000339 MVT VT = Root->getValueType(Root->getNumValues()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 while ((VT == MVT::Flag && !Root->use_empty())) {
341 SDNode *FU = findFlagUse(Root);
342 if (FU == NULL)
343 break;
344 else {
345 Root = FU;
346 HasFlagUse = true;
347 }
348 VT = Root->getValueType(Root->getNumValues()-1);
349 }
350
351 if (HasFlagUse)
352 return !isNonImmUse(Root, N, Root, U);
353 return true;
354}
355
356/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
357/// and move load below the TokenFactor. Replace store's chain operand with
358/// load's chain result.
359static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
360 SDOperand Store, SDOperand TF) {
361 std::vector<SDOperand> Ops;
362 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
363 if (Load.Val == TF.Val->getOperand(i).Val)
364 Ops.push_back(Load.Val->getOperand(0));
365 else
366 Ops.push_back(TF.Val->getOperand(i));
367 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
368 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
369 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
370 Store.getOperand(2), Store.getOperand(3));
371}
372
Evan Cheng2b2a7012008-05-23 21:23:16 +0000373/// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
374///
375static bool isRMWLoad(SDOperand N, SDOperand Chain, SDOperand Address,
376 SDOperand &Load) {
377 if (N.getOpcode() == ISD::BIT_CONVERT)
378 N = N.getOperand(0);
379
380 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
381 if (!LD || LD->isVolatile())
382 return false;
383 if (LD->getAddressingMode() != ISD::UNINDEXED)
384 return false;
385
386 ISD::LoadExtType ExtType = LD->getExtensionType();
387 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
388 return false;
389
390 if (N.hasOneUse() &&
391 N.getOperand(1) == Address &&
392 N.Val->isOperandOf(Chain.Val)) {
393 Load = N;
394 return true;
395 }
396 return false;
397}
398
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000399/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
400/// This is only run if not in -fast mode (aka -O0).
401/// This allows the instruction selector to pick more read-modify-write
402/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403///
404/// [Load chain]
405/// ^
406/// |
407/// [Load]
408/// ^ ^
409/// | |
410/// / \-
411/// / |
412/// [TokenFactor] [Op]
413/// ^ ^
414/// | |
415/// \ /
416/// \ /
417/// [Store]
418///
419/// The fact the store's chain operand != load's chain will prevent the
420/// (store (op (load))) instruction from being selected. We can transform it to:
421///
422/// [Load chain]
423/// ^
424/// |
425/// [TokenFactor]
426/// ^
427/// |
428/// [Load]
429/// ^ ^
430/// | |
431/// | \-
432/// | |
433/// | [Op]
434/// | ^
435/// | |
436/// \ /
437/// \ /
438/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000439void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
441 E = DAG.allnodes_end(); I != E; ++I) {
442 if (!ISD::isNON_TRUNCStore(I))
443 continue;
444 SDOperand Chain = I->getOperand(0);
445 if (Chain.Val->getOpcode() != ISD::TokenFactor)
446 continue;
447
448 SDOperand N1 = I->getOperand(1);
449 SDOperand N2 = I->getOperand(2);
Duncan Sands92c43912008-06-06 12:08:01 +0000450 if ((N1.getValueType().isFloatingPoint() &&
451 !N1.getValueType().isVector()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 !N1.hasOneUse())
453 continue;
454
455 bool RModW = false;
456 SDOperand Load;
457 unsigned Opcode = N1.Val->getOpcode();
458 switch (Opcode) {
459 case ISD::ADD:
460 case ISD::MUL:
461 case ISD::AND:
462 case ISD::OR:
463 case ISD::XOR:
464 case ISD::ADDC:
Evan Cheng2b2a7012008-05-23 21:23:16 +0000465 case ISD::ADDE:
466 case ISD::VECTOR_SHUFFLE: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 SDOperand N10 = N1.getOperand(0);
468 SDOperand N11 = N1.getOperand(1);
Evan Cheng2b2a7012008-05-23 21:23:16 +0000469 RModW = isRMWLoad(N10, Chain, N2, Load);
470 if (!RModW)
471 RModW = isRMWLoad(N11, Chain, N2, Load);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 break;
473 }
474 case ISD::SUB:
475 case ISD::SHL:
476 case ISD::SRA:
477 case ISD::SRL:
478 case ISD::ROTL:
479 case ISD::ROTR:
480 case ISD::SUBC:
481 case ISD::SUBE:
482 case X86ISD::SHLD:
483 case X86ISD::SHRD: {
484 SDOperand N10 = N1.getOperand(0);
Evan Cheng2b2a7012008-05-23 21:23:16 +0000485 RModW = isRMWLoad(N10, Chain, N2, Load);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 break;
487 }
488 }
489
490 if (RModW) {
491 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
492 ++NumLoadMoved;
493 }
494 }
495}
496
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000497
498/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
499/// nodes that target the FP stack to be store and load to the stack. This is a
500/// gross hack. We would like to simply mark these as being illegal, but when
501/// we do that, legalize produces these when it expands calls, then expands
502/// these in the same legalize pass. We would like dag combine to be able to
503/// hack on these between the call expansion and the node legalization. As such
504/// this pass basically does "really late" legalization of these inline with the
505/// X86 isel pass.
506void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
507 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
508 E = DAG.allnodes_end(); I != E; ) {
509 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
510 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
511 continue;
512
513 // If the source and destination are SSE registers, then this is a legal
514 // conversion that should not be lowered.
Duncan Sands92c43912008-06-06 12:08:01 +0000515 MVT SrcVT = N->getOperand(0).getValueType();
516 MVT DstVT = N->getValueType(0);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000517 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
518 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
519 if (SrcIsSSE && DstIsSSE)
520 continue;
521
Chris Lattner5d294e52008-03-09 07:05:32 +0000522 if (!SrcIsSSE && !DstIsSSE) {
523 // If this is an FPStack extension, it is a noop.
524 if (N->getOpcode() == ISD::FP_EXTEND)
525 continue;
526 // If this is a value-preserving FPStack truncation, it is a noop.
527 if (N->getConstantOperandVal(1))
528 continue;
529 }
530
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000531 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
532 // FPStack has extload and truncstore. SSE can fold direct loads into other
533 // operations. Based on this, decide what we want to do.
Duncan Sands92c43912008-06-06 12:08:01 +0000534 MVT MemVT;
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000535 if (N->getOpcode() == ISD::FP_ROUND)
536 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
537 else
538 MemVT = SrcIsSSE ? SrcVT : DstVT;
539
540 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
541
542 // FIXME: optimize the case where the src/dest is a load or store?
543 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
544 MemTmp, NULL, 0, MemVT);
545 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
546 NULL, 0, MemVT);
547
548 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
549 // extload we created. This will cause general havok on the dag because
550 // anything below the conversion could be folded into other existing nodes.
551 // To avoid invalidating 'I', back it up to the convert node.
552 --I;
553 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
554
555 // Now that we did that, the node is dead. Increment the iterator to the
556 // next node to process, then delete N.
557 ++I;
558 DAG.DeleteNode(N);
559 }
560}
561
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
563/// when it has created a SelectionDAG for us to codegen.
Evan Cheng34fd4f32008-06-30 20:45:06 +0000564void X86DAGToDAGISel::InstructionSelect(SelectionDAG &DAG) {
565 CurBB = BB; // BB can change as result of isel.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566
Evan Cheng34fd4f32008-06-30 20:45:06 +0000567 DEBUG(BB->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000569 PreprocessForRMW(DAG);
570
571 // FIXME: This should only happen when not -fast.
572 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573
574 // Codegen the basic block.
575#ifndef NDEBUG
576 DOUT << "===== Instruction selection begins:\n";
577 Indent = 0;
578#endif
579 DAG.setRoot(SelectRoot(DAG.getRoot()));
580#ifndef NDEBUG
581 DOUT << "===== Instruction selection ends:\n";
582#endif
583
584 DAG.RemoveDeadNodes();
Evan Cheng34fd4f32008-06-30 20:45:06 +0000585}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586
Evan Cheng34fd4f32008-06-30 20:45:06 +0000587void X86DAGToDAGISel::InstructionSelectPostProcessing(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 // If we are emitting FP stack code, scan the basic block to determine if this
589 // block defines any FP values. If so, put an FP_REG_KILL instruction before
590 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000591
Dale Johannesen684887e2007-09-24 22:52:39 +0000592 // Note that FP stack instructions are used in all modes for long double,
593 // so we always need to do this check.
594 // Also note that it's possible for an FP stack register to be live across
595 // an instruction that produces multiple basic blocks (SSE CMOV) so we
596 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000597
598 // Scan all of the machine instructions in these MBBs, checking for FP
599 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
Evan Cheng34fd4f32008-06-30 20:45:06 +0000600 MachineFunction::iterator MBBI = CurBB;
Chris Lattner04d64b22008-03-10 23:34:12 +0000601 MachineFunction::iterator EndMBB = BB; ++EndMBB;
602 for (; MBBI != EndMBB; ++MBBI) {
603 MachineBasicBlock *MBB = MBBI;
604
605 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
606 // before the return.
607 if (!MBB->empty()) {
608 MachineBasicBlock::iterator EndI = MBB->end();
609 --EndI;
610 if (EndI->getDesc().isReturn())
611 continue;
612 }
613
Dale Johannesen684887e2007-09-24 22:52:39 +0000614 bool ContainsFPCode = false;
Chris Lattner04d64b22008-03-10 23:34:12 +0000615 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000616 !ContainsFPCode && I != E; ++I) {
617 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
618 const TargetRegisterClass *clas;
619 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
620 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Chris Lattner04d64b22008-03-10 23:34:12 +0000621 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000622 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000623 X86::RFP32RegisterClass ||
624 clas == X86::RFP64RegisterClass ||
625 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 ContainsFPCode = true;
627 break;
628 }
629 }
630 }
631 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000632 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
633 // a copy of the input value in this block. In SSE mode, we only care about
634 // 80-bit values.
635 if (!ContainsFPCode) {
636 // Final check, check LLVM BB's that are successors to the LLVM BB
637 // corresponding to BB for FP PHI nodes.
638 const BasicBlock *LLVMBB = BB->getBasicBlock();
639 const PHINode *PN;
640 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
641 !ContainsFPCode && SI != E; ++SI) {
642 for (BasicBlock::const_iterator II = SI->begin();
643 (PN = dyn_cast<PHINode>(II)); ++II) {
644 if (PN->getType()==Type::X86_FP80Ty ||
645 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
646 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
647 ContainsFPCode = true;
648 break;
649 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000650 }
651 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000653 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
654 if (ContainsFPCode) {
Chris Lattner04d64b22008-03-10 23:34:12 +0000655 BuildMI(*MBB, MBBI->getFirstTerminator(),
Dale Johannesen684887e2007-09-24 22:52:39 +0000656 TM.getInstrInfo()->get(X86::FP_REG_KILL));
657 ++NumFPKill;
658 }
Chris Lattner04d64b22008-03-10 23:34:12 +0000659 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660}
661
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000662/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
663/// the main function.
664void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
665 MachineFrameInfo *MFI) {
666 const TargetInstrInfo *TII = TM.getInstrInfo();
667 if (Subtarget->isTargetCygMing())
668 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
669}
670
671void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
672 // If this is main, emit special code for main.
673 MachineBasicBlock *BB = MF.begin();
674 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
675 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
676}
677
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678/// MatchAddress - Add the specified node to the specified addressing mode,
679/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000680/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
682 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000683 // Limit recursion.
684 if (Depth > 5)
685 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686
687 // RIP relative addressing: %rip + 32-bit displacement!
688 if (AM.isRIPRel) {
689 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
690 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
691 if (isInt32(AM.Disp + Val)) {
692 AM.Disp += Val;
693 return false;
694 }
695 }
696 return true;
697 }
698
699 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000700 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701
702 switch (N.getOpcode()) {
703 default: break;
704 case ISD::Constant: {
705 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
706 if (isInt32(AM.Disp + Val)) {
707 AM.Disp += Val;
708 return false;
709 }
710 break;
711 }
712
713 case X86ISD::Wrapper: {
714 bool is64Bit = Subtarget->is64Bit();
715 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000716 // Also, base and index reg must be 0 in order to use rip as base.
717 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
718 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 break;
720 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
721 break;
722 // If value is available in a register both base and index components have
723 // been picked, we can't fit the result available in the register in the
724 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000725 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 SDOperand N0 = N.getOperand(0);
727 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
728 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000729 AM.GV = GV;
730 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000731 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
732 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000733 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000735 AM.CP = CP->getConstVal();
736 AM.Align = CP->getAlignment();
737 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000738 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
739 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000740 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000742 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000743 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
744 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000745 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000747 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000748 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
749 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000750 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 }
752 }
753 break;
754 }
755
756 case ISD::FrameIndex:
757 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
758 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
759 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
760 return false;
761 }
762 break;
763
764 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000765 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000766 break;
767
768 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
769 unsigned Val = CN->getValue();
770 if (Val == 1 || Val == 2 || Val == 3) {
771 AM.Scale = 1 << Val;
772 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773
Chris Lattner7f06edd2007-12-08 07:22:58 +0000774 // Okay, we know that we have a scale by now. However, if the scaled
775 // value is an add of something and a constant, we can fold the
776 // constant into the disp field here.
777 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
778 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
779 AM.IndexReg = ShVal.Val->getOperand(0);
780 ConstantSDNode *AddVal =
781 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
782 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
783 if (isInt32(Disp))
784 AM.Disp = Disp;
785 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000787 } else {
788 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000790 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791 }
792 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000793 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794
Dan Gohman35b99222007-10-22 20:22:24 +0000795 case ISD::SMUL_LOHI:
796 case ISD::UMUL_LOHI:
797 // A mul_lohi where we need the low part can be folded as a plain multiply.
798 if (N.ResNo != 0) break;
799 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 case ISD::MUL:
801 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000802 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 AM.BaseType == X86ISelAddressMode::RegBase &&
804 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000805 AM.IndexReg.Val == 0 &&
806 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
808 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
809 AM.Scale = unsigned(CN->getValue())-1;
810
811 SDOperand MulVal = N.Val->getOperand(0);
812 SDOperand Reg;
813
814 // Okay, we know that we have a scale by now. However, if the scaled
815 // value is an add of something and a constant, we can fold the
816 // constant into the disp field here.
817 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
818 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
819 Reg = MulVal.Val->getOperand(0);
820 ConstantSDNode *AddVal =
821 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
822 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
823 if (isInt32(Disp))
824 AM.Disp = Disp;
825 else
826 Reg = N.Val->getOperand(0);
827 } else {
828 Reg = N.Val->getOperand(0);
829 }
830
831 AM.IndexReg = AM.Base.Reg = Reg;
832 return false;
833 }
834 }
835 break;
836
837 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000838 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 X86ISelAddressMode Backup = AM;
840 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
841 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
842 return false;
843 AM = Backup;
844 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
845 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
846 return false;
847 AM = Backup;
848 }
849 break;
850
851 case ISD::OR:
852 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000853 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000854
855 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
856 X86ISelAddressMode Backup = AM;
857 // Start with the LHS as an addr mode.
858 if (!MatchAddress(N.getOperand(0), AM, false) &&
859 // Address could not have picked a GV address for the displacement.
860 AM.GV == NULL &&
861 // On x86-64, the resultant disp must fit in 32-bits.
862 isInt32(AM.Disp + CN->getSignExtended()) &&
863 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000864 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000865 AM.Disp += CN->getValue();
866 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000868 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 }
870 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000871
872 case ISD::AND: {
873 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
874 // allows us to fold the shift into this addressing mode.
875 if (AlreadySelected) break;
876 SDOperand Shift = N.getOperand(0);
877 if (Shift.getOpcode() != ISD::SHL) break;
878
879 // Scale must not be used already.
880 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000881
882 // Not when RIP is used as the base.
883 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000884
885 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
886 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
887 if (!C1 || !C2) break;
888
889 // Not likely to be profitable if either the AND or SHIFT node has more
890 // than one use (unless all uses are for address computation). Besides,
891 // isel mechanism requires their node ids to be reused.
892 if (!N.hasOneUse() || !Shift.hasOneUse())
893 break;
894
895 // Verify that the shift amount is something we can fold.
896 unsigned ShiftCst = C1->getValue();
897 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
898 break;
899
900 // Get the new AND mask, this folds to a constant.
901 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
902 SDOperand(C2, 0), SDOperand(C1, 0));
903 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
904 Shift.getOperand(0), NewANDMask);
905 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
906 NewAND.Val->setNodeId(N.Val->getNodeId());
907
908 AM.Scale = 1 << ShiftCst;
909 AM.IndexReg = NewAND;
910 return false;
911 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 }
913
Dan Gohmana60c1b32007-08-13 20:03:06 +0000914 return MatchAddressBase(N, AM, isRoot, Depth);
915}
916
917/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
918/// specified addressing mode without any further recursion.
919bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
920 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 // Is the base register already occupied?
922 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
923 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000924 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 AM.IndexReg = N;
926 AM.Scale = 1;
927 return false;
928 }
929
930 // Otherwise, we cannot select it.
931 return true;
932 }
933
934 // Default, generate it as a register.
935 AM.BaseType = X86ISelAddressMode::RegBase;
936 AM.Base.Reg = N;
937 return false;
938}
939
940/// SelectAddr - returns true if it is able pattern match an addressing mode.
941/// It returns the operands which make up the maximal addressing mode it can
942/// match by reference.
943bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
944 SDOperand &Scale, SDOperand &Index,
945 SDOperand &Disp) {
946 X86ISelAddressMode AM;
947 if (MatchAddress(N, AM))
948 return false;
949
Duncan Sands92c43912008-06-06 12:08:01 +0000950 MVT VT = N.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 if (AM.BaseType == X86ISelAddressMode::RegBase) {
952 if (!AM.Base.Reg.Val)
953 AM.Base.Reg = CurDAG->getRegister(0, VT);
954 }
955
956 if (!AM.IndexReg.Val)
957 AM.IndexReg = CurDAG->getRegister(0, VT);
958
959 getAddressOperands(AM, Base, Scale, Index, Disp);
960 return true;
961}
962
963/// isZeroNode - Returns true if Elt is a constant zero or a floating point
964/// constant +0.0.
965static inline bool isZeroNode(SDOperand Elt) {
966 return ((isa<ConstantSDNode>(Elt) &&
967 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
968 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000969 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970}
971
972
973/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
974/// match a load whose top elements are either undef or zeros. The load flavor
975/// is derived from the type of N, which is either v4f32 or v2f64.
976bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
977 SDOperand N, SDOperand &Base,
978 SDOperand &Scale, SDOperand &Index,
979 SDOperand &Disp, SDOperand &InChain,
980 SDOperand &OutChain) {
981 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
982 InChain = N.getOperand(0).getValue(1);
983 if (ISD::isNON_EXTLoad(InChain.Val) &&
984 InChain.getValue(0).hasOneUse() &&
985 N.hasOneUse() &&
986 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
987 LoadSDNode *LD = cast<LoadSDNode>(InChain);
988 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
989 return false;
990 OutChain = LD->getChain();
991 return true;
992 }
993 }
994
995 // Also handle the case where we explicitly require zeros in the top
996 // elements. This is a vector shuffle from the zero vector.
Evan Chenge9b9c672008-05-09 21:53:03 +0000997 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000998 // Check to see if the top elements are all zeros (or bitcast of zeros).
Evan Cheng40ee6e52008-05-08 00:57:18 +0000999 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1000 N.getOperand(0).Val->hasOneUse() &&
1001 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
1002 N.getOperand(0).getOperand(0).hasOneUse()) {
1003 // Okay, this is a zero extending load. Fold it.
1004 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1005 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1006 return false;
1007 OutChain = LD->getChain();
1008 InChain = SDOperand(LD, 1);
1009 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 }
1011 return false;
1012}
1013
1014
1015/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1016/// mode it matches can be cost effectively emitted as an LEA instruction.
1017bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1018 SDOperand &Base, SDOperand &Scale,
1019 SDOperand &Index, SDOperand &Disp) {
1020 X86ISelAddressMode AM;
1021 if (MatchAddress(N, AM))
1022 return false;
1023
Duncan Sands92c43912008-06-06 12:08:01 +00001024 MVT VT = N.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 unsigned Complexity = 0;
1026 if (AM.BaseType == X86ISelAddressMode::RegBase)
1027 if (AM.Base.Reg.Val)
1028 Complexity = 1;
1029 else
1030 AM.Base.Reg = CurDAG->getRegister(0, VT);
1031 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1032 Complexity = 4;
1033
1034 if (AM.IndexReg.Val)
1035 Complexity++;
1036 else
1037 AM.IndexReg = CurDAG->getRegister(0, VT);
1038
1039 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1040 // a simple shift.
1041 if (AM.Scale > 1)
1042 Complexity++;
1043
1044 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1045 // to a LEA. This is determined with some expermentation but is by no means
1046 // optimal (especially for code size consideration). LEA is nice because of
1047 // its three-address nature. Tweak the cost function again when we can run
1048 // convertToThreeAddress() at register allocation time.
1049 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1050 // For X86-64, we should always use lea to materialize RIP relative
1051 // addresses.
1052 if (Subtarget->is64Bit())
1053 Complexity = 4;
1054 else
1055 Complexity += 2;
1056 }
1057
1058 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1059 Complexity++;
1060
1061 if (Complexity > 2) {
1062 getAddressOperands(AM, Base, Scale, Index, Disp);
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1069 SDOperand &Base, SDOperand &Scale,
1070 SDOperand &Index, SDOperand &Disp) {
1071 if (ISD::isNON_EXTLoad(N.Val) &&
1072 N.hasOneUse() &&
1073 CanBeFoldedBy(N.Val, P.Val, P.Val))
1074 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1075 return false;
1076}
1077
1078/// getGlobalBaseReg - Output the instructions required to put the
1079/// base address to use for accessing globals into a register.
1080///
1081SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1082 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1083 if (!GlobalBaseReg) {
1084 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001085 MachineFunction *MF = BB->getParent();
1086 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001088 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001089 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001092 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1093 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001094 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095
1096 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1097 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1098 if (TM.getRelocationModel() == Reloc::PIC_ &&
1099 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001100 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001101 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1102 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 } else {
1104 GlobalBaseReg = PC;
1105 }
1106
1107 }
1108 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1109}
1110
1111static SDNode *FindCallStartFromCall(SDNode *Node) {
1112 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1113 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1114 "Node doesn't have a token chain argument!");
1115 return FindCallStartFromCall(Node->getOperand(0).Val);
1116}
1117
Duncan Sands92c43912008-06-06 12:08:01 +00001118SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT VT) {
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001119 SDOperand SRIdx;
Duncan Sands92c43912008-06-06 12:08:01 +00001120 switch (VT.getSimpleVT()) {
1121 default: assert(0 && "Unknown truncate!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001122 case MVT::i8:
1123 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1124 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1125 if (!Subtarget->is64Bit()) {
1126 unsigned Opc;
Duncan Sands92c43912008-06-06 12:08:01 +00001127 MVT VT;
1128 switch (N0.getValueType().getSimpleVT()) {
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001129 default: assert(0 && "Unknown truncate!");
1130 case MVT::i16:
1131 Opc = X86::MOV16to16_;
1132 VT = MVT::i16;
1133 break;
1134 case MVT::i32:
1135 Opc = X86::MOV32to32_;
1136 VT = MVT::i32;
1137 break;
1138 }
Evan Chenge1f39552007-10-12 07:55:53 +00001139 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1140 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1141 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001142 }
1143 break;
1144 case MVT::i16:
1145 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1146 break;
1147 case MVT::i32:
1148 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1149 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001150 }
Evan Chenge1f39552007-10-12 07:55:53 +00001151 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001152}
1153
1154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1156 SDNode *Node = N.Val;
Duncan Sands92c43912008-06-06 12:08:01 +00001157 MVT NVT = Node->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 unsigned Opc, MOpc;
1159 unsigned Opcode = Node->getOpcode();
1160
1161#ifndef NDEBUG
1162 DOUT << std::string(Indent, ' ') << "Selecting: ";
1163 DEBUG(Node->dump(CurDAG));
1164 DOUT << "\n";
1165 Indent += 2;
1166#endif
1167
1168 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1169#ifndef NDEBUG
1170 DOUT << std::string(Indent-2, ' ') << "== ";
1171 DEBUG(Node->dump(CurDAG));
1172 DOUT << "\n";
1173 Indent -= 2;
1174#endif
1175 return NULL; // Already selected.
1176 }
1177
1178 switch (Opcode) {
1179 default: break;
1180 case X86ISD::GlobalBaseReg:
1181 return getGlobalBaseReg();
1182
1183 case ISD::ADD: {
1184 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1185 // code and is matched first so to prevent it from being turned into
1186 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001187 // In 64-bit small code size mode, use LEA to take advantage of
1188 // RIP-relative addressing.
1189 if (TM.getCodeModel() != CodeModel::Small)
1190 break;
Duncan Sands92c43912008-06-06 12:08:01 +00001191 MVT PtrVT = TLI.getPointerTy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 SDOperand N0 = N.getOperand(0);
1193 SDOperand N1 = N.getOperand(1);
1194 if (N.Val->getValueType(0) == PtrVT &&
1195 N0.getOpcode() == X86ISD::Wrapper &&
1196 N1.getOpcode() == ISD::Constant) {
1197 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1198 SDOperand C(0, 0);
1199 // TODO: handle ExternalSymbolSDNode.
1200 if (GlobalAddressSDNode *G =
1201 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1202 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1203 G->getOffset() + Offset);
1204 } else if (ConstantPoolSDNode *CP =
1205 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1206 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1207 CP->getAlignment(),
1208 CP->getOffset()+Offset);
1209 }
1210
1211 if (C.Val) {
1212 if (Subtarget->is64Bit()) {
1213 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1214 CurDAG->getRegister(0, PtrVT), C };
1215 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1216 } else
1217 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1218 }
1219 }
1220
1221 // Other cases are handled by auto-generated code.
1222 break;
1223 }
1224
Dan Gohman5a199552007-10-08 18:33:35 +00001225 case ISD::SMUL_LOHI:
1226 case ISD::UMUL_LOHI: {
1227 SDOperand N0 = Node->getOperand(0);
1228 SDOperand N1 = Node->getOperand(1);
1229
Dan Gohman5a199552007-10-08 18:33:35 +00001230 bool isSigned = Opcode == ISD::SMUL_LOHI;
1231 if (!isSigned)
Duncan Sands92c43912008-06-06 12:08:01 +00001232 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 default: assert(0 && "Unsupported VT!");
1234 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1235 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1236 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1237 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1238 }
1239 else
Duncan Sands92c43912008-06-06 12:08:01 +00001240 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 default: assert(0 && "Unsupported VT!");
1242 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1243 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1244 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1245 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1246 }
1247
1248 unsigned LoReg, HiReg;
Duncan Sands92c43912008-06-06 12:08:01 +00001249 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 default: assert(0 && "Unsupported VT!");
1251 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1252 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1253 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1254 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1255 }
1256
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001258 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001259 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 if (!foldedLoad) {
1261 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001262 if (foldedLoad)
1263 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
1265
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001267 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1268 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269
1270 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001271 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 AddToISelQueue(Tmp0);
1273 AddToISelQueue(Tmp1);
1274 AddToISelQueue(Tmp2);
1275 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001276 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 SDNode *CNode =
1278 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001280 // Update the chain.
1281 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 } else {
1283 AddToISelQueue(N1);
1284 InFlag =
1285 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1286 }
1287
Dan Gohman5a199552007-10-08 18:33:35 +00001288 // Copy the low half of the result, if it is needed.
1289 if (!N.getValue(0).use_empty()) {
1290 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1291 LoReg, NVT, InFlag);
1292 InFlag = Result.getValue(2);
1293 ReplaceUses(N.getValue(0), Result);
1294#ifndef NDEBUG
1295 DOUT << std::string(Indent-2, ' ') << "=> ";
1296 DEBUG(Result.Val->dump(CurDAG));
1297 DOUT << "\n";
1298#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001299 }
Dan Gohman5a199552007-10-08 18:33:35 +00001300 // Copy the high half of the result, if it is needed.
1301 if (!N.getValue(1).use_empty()) {
1302 SDOperand Result;
1303 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1304 // Prevent use of AH in a REX instruction by referencing AX instead.
1305 // Shift it down 8 bits.
1306 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1307 X86::AX, MVT::i16, InFlag);
1308 InFlag = Result.getValue(2);
1309 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1310 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1311 // Then truncate it down to i8.
1312 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1313 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1314 MVT::i8, Result, SRIdx), 0);
1315 } else {
1316 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1317 HiReg, NVT, InFlag);
1318 InFlag = Result.getValue(2);
1319 }
1320 ReplaceUses(N.getValue(1), Result);
1321#ifndef NDEBUG
1322 DOUT << std::string(Indent-2, ' ') << "=> ";
1323 DEBUG(Result.Val->dump(CurDAG));
1324 DOUT << "\n";
1325#endif
1326 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327
1328#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 Indent -= 2;
1330#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001331
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 return NULL;
1333 }
1334
Dan Gohman5a199552007-10-08 18:33:35 +00001335 case ISD::SDIVREM:
1336 case ISD::UDIVREM: {
1337 SDOperand N0 = Node->getOperand(0);
1338 SDOperand N1 = Node->getOperand(1);
1339
1340 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 if (!isSigned)
Duncan Sands92c43912008-06-06 12:08:01 +00001342 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 default: assert(0 && "Unsupported VT!");
1344 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1345 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1346 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1347 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1348 }
1349 else
Duncan Sands92c43912008-06-06 12:08:01 +00001350 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 default: assert(0 && "Unsupported VT!");
1352 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1353 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1354 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1355 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1356 }
1357
1358 unsigned LoReg, HiReg;
1359 unsigned ClrOpcode, SExtOpcode;
Duncan Sands92c43912008-06-06 12:08:01 +00001360 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 default: assert(0 && "Unsupported VT!");
1362 case MVT::i8:
1363 LoReg = X86::AL; HiReg = X86::AH;
1364 ClrOpcode = 0;
1365 SExtOpcode = X86::CBW;
1366 break;
1367 case MVT::i16:
1368 LoReg = X86::AX; HiReg = X86::DX;
1369 ClrOpcode = X86::MOV16r0;
1370 SExtOpcode = X86::CWD;
1371 break;
1372 case MVT::i32:
1373 LoReg = X86::EAX; HiReg = X86::EDX;
1374 ClrOpcode = X86::MOV32r0;
1375 SExtOpcode = X86::CDQ;
1376 break;
1377 case MVT::i64:
1378 LoReg = X86::RAX; HiReg = X86::RDX;
1379 ClrOpcode = X86::MOV64r0;
1380 SExtOpcode = X86::CQO;
1381 break;
1382 }
1383
Dan Gohman5a199552007-10-08 18:33:35 +00001384 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1385 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1386
1387 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 if (NVT == MVT::i8 && !isSigned) {
1389 // Special case for div8, just use a move with zero extension to AX to
1390 // clear the upper 8 bits (AH).
1391 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1392 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1393 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1394 AddToISelQueue(N0.getOperand(0));
1395 AddToISelQueue(Tmp0);
1396 AddToISelQueue(Tmp1);
1397 AddToISelQueue(Tmp2);
1398 AddToISelQueue(Tmp3);
1399 Move =
1400 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1401 Ops, 5), 0);
1402 Chain = Move.getValue(1);
1403 ReplaceUses(N0.getValue(1), Chain);
1404 } else {
1405 AddToISelQueue(N0);
1406 Move =
1407 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1408 Chain = CurDAG->getEntryNode();
1409 }
Dan Gohman5a199552007-10-08 18:33:35 +00001410 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 InFlag = Chain.getValue(1);
1412 } else {
1413 AddToISelQueue(N0);
1414 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001415 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1416 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 if (isSigned) {
1418 // Sign extend the low part into the high part.
1419 InFlag =
1420 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1421 } else {
1422 // Zero out the high part, effectively zero extending the input.
1423 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001424 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1425 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 }
1427 }
1428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 if (foldedLoad) {
1430 AddToISelQueue(N1.getOperand(0));
1431 AddToISelQueue(Tmp0);
1432 AddToISelQueue(Tmp1);
1433 AddToISelQueue(Tmp2);
1434 AddToISelQueue(Tmp3);
1435 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1436 SDNode *CNode =
1437 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001439 // Update the chain.
1440 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441 } else {
1442 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 InFlag =
1444 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1445 }
1446
Dan Gohman242a5ba2007-09-25 18:23:27 +00001447 // Copy the division (low) result, if it is needed.
1448 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001449 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1450 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001451 InFlag = Result.getValue(2);
1452 ReplaceUses(N.getValue(0), Result);
1453#ifndef NDEBUG
1454 DOUT << std::string(Indent-2, ' ') << "=> ";
1455 DEBUG(Result.Val->dump(CurDAG));
1456 DOUT << "\n";
1457#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001458 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001459 // Copy the remainder (high) result, if it is needed.
1460 if (!N.getValue(1).use_empty()) {
1461 SDOperand Result;
1462 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1463 // Prevent use of AH in a REX instruction by referencing AX instead.
1464 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001465 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1466 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001467 InFlag = Result.getValue(2);
1468 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1469 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1470 // Then truncate it down to i8.
1471 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1472 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1473 MVT::i8, Result, SRIdx), 0);
1474 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001475 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1476 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001477 InFlag = Result.getValue(2);
1478 }
1479 ReplaceUses(N.getValue(1), Result);
1480#ifndef NDEBUG
1481 DOUT << std::string(Indent-2, ' ') << "=> ";
1482 DEBUG(Result.Val->dump(CurDAG));
1483 DOUT << "\n";
1484#endif
1485 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001486
1487#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 Indent -= 2;
1489#endif
1490
1491 return NULL;
1492 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001493
1494 case ISD::ANY_EXTEND: {
Christopher Lamb76d72da2008-03-16 03:12:01 +00001495 // Check if the type extended to supports subregs.
1496 if (NVT == MVT::i8)
1497 break;
1498
Christopher Lamb422213d2007-08-10 22:22:41 +00001499 SDOperand N0 = Node->getOperand(0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001500 // Get the subregsiter index for the type to extend.
Duncan Sands92c43912008-06-06 12:08:01 +00001501 MVT N0VT = N0.getValueType();
Christopher Lamb76d72da2008-03-16 03:12:01 +00001502 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1503 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1504 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1505
1506 // If we don't have a subreg Idx, let generated ISel have a try.
1507 if (Idx == 0)
1508 break;
1509
1510 // If we have an index, generate an insert_subreg into undef.
Christopher Lamb422213d2007-08-10 22:22:41 +00001511 AddToISelQueue(N0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001512 SDOperand Undef =
Evan Cheng55a2dd02008-04-03 07:45:18 +00001513 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001514 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1515 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
Evan Cheng55a2dd02008-04-03 07:45:18 +00001516 NVT, Undef, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001517
1518#ifndef NDEBUG
Christopher Lamb76d72da2008-03-16 03:12:01 +00001519 DOUT << std::string(Indent-2, ' ') << "=> ";
1520 DEBUG(ResNode->dump(CurDAG));
1521 DOUT << "\n";
1522 Indent -= 2;
Christopher Lamb422213d2007-08-10 22:22:41 +00001523#endif
Christopher Lamb76d72da2008-03-16 03:12:01 +00001524 return ResNode;
Christopher Lamb422213d2007-08-10 22:22:41 +00001525 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001526
1527 case ISD::SIGN_EXTEND_INREG: {
1528 SDOperand N0 = Node->getOperand(0);
1529 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530
Duncan Sands92c43912008-06-06 12:08:01 +00001531 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001532 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001533 unsigned Opc = 0;
Duncan Sands92c43912008-06-06 12:08:01 +00001534 switch (NVT.getSimpleVT()) {
1535 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001536 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001537 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1538 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001539 break;
1540 case MVT::i32:
Duncan Sands92c43912008-06-06 12:08:01 +00001541 switch (SVT.getSimpleVT()) {
1542 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001543 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1544 case MVT::i16: Opc = X86::MOVSX32rr16; break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001545 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001546 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001547 case MVT::i64:
Duncan Sands92c43912008-06-06 12:08:01 +00001548 switch (SVT.getSimpleVT()) {
1549 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001550 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1551 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1552 case MVT::i32: Opc = X86::MOVSX64rr32; break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001553 }
1554 break;
Christopher Lamb444336c2007-07-29 01:24:57 +00001555 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001556
1557 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1558
1559#ifndef NDEBUG
1560 DOUT << std::string(Indent-2, ' ') << "=> ";
1561 DEBUG(TruncOp.Val->dump(CurDAG));
1562 DOUT << "\n";
1563 DOUT << std::string(Indent-2, ' ') << "=> ";
1564 DEBUG(ResNode->dump(CurDAG));
1565 DOUT << "\n";
1566 Indent -= 2;
1567#endif
1568 return ResNode;
1569 break;
1570 }
1571
1572 case ISD::TRUNCATE: {
1573 SDOperand Input = Node->getOperand(0);
1574 AddToISelQueue(Node->getOperand(0));
1575 SDNode *ResNode = getTruncate(Input, NVT);
1576
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577#ifndef NDEBUG
1578 DOUT << std::string(Indent-2, ' ') << "=> ";
1579 DEBUG(ResNode->dump(CurDAG));
1580 DOUT << "\n";
1581 Indent -= 2;
1582#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001583 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584 break;
1585 }
Evan Chengd4cebcd2008-06-17 02:01:22 +00001586
1587 case ISD::DECLARE: {
1588 // Handle DECLARE nodes here because the second operand may have been
1589 // wrapped in X86ISD::Wrapper.
1590 SDOperand Chain = Node->getOperand(0);
1591 SDOperand N1 = Node->getOperand(1);
1592 SDOperand N2 = Node->getOperand(2);
Evan Cheng651e1442008-06-18 02:48:27 +00001593 if (!isa<FrameIndexSDNode>(N1))
1594 break;
1595 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1596 if (N2.getOpcode() == ISD::ADD &&
1597 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1598 N2 = N2.getOperand(1);
1599 if (N2.getOpcode() == X86ISD::Wrapper &&
Evan Chengd4cebcd2008-06-17 02:01:22 +00001600 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
Evan Chengd4cebcd2008-06-17 02:01:22 +00001601 GlobalValue *GV =
1602 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1603 SDOperand Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1604 SDOperand Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1605 AddToISelQueue(Chain);
1606 SDOperand Ops[] = { Tmp1, Tmp2, Chain };
1607 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1608 MVT::Other, Ops, 3);
1609 }
1610 break;
1611 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 }
1613
1614 SDNode *ResNode = SelectCode(N);
1615
1616#ifndef NDEBUG
1617 DOUT << std::string(Indent-2, ' ') << "=> ";
1618 if (ResNode == NULL || ResNode == N.Val)
1619 DEBUG(N.Val->dump(CurDAG));
1620 else
1621 DEBUG(ResNode->dump(CurDAG));
1622 DOUT << "\n";
1623 Indent -= 2;
1624#endif
1625
1626 return ResNode;
1627}
1628
1629bool X86DAGToDAGISel::
1630SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1631 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1632 SDOperand Op0, Op1, Op2, Op3;
1633 switch (ConstraintCode) {
1634 case 'o': // offsetable ??
1635 case 'v': // not offsetable ??
1636 default: return true;
1637 case 'm': // memory
1638 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1639 return true;
1640 break;
1641 }
1642
1643 OutOps.push_back(Op0);
1644 OutOps.push_back(Op1);
1645 OutOps.push_back(Op2);
1646 OutOps.push_back(Op3);
1647 AddToISelQueue(Op0);
1648 AddToISelQueue(Op1);
1649 AddToISelQueue(Op2);
1650 AddToISelQueue(Op3);
1651 return false;
1652}
1653
1654/// createX86ISelDag - This pass converts a legalized DAG into a
1655/// X86-specific DAG, ready for instruction scheduling.
1656///
1657FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1658 return new X86DAGToDAGISel(TM, Fast);
1659}