Added custom lowering of fabs
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.h - X86 DAG Lowering Interface ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetOptions.h"
28 using namespace llvm;
29
30 // FIXME: temporary.
31 #include "llvm/Support/CommandLine.h"
32 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
33                                   cl::desc("Enable fastcc on X86"));
34
35 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
36   : TargetLowering(TM) {
37   Subtarget = &TM.getSubtarget<X86Subtarget>();
38   X86ScalarSSE = Subtarget->hasSSE2();
39
40   // Set up the TargetLowering object.
41
42   // X86 is weird, it always uses i8 for shift amounts and setcc results.
43   setShiftAmountType(MVT::i8);
44   setSetCCResultType(MVT::i8);
45   setSetCCResultContents(ZeroOrOneSetCCResult);
46   setSchedulingPreference(SchedulingForRegPressure);
47   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
48   setStackPointerRegisterToSaveRestore(X86::ESP);
49   
50   // Set up the register classes.
51   addRegisterClass(MVT::i8, X86::R8RegisterClass);
52   addRegisterClass(MVT::i16, X86::R16RegisterClass);
53   addRegisterClass(MVT::i32, X86::R32RegisterClass);
54
55   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
56   // operation.
57   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
58   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
59   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
60
61   if (X86ScalarSSE)
62     // No SSE i64 SINT_TO_FP, so expand i32 UINT_TO_FP instead.
63     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
64   else
65     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
66
67   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
68   // this operation.
69   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
70   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
71   if (X86ScalarSSE)
72     // SSE has no i16 to fp conversion, only i32
73     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
74   else if (!X86PatIsel) {
75     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
76     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
77   }
78
79   // We can handle SINT_TO_FP and FP_TO_SINT from/to i64 even though i64
80   // isn't legal.
81   setOperationAction(ISD::SINT_TO_FP       , MVT::i64  , Custom);
82   setOperationAction(ISD::FP_TO_SINT       , MVT::i64  , Custom);
83
84   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
85   // this operation.
86   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
87   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
88
89   if (X86ScalarSSE) {
90     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
91   } else {
92     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
93     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
94   }
95
96   // Handle FP_TO_UINT by promoting the destination to a larger signed
97   // conversion.
98   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
99   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
100   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
101
102   if (X86ScalarSSE)
103     // Expand FP_TO_UINT into a select.
104     // FIXME: We would like to use a Custom expander here eventually to do
105     // the optimal thing for SSE vs. the default expansion in the legalizer.
106     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Expand);
107   else
108     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
109
110   setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
111   setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
112
113   if (!X86PatIsel) {
114     setOperationAction(ISD::BRCOND         , MVT::Other, Custom);
115   }
116   setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
117   setOperationAction(ISD::BRTWOWAY_CC      , MVT::Other, Expand);
118   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
122   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
123   setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
124   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
125   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
126   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
127   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
128   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
129   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
130   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
131   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
132   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
133   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
134   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
135
136   if (X86PatIsel) {
137     setOperationAction(ISD::BSWAP          , MVT::i32  , Expand);
138     setOperationAction(ISD::ROTL           , MVT::i8   , Expand);
139     setOperationAction(ISD::ROTR           , MVT::i8   , Expand);
140     setOperationAction(ISD::ROTL           , MVT::i16  , Expand);
141     setOperationAction(ISD::ROTR           , MVT::i16  , Expand);
142     setOperationAction(ISD::ROTL           , MVT::i32  , Expand);
143     setOperationAction(ISD::ROTR           , MVT::i32  , Expand);
144   }
145   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
146
147   setOperationAction(ISD::READIO           , MVT::i1   , Expand);
148   setOperationAction(ISD::READIO           , MVT::i8   , Expand);
149   setOperationAction(ISD::READIO           , MVT::i16  , Expand);
150   setOperationAction(ISD::READIO           , MVT::i32  , Expand);
151   setOperationAction(ISD::WRITEIO          , MVT::i1   , Expand);
152   setOperationAction(ISD::WRITEIO          , MVT::i8   , Expand);
153   setOperationAction(ISD::WRITEIO          , MVT::i16  , Expand);
154   setOperationAction(ISD::WRITEIO          , MVT::i32  , Expand);
155
156   // These should be promoted to a larger select which is supported.
157   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
158   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
159   if (!X86PatIsel) {
160     // X86 wants to expand cmov itself.
161     setOperationAction(ISD::SELECT         , MVT::i16  , Custom);
162     setOperationAction(ISD::SELECT         , MVT::i32  , Custom);
163     setOperationAction(ISD::SELECT         , MVT::f32  , Custom);
164     setOperationAction(ISD::SELECT         , MVT::f64  , Custom);
165     setOperationAction(ISD::SETCC          , MVT::i8   , Custom);
166     setOperationAction(ISD::SETCC          , MVT::i16  , Custom);
167     setOperationAction(ISD::SETCC          , MVT::i32  , Custom);
168     setOperationAction(ISD::SETCC          , MVT::f32  , Custom);
169     setOperationAction(ISD::SETCC          , MVT::f64  , Custom);
170     // X86 ret instruction may pop stack.
171     setOperationAction(ISD::RET            , MVT::Other, Custom);
172     // Darwin ABI issue.
173     setOperationAction(ISD::GlobalAddress  , MVT::i32  , Custom);
174     // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
175     setOperationAction(ISD::ADD_PARTS      , MVT::i32  , Custom);
176     setOperationAction(ISD::SUB_PARTS      , MVT::i32  , Custom);
177     setOperationAction(ISD::SHL_PARTS      , MVT::i32  , Custom);
178     setOperationAction(ISD::SRA_PARTS      , MVT::i32  , Custom);
179     setOperationAction(ISD::SRL_PARTS      , MVT::i32  , Custom);
180     // X86 wants to expand memset / memcpy itself.
181     setOperationAction(ISD::MEMSET         , MVT::Other, Custom);
182     setOperationAction(ISD::MEMCPY         , MVT::Other, Custom);
183   }
184
185   // We don't have line number support yet.
186   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
187   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
188   setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
189
190   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
191   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
192   
193   // Use the default implementation.
194   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
195   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
196   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
197   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
198   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
199   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
200
201   if (X86ScalarSSE) {
202     // Set up the FP register classes.
203     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
204     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
205
206     // SSE has no load+extend ops
207     setOperationAction(ISD::EXTLOAD,  MVT::f32, Expand);
208     setOperationAction(ISD::ZEXTLOAD, MVT::f32, Expand);
209
210     // We don't support sin/cos/sqrt/fmod
211     setOperationAction(ISD::FSIN , MVT::f64, Expand);
212     setOperationAction(ISD::FCOS , MVT::f64, Expand);
213     setOperationAction(ISD::FABS , MVT::f64, Custom);
214     setOperationAction(ISD::FNEG , MVT::f64, Expand);
215     setOperationAction(ISD::FREM , MVT::f64, Expand);
216     setOperationAction(ISD::FSIN , MVT::f32, Expand);
217     setOperationAction(ISD::FCOS , MVT::f32, Expand);
218     setOperationAction(ISD::FABS , MVT::f32, Custom);
219     setOperationAction(ISD::FNEG , MVT::f32, Expand);
220     setOperationAction(ISD::FREM , MVT::f32, Expand);
221
222     // Expand FP immediates into loads from the stack, except for the special
223     // cases we handle.
224     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
225     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
226     addLegalFPImmediate(+0.0); // xorps / xorpd
227   } else {
228     // Set up the FP register classes.
229     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
230     
231     setOperationAction(ISD::UNDEF, MVT::f64, Expand);
232     
233     if (!UnsafeFPMath) {
234       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
235       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
236     }
237
238     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
239     addLegalFPImmediate(+0.0); // FLD0
240     addLegalFPImmediate(+1.0); // FLD1
241     addLegalFPImmediate(-0.0); // FLD0/FCHS
242     addLegalFPImmediate(-1.0); // FLD1/FCHS
243   }
244   computeRegisterProperties();
245
246   maxStoresPerMemSet = 8; // For %llvm.memset -> sequence of stores
247   maxStoresPerMemCpy = 8; // For %llvm.memcpy -> sequence of stores
248   maxStoresPerMemMove = 8; // For %llvm.memmove -> sequence of stores
249   allowUnalignedMemoryAccesses = true; // x86 supports it!
250 }
251
252 std::vector<SDOperand>
253 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
254   if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
255     return LowerFastCCArguments(F, DAG);
256   return LowerCCCArguments(F, DAG);
257 }
258
259 std::pair<SDOperand, SDOperand>
260 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
261                                bool isVarArg, unsigned CallingConv,
262                                bool isTailCall,
263                                SDOperand Callee, ArgListTy &Args,
264                                SelectionDAG &DAG) {
265   assert((!isVarArg || CallingConv == CallingConv::C) &&
266          "Only C takes varargs!");
267
268   // If the callee is a GlobalAddress node (quite common, every direct call is)
269   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
270   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
271     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
272   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
273     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
274
275   if (CallingConv == CallingConv::Fast && EnableFastCC)
276     return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
277   return  LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
278 }
279
280 //===----------------------------------------------------------------------===//
281 //                    C Calling Convention implementation
282 //===----------------------------------------------------------------------===//
283
284 std::vector<SDOperand>
285 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
286   std::vector<SDOperand> ArgValues;
287
288   MachineFunction &MF = DAG.getMachineFunction();
289   MachineFrameInfo *MFI = MF.getFrameInfo();
290
291   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
292   // the stack frame looks like this:
293   //
294   // [ESP] -- return address
295   // [ESP + 4] -- first argument (leftmost lexically)
296   // [ESP + 8] -- second argument, if first argument is four bytes in size
297   //    ...
298   //
299   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
300   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
301     MVT::ValueType ObjectVT = getValueType(I->getType());
302     unsigned ArgIncrement = 4;
303     unsigned ObjSize;
304     switch (ObjectVT) {
305     default: assert(0 && "Unhandled argument type!");
306     case MVT::i1:
307     case MVT::i8:  ObjSize = 1;                break;
308     case MVT::i16: ObjSize = 2;                break;
309     case MVT::i32: ObjSize = 4;                break;
310     case MVT::i64: ObjSize = ArgIncrement = 8; break;
311     case MVT::f32: ObjSize = 4;                break;
312     case MVT::f64: ObjSize = ArgIncrement = 8; break;
313     }
314     // Create the frame index object for this incoming parameter...
315     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
316
317     // Create the SelectionDAG nodes corresponding to a load from this parameter
318     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
319
320     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
321     // dead loads.
322     SDOperand ArgValue;
323     if (!I->use_empty())
324       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
325                              DAG.getSrcValue(NULL));
326     else {
327       if (MVT::isInteger(ObjectVT))
328         ArgValue = DAG.getConstant(0, ObjectVT);
329       else
330         ArgValue = DAG.getConstantFP(0, ObjectVT);
331     }
332     ArgValues.push_back(ArgValue);
333
334     ArgOffset += ArgIncrement;   // Move on to the next argument...
335   }
336
337   // If the function takes variable number of arguments, make a frame index for
338   // the start of the first vararg value... for expansion of llvm.va_start.
339   if (F.isVarArg())
340     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
341   ReturnAddrIndex = 0;     // No return address slot generated yet.
342   BytesToPopOnReturn = 0;  // Callee pops nothing.
343   BytesCallerReserves = ArgOffset;
344
345   // Finally, inform the code generator which regs we return values in.
346   switch (getValueType(F.getReturnType())) {
347   default: assert(0 && "Unknown type!");
348   case MVT::isVoid: break;
349   case MVT::i1:
350   case MVT::i8:
351   case MVT::i16:
352   case MVT::i32:
353     MF.addLiveOut(X86::EAX);
354     break;
355   case MVT::i64:
356     MF.addLiveOut(X86::EAX);
357     MF.addLiveOut(X86::EDX);
358     break;
359   case MVT::f32:
360   case MVT::f64:
361     MF.addLiveOut(X86::ST0);
362     break;
363   }
364   return ArgValues;
365 }
366
367 std::pair<SDOperand, SDOperand>
368 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
369                                   bool isVarArg, bool isTailCall,
370                                   SDOperand Callee, ArgListTy &Args,
371                                   SelectionDAG &DAG) {
372   // Count how many bytes are to be pushed on the stack.
373   unsigned NumBytes = 0;
374
375   if (Args.empty()) {
376     // Save zero bytes.
377     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
378                         DAG.getConstant(0, getPointerTy()));
379   } else {
380     for (unsigned i = 0, e = Args.size(); i != e; ++i)
381       switch (getValueType(Args[i].second)) {
382       default: assert(0 && "Unknown value type!");
383       case MVT::i1:
384       case MVT::i8:
385       case MVT::i16:
386       case MVT::i32:
387       case MVT::f32:
388         NumBytes += 4;
389         break;
390       case MVT::i64:
391       case MVT::f64:
392         NumBytes += 8;
393         break;
394       }
395
396     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
397                         DAG.getConstant(NumBytes, getPointerTy()));
398
399     // Arguments go on the stack in reverse order, as specified by the ABI.
400     unsigned ArgOffset = 0;
401     SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
402     std::vector<SDOperand> Stores;
403
404     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
405       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
406       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
407
408       switch (getValueType(Args[i].second)) {
409       default: assert(0 && "Unexpected ValueType for argument!");
410       case MVT::i1:
411       case MVT::i8:
412       case MVT::i16:
413         // Promote the integer to 32 bits.  If the input type is signed use a
414         // sign extend, otherwise use a zero extend.
415         if (Args[i].second->isSigned())
416           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
417         else
418           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
419
420         // FALL THROUGH
421       case MVT::i32:
422       case MVT::f32:
423         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
424                                      Args[i].first, PtrOff,
425                                      DAG.getSrcValue(NULL)));
426         ArgOffset += 4;
427         break;
428       case MVT::i64:
429       case MVT::f64:
430         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
431                                      Args[i].first, PtrOff,
432                                      DAG.getSrcValue(NULL)));
433         ArgOffset += 8;
434         break;
435       }
436     }
437     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
438   }
439
440   std::vector<MVT::ValueType> RetVals;
441   MVT::ValueType RetTyVT = getValueType(RetTy);
442   RetVals.push_back(MVT::Other);
443
444   // The result values produced have to be legal.  Promote the result.
445   switch (RetTyVT) {
446   case MVT::isVoid: break;
447   default:
448     RetVals.push_back(RetTyVT);
449     break;
450   case MVT::i1:
451   case MVT::i8:
452   case MVT::i16:
453     RetVals.push_back(MVT::i32);
454     break;
455   case MVT::f32:
456     if (X86ScalarSSE)
457       RetVals.push_back(MVT::f32);
458     else
459       RetVals.push_back(MVT::f64);
460     break;
461   case MVT::i64:
462     RetVals.push_back(MVT::i32);
463     RetVals.push_back(MVT::i32);
464     break;
465   }
466
467   if (!X86PatIsel) {
468     std::vector<MVT::ValueType> NodeTys;
469     NodeTys.push_back(MVT::Other);   // Returns a chain
470     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
471     std::vector<SDOperand> Ops;
472     Ops.push_back(Chain);
473     Ops.push_back(Callee);
474
475     // FIXME: Do not generate X86ISD::TAILCALL for now.
476     Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
477     SDOperand InFlag = Chain.getValue(1);
478
479     NodeTys.clear();
480     NodeTys.push_back(MVT::Other);   // Returns a chain
481     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
482     Ops.clear();
483     Ops.push_back(Chain);
484     Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
485     Ops.push_back(DAG.getConstant(0, getPointerTy()));
486     Ops.push_back(InFlag);
487     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
488     InFlag = Chain.getValue(1);
489     
490     SDOperand RetVal;
491     if (RetTyVT != MVT::isVoid) {
492       switch (RetTyVT) {
493       default: assert(0 && "Unknown value type to return!");
494       case MVT::i1:
495       case MVT::i8:
496         RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
497         Chain = RetVal.getValue(1);
498         if (RetTyVT == MVT::i1) 
499           RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
500         break;
501       case MVT::i16:
502         RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
503         Chain = RetVal.getValue(1);
504         break;
505       case MVT::i32:
506         RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
507         Chain = RetVal.getValue(1);
508         break;
509       case MVT::i64: {
510         SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
511         SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
512                                           Lo.getValue(2));
513         RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
514         Chain = Hi.getValue(1);
515         break;
516       }
517       case MVT::f32:
518       case MVT::f64: {
519         std::vector<MVT::ValueType> Tys;
520         Tys.push_back(MVT::f64);
521         Tys.push_back(MVT::Other);
522         Tys.push_back(MVT::Flag);
523         std::vector<SDOperand> Ops;
524         Ops.push_back(Chain);
525         Ops.push_back(InFlag);
526         RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
527         Chain  = RetVal.getValue(1);
528         InFlag = RetVal.getValue(2);
529         if (X86ScalarSSE) {
530           // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
531           // shouldn't be necessary except that RFP cannot be live across
532           // multiple blocks. When stackifier is fixed, they can be uncoupled.
533           MachineFunction &MF = DAG.getMachineFunction();
534           int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
535           SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
536           Tys.clear();
537           Tys.push_back(MVT::Other);
538           Ops.clear();
539           Ops.push_back(Chain);
540           Ops.push_back(RetVal);
541           Ops.push_back(StackSlot);
542           Ops.push_back(DAG.getValueType(RetTyVT));
543           Ops.push_back(InFlag);
544           Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
545           RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
546                                DAG.getSrcValue(NULL));
547           Chain = RetVal.getValue(1);
548         }
549
550         if (RetTyVT == MVT::f32 && !X86ScalarSSE)
551           // FIXME: we would really like to remember that this FP_ROUND
552           // operation is okay to eliminate if we allow excess FP precision.
553           RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
554         break;
555       }
556       }
557     }
558
559     return std::make_pair(RetVal, Chain);
560   } else {
561     std::vector<SDOperand> Ops;
562     Ops.push_back(Chain);
563     Ops.push_back(Callee);
564     Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
565     Ops.push_back(DAG.getConstant(0, getPointerTy()));
566
567     SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
568                                     RetVals, Ops);
569
570     SDOperand ResultVal;
571     switch (RetTyVT) {
572     case MVT::isVoid: break;
573     default:
574       ResultVal = TheCall.getValue(1);
575       break;
576     case MVT::i1:
577     case MVT::i8:
578     case MVT::i16:
579       ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
580       break;
581     case MVT::f32:
582       // FIXME: we would really like to remember that this FP_ROUND operation is
583       // okay to eliminate if we allow excess FP precision.
584       ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
585       break;
586     case MVT::i64:
587       ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
588                               TheCall.getValue(2));
589       break;
590     }
591
592     Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
593     return std::make_pair(ResultVal, Chain);
594   }
595 }
596
597 //===----------------------------------------------------------------------===//
598 //                    Fast Calling Convention implementation
599 //===----------------------------------------------------------------------===//
600 //
601 // The X86 'fast' calling convention passes up to two integer arguments in
602 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
603 // and requires that the callee pop its arguments off the stack (allowing proper
604 // tail calls), and has the same return value conventions as C calling convs.
605 //
606 // This calling convention always arranges for the callee pop value to be 8n+4
607 // bytes, which is needed for tail recursion elimination and stack alignment
608 // reasons.
609 //
610 // Note that this can be enhanced in the future to pass fp vals in registers
611 // (when we have a global fp allocator) and do other tricks.
612 //
613
614 /// AddLiveIn - This helper function adds the specified physical register to the
615 /// MachineFunction as a live in value.  It also creates a corresponding virtual
616 /// register for it.
617 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
618                           TargetRegisterClass *RC) {
619   assert(RC->contains(PReg) && "Not the correct regclass!");
620   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
621   MF.addLiveIn(PReg, VReg);
622   return VReg;
623 }
624
625
626 std::vector<SDOperand>
627 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
628   std::vector<SDOperand> ArgValues;
629
630   MachineFunction &MF = DAG.getMachineFunction();
631   MachineFrameInfo *MFI = MF.getFrameInfo();
632
633   // Add DAG nodes to load the arguments...  On entry to a function the stack
634   // frame looks like this:
635   //
636   // [ESP] -- return address
637   // [ESP + 4] -- first nonreg argument (leftmost lexically)
638   // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
639   //    ...
640   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
641
642   // Keep track of the number of integer regs passed so far.  This can be either
643   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
644   // used).
645   unsigned NumIntRegs = 0;
646
647   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
648     MVT::ValueType ObjectVT = getValueType(I->getType());
649     unsigned ArgIncrement = 4;
650     unsigned ObjSize = 0;
651     SDOperand ArgValue;
652
653     switch (ObjectVT) {
654     default: assert(0 && "Unhandled argument type!");
655     case MVT::i1:
656     case MVT::i8:
657       if (NumIntRegs < 2) {
658         if (!I->use_empty()) {
659           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
660                                     X86::R8RegisterClass);
661           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i8);
662           DAG.setRoot(ArgValue.getValue(1));
663           if (ObjectVT == MVT::i1)
664             // FIXME: Should insert a assertzext here.
665             ArgValue = DAG.getNode(ISD::TRUNCATE, MVT::i1, ArgValue);
666         }
667         ++NumIntRegs;
668         break;
669       }
670
671       ObjSize = 1;
672       break;
673     case MVT::i16:
674       if (NumIntRegs < 2) {
675         if (!I->use_empty()) {
676           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
677                                     X86::R16RegisterClass);
678           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i16);
679           DAG.setRoot(ArgValue.getValue(1));
680         }
681         ++NumIntRegs;
682         break;
683       }
684       ObjSize = 2;
685       break;
686     case MVT::i32:
687       if (NumIntRegs < 2) {
688         if (!I->use_empty()) {
689           unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
690                                     X86::R32RegisterClass);
691           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
692           DAG.setRoot(ArgValue.getValue(1));
693         }
694         ++NumIntRegs;
695         break;
696       }
697       ObjSize = 4;
698       break;
699     case MVT::i64:
700       if (NumIntRegs == 0) {
701         if (!I->use_empty()) {
702           unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
703           unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
704
705           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
706           SDOperand Hi  = DAG.getCopyFromReg(Low.getValue(1), TopReg, MVT::i32);
707           DAG.setRoot(Hi.getValue(1));
708
709           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
710         }
711         NumIntRegs = 2;
712         break;
713       } else if (NumIntRegs == 1) {
714         if (!I->use_empty()) {
715           unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
716           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
717           DAG.setRoot(Low.getValue(1));
718
719           // Load the high part from memory.
720           // Create the frame index object for this incoming parameter...
721           int FI = MFI->CreateFixedObject(4, ArgOffset);
722           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
723           SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
724                                      DAG.getSrcValue(NULL));
725           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
726         }
727         ArgOffset += 4;
728         NumIntRegs = 2;
729         break;
730       }
731       ObjSize = ArgIncrement = 8;
732       break;
733     case MVT::f32: ObjSize = 4;                break;
734     case MVT::f64: ObjSize = ArgIncrement = 8; break;
735     }
736
737     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
738     // dead loads.
739     if (ObjSize && !I->use_empty()) {
740       // Create the frame index object for this incoming parameter...
741       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
742
743       // Create the SelectionDAG nodes corresponding to a load from this
744       // parameter.
745       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
746
747       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
748                              DAG.getSrcValue(NULL));
749     } else if (ArgValue.Val == 0) {
750       if (MVT::isInteger(ObjectVT))
751         ArgValue = DAG.getConstant(0, ObjectVT);
752       else
753         ArgValue = DAG.getConstantFP(0, ObjectVT);
754     }
755     ArgValues.push_back(ArgValue);
756
757     if (ObjSize)
758       ArgOffset += ArgIncrement;   // Move on to the next argument.
759   }
760
761   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
762   // arguments and the arguments after the retaddr has been pushed are aligned.
763   if ((ArgOffset & 7) == 0)
764     ArgOffset += 4;
765
766   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
767   ReturnAddrIndex = 0;             // No return address slot generated yet.
768   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
769   BytesCallerReserves = 0;
770
771   // Finally, inform the code generator which regs we return values in.
772   switch (getValueType(F.getReturnType())) {
773   default: assert(0 && "Unknown type!");
774   case MVT::isVoid: break;
775   case MVT::i1:
776   case MVT::i8:
777   case MVT::i16:
778   case MVT::i32:
779     MF.addLiveOut(X86::EAX);
780     break;
781   case MVT::i64:
782     MF.addLiveOut(X86::EAX);
783     MF.addLiveOut(X86::EDX);
784     break;
785   case MVT::f32:
786   case MVT::f64:
787     MF.addLiveOut(X86::ST0);
788     break;
789   }
790   return ArgValues;
791 }
792
793 std::pair<SDOperand, SDOperand>
794 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
795                                      bool isTailCall, SDOperand Callee,
796                                      ArgListTy &Args, SelectionDAG &DAG) {
797   // Count how many bytes are to be pushed on the stack.
798   unsigned NumBytes = 0;
799
800   // Keep track of the number of integer regs passed so far.  This can be either
801   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
802   // used).
803   unsigned NumIntRegs = 0;
804
805   for (unsigned i = 0, e = Args.size(); i != e; ++i)
806     switch (getValueType(Args[i].second)) {
807     default: assert(0 && "Unknown value type!");
808     case MVT::i1:
809     case MVT::i8:
810     case MVT::i16:
811     case MVT::i32:
812       if (NumIntRegs < 2) {
813         ++NumIntRegs;
814         break;
815       }
816       // fall through
817     case MVT::f32:
818       NumBytes += 4;
819       break;
820     case MVT::i64:
821       if (NumIntRegs == 0) {
822         NumIntRegs = 2;
823         break;
824       } else if (NumIntRegs == 1) {
825         NumIntRegs = 2;
826         NumBytes += 4;
827         break;
828       }
829
830       // fall through
831     case MVT::f64:
832       NumBytes += 8;
833       break;
834     }
835
836   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
837   // arguments and the arguments after the retaddr has been pushed are aligned.
838   if ((NumBytes & 7) == 0)
839     NumBytes += 4;
840
841   Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
842                       DAG.getConstant(NumBytes, getPointerTy()));
843
844   // Arguments go on the stack in reverse order, as specified by the ABI.
845   unsigned ArgOffset = 0;
846   SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
847   NumIntRegs = 0;
848   std::vector<SDOperand> Stores;
849   std::vector<SDOperand> RegValuesToPass;
850   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
851     switch (getValueType(Args[i].second)) {
852     default: assert(0 && "Unexpected ValueType for argument!");
853     case MVT::i1:
854       Args[i].first = DAG.getNode(ISD::ANY_EXTEND, MVT::i8, Args[i].first);
855       // Fall through.
856     case MVT::i8:
857     case MVT::i16:
858     case MVT::i32:
859       if (NumIntRegs < 2) {
860         RegValuesToPass.push_back(Args[i].first);
861         ++NumIntRegs;
862         break;
863       }
864       // Fall through
865     case MVT::f32: {
866       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
867       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
868       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
869                                    Args[i].first, PtrOff,
870                                    DAG.getSrcValue(NULL)));
871       ArgOffset += 4;
872       break;
873     }
874     case MVT::i64:
875       if (NumIntRegs < 2) {    // Can pass part of it in regs?
876         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
877                                    Args[i].first, DAG.getConstant(1, MVT::i32));
878         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
879                                    Args[i].first, DAG.getConstant(0, MVT::i32));
880         RegValuesToPass.push_back(Lo);
881         ++NumIntRegs;
882         if (NumIntRegs < 2) {   // Pass both parts in regs?
883           RegValuesToPass.push_back(Hi);
884           ++NumIntRegs;
885         } else {
886           // Pass the high part in memory.
887           SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
888           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
889           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
890                                        Hi, PtrOff, DAG.getSrcValue(NULL)));
891           ArgOffset += 4;
892         }
893         break;
894       }
895       // Fall through
896     case MVT::f64:
897       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
898       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
899       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
900                                    Args[i].first, PtrOff,
901                                    DAG.getSrcValue(NULL)));
902       ArgOffset += 8;
903       break;
904     }
905   }
906   if (!Stores.empty())
907     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
908
909   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
910   // arguments and the arguments after the retaddr has been pushed are aligned.
911   if ((ArgOffset & 7) == 0)
912     ArgOffset += 4;
913
914   std::vector<MVT::ValueType> RetVals;
915   MVT::ValueType RetTyVT = getValueType(RetTy);
916
917   RetVals.push_back(MVT::Other);
918
919   // The result values produced have to be legal.  Promote the result.
920   switch (RetTyVT) {
921   case MVT::isVoid: break;
922   default:
923     RetVals.push_back(RetTyVT);
924     break;
925   case MVT::i1:
926   case MVT::i8:
927   case MVT::i16:
928     RetVals.push_back(MVT::i32);
929     break;
930   case MVT::f32:
931     if (X86ScalarSSE)
932       RetVals.push_back(MVT::f32);
933     else
934       RetVals.push_back(MVT::f64);
935     break;
936   case MVT::i64:
937     RetVals.push_back(MVT::i32);
938     RetVals.push_back(MVT::i32);
939     break;
940   }
941
942   if (!X86PatIsel) {
943     // Build a sequence of copy-to-reg nodes chained together with token chain
944     // and flag operands which copy the outgoing args into registers.
945     SDOperand InFlag;
946     for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
947       unsigned CCReg;
948       SDOperand RegToPass = RegValuesToPass[i];
949       switch (RegToPass.getValueType()) {
950       default: assert(0 && "Bad thing to pass in regs");
951       case MVT::i8:
952         CCReg = (i == 0) ? X86::AL  : X86::DL;
953         break;
954       case MVT::i16:
955         CCReg = (i == 0) ? X86::AX  : X86::DX;
956         break;
957       case MVT::i32:
958         CCReg = (i == 0) ? X86::EAX : X86::EDX;
959         break;
960       }
961
962       Chain = DAG.getCopyToReg(Chain, CCReg, RegToPass, InFlag);
963       InFlag = Chain.getValue(1);
964     }
965
966     std::vector<MVT::ValueType> NodeTys;
967     NodeTys.push_back(MVT::Other);   // Returns a chain
968     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
969     std::vector<SDOperand> Ops;
970     Ops.push_back(Chain);
971     Ops.push_back(Callee);
972     if (InFlag.Val)
973       Ops.push_back(InFlag);
974
975     // FIXME: Do not generate X86ISD::TAILCALL for now.
976     Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
977     InFlag = Chain.getValue(1);
978
979     NodeTys.clear();
980     NodeTys.push_back(MVT::Other);   // Returns a chain
981     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
982     Ops.clear();
983     Ops.push_back(Chain);
984     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
985     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
986     Ops.push_back(InFlag);
987     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
988     InFlag = Chain.getValue(1);
989     
990     SDOperand RetVal;
991     if (RetTyVT != MVT::isVoid) {
992       switch (RetTyVT) {
993       default: assert(0 && "Unknown value type to return!");
994       case MVT::i1:
995       case MVT::i8:
996         RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
997         Chain = RetVal.getValue(1);
998         if (RetTyVT == MVT::i1) 
999           RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
1000         break;
1001       case MVT::i16:
1002         RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
1003         Chain = RetVal.getValue(1);
1004         break;
1005       case MVT::i32:
1006         RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1007         Chain = RetVal.getValue(1);
1008         break;
1009       case MVT::i64: {
1010         SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1011         SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
1012                                           Lo.getValue(2));
1013         RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
1014         Chain = Hi.getValue(1);
1015         break;
1016       }
1017       case MVT::f32:
1018       case MVT::f64: {
1019         std::vector<MVT::ValueType> Tys;
1020         Tys.push_back(MVT::f64);
1021         Tys.push_back(MVT::Other);
1022         Tys.push_back(MVT::Flag);
1023         std::vector<SDOperand> Ops;
1024         Ops.push_back(Chain);
1025         Ops.push_back(InFlag);
1026         RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
1027         Chain  = RetVal.getValue(1);
1028         InFlag = RetVal.getValue(2);
1029         if (X86ScalarSSE) {
1030           // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
1031           // shouldn't be necessary except that RFP cannot be live across
1032           // multiple blocks. When stackifier is fixed, they can be uncoupled.
1033           MachineFunction &MF = DAG.getMachineFunction();
1034           int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1035           SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1036           Tys.clear();
1037           Tys.push_back(MVT::Other);
1038           Ops.clear();
1039           Ops.push_back(Chain);
1040           Ops.push_back(RetVal);
1041           Ops.push_back(StackSlot);
1042           Ops.push_back(DAG.getValueType(RetTyVT));
1043           Ops.push_back(InFlag);
1044           Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1045           RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
1046                                DAG.getSrcValue(NULL));
1047           Chain = RetVal.getValue(1);
1048         }
1049
1050         if (RetTyVT == MVT::f32 && !X86ScalarSSE)
1051           // FIXME: we would really like to remember that this FP_ROUND
1052           // operation is okay to eliminate if we allow excess FP precision.
1053           RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
1054         break;
1055       }
1056       }
1057     }
1058
1059     return std::make_pair(RetVal, Chain);
1060   } else {
1061     std::vector<SDOperand> Ops;
1062     Ops.push_back(Chain);
1063     Ops.push_back(Callee);
1064     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1065     // Callee pops all arg values on the stack.
1066     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1067
1068     // Pass register arguments as needed.
1069     Ops.insert(Ops.end(), RegValuesToPass.begin(), RegValuesToPass.end());
1070
1071     SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1072                                     RetVals, Ops);
1073     Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
1074
1075     SDOperand ResultVal;
1076     switch (RetTyVT) {
1077     case MVT::isVoid: break;
1078     default:
1079       ResultVal = TheCall.getValue(1);
1080       break;
1081     case MVT::i1:
1082     case MVT::i8:
1083     case MVT::i16:
1084       ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
1085       break;
1086     case MVT::f32:
1087       // FIXME: we would really like to remember that this FP_ROUND operation is
1088       // okay to eliminate if we allow excess FP precision.
1089       ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
1090       break;
1091     case MVT::i64:
1092       ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
1093                               TheCall.getValue(2));
1094       break;
1095     }
1096
1097     return std::make_pair(ResultVal, Chain);
1098   }
1099 }
1100
1101 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1102   if (ReturnAddrIndex == 0) {
1103     // Set up a frame object for the return address.
1104     MachineFunction &MF = DAG.getMachineFunction();
1105     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1106   }
1107
1108   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
1109 }
1110
1111
1112
1113 std::pair<SDOperand, SDOperand> X86TargetLowering::
1114 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
1115                         SelectionDAG &DAG) {
1116   SDOperand Result;
1117   if (Depth)        // Depths > 0 not supported yet!
1118     Result = DAG.getConstant(0, getPointerTy());
1119   else {
1120     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
1121     if (!isFrameAddress)
1122       // Just load the return address
1123       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
1124                            DAG.getSrcValue(NULL));
1125     else
1126       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
1127                            DAG.getConstant(4, MVT::i32));
1128   }
1129   return std::make_pair(Result, Chain);
1130 }
1131
1132 /// getCondBrOpcodeForX86CC - Returns the X86 conditional branch opcode
1133 /// which corresponds to the condition code.
1134 static unsigned getCondBrOpcodeForX86CC(unsigned X86CC) {
1135   switch (X86CC) {
1136   default: assert(0 && "Unknown X86 conditional code!");
1137   case X86ISD::COND_A:  return X86::JA;
1138   case X86ISD::COND_AE: return X86::JAE;
1139   case X86ISD::COND_B:  return X86::JB;
1140   case X86ISD::COND_BE: return X86::JBE;
1141   case X86ISD::COND_E:  return X86::JE;
1142   case X86ISD::COND_G:  return X86::JG;
1143   case X86ISD::COND_GE: return X86::JGE;
1144   case X86ISD::COND_L:  return X86::JL;
1145   case X86ISD::COND_LE: return X86::JLE;
1146   case X86ISD::COND_NE: return X86::JNE;
1147   case X86ISD::COND_NO: return X86::JNO;
1148   case X86ISD::COND_NP: return X86::JNP;
1149   case X86ISD::COND_NS: return X86::JNS;
1150   case X86ISD::COND_O:  return X86::JO;
1151   case X86ISD::COND_P:  return X86::JP;
1152   case X86ISD::COND_S:  return X86::JS;
1153   }
1154 }
1155
1156 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1157 /// specific condition code. It returns a false if it cannot do a direct
1158 /// translation. X86CC is the translated CondCode. Flip is set to true if the
1159 /// the order of comparison operands should be flipped.
1160 static bool translateX86CC(SDOperand CC, bool isFP, unsigned &X86CC, bool &Flip) {
1161   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1162   Flip = false;
1163   X86CC = X86ISD::COND_INVALID;
1164   if (!isFP) {
1165     switch (SetCCOpcode) {
1166     default: break;
1167     case ISD::SETEQ:  X86CC = X86ISD::COND_E;  break;
1168     case ISD::SETGT:  X86CC = X86ISD::COND_G;  break;
1169     case ISD::SETGE:  X86CC = X86ISD::COND_GE; break;
1170     case ISD::SETLT:  X86CC = X86ISD::COND_L;  break;
1171     case ISD::SETLE:  X86CC = X86ISD::COND_LE; break;
1172     case ISD::SETNE:  X86CC = X86ISD::COND_NE; break;
1173     case ISD::SETULT: X86CC = X86ISD::COND_B;  break;
1174     case ISD::SETUGT: X86CC = X86ISD::COND_A;  break;
1175     case ISD::SETULE: X86CC = X86ISD::COND_BE; break;
1176     case ISD::SETUGE: X86CC = X86ISD::COND_AE; break;
1177     }
1178   } else {
1179     // On a floating point condition, the flags are set as follows:
1180     // ZF  PF  CF   op
1181     //  0 | 0 | 0 | X > Y
1182     //  0 | 0 | 1 | X < Y
1183     //  1 | 0 | 0 | X == Y
1184     //  1 | 1 | 1 | unordered
1185     switch (SetCCOpcode) {
1186     default: break;
1187     case ISD::SETUEQ:
1188     case ISD::SETEQ: X86CC = X86ISD::COND_E;  break;
1189     case ISD::SETOLE: Flip = true; // Fallthrough
1190     case ISD::SETOGT:
1191     case ISD::SETGT: X86CC = X86ISD::COND_A;  break;
1192     case ISD::SETOLT: Flip = true; // Fallthrough
1193     case ISD::SETOGE:
1194     case ISD::SETGE: X86CC = X86ISD::COND_AE; break;
1195     case ISD::SETUGE: Flip = true; // Fallthrough
1196     case ISD::SETULT:
1197     case ISD::SETLT: X86CC = X86ISD::COND_B;  break;
1198     case ISD::SETUGT: Flip = true; // Fallthrough
1199     case ISD::SETULE:
1200     case ISD::SETLE: X86CC = X86ISD::COND_BE; break;
1201     case ISD::SETONE:
1202     case ISD::SETNE: X86CC = X86ISD::COND_NE; break;
1203     case ISD::SETUO: X86CC = X86ISD::COND_P;  break;
1204     case ISD::SETO:  X86CC = X86ISD::COND_NP; break;
1205     }
1206   }
1207
1208   return X86CC != X86ISD::COND_INVALID;
1209 }
1210
1211 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1212 /// code. Current x86 isa includes the following FP cmov instructions:
1213 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1214 static bool hasFPCMov(unsigned X86CC) {
1215   switch (X86CC) {
1216   default:
1217     return false;
1218   case X86ISD::COND_B:
1219   case X86ISD::COND_BE:
1220   case X86ISD::COND_E:
1221   case X86ISD::COND_P:
1222   case X86ISD::COND_A:
1223   case X86ISD::COND_AE:
1224   case X86ISD::COND_NE:
1225   case X86ISD::COND_NP:
1226     return true;
1227   }
1228 }
1229
1230 MachineBasicBlock *
1231 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1232                                            MachineBasicBlock *BB) {
1233   switch (MI->getOpcode()) {
1234   default: assert(false && "Unexpected instr type to insert");
1235   case X86::CMOV_FR32:
1236   case X86::CMOV_FR64: {
1237     // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1238     // control-flow pattern.  The incoming instruction knows the destination vreg
1239     // to set, the condition code register to branch on, the true/false values to
1240     // select between, and a branch opcode to use.
1241     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1242     ilist<MachineBasicBlock>::iterator It = BB;
1243     ++It;
1244   
1245     //  thisMBB:
1246     //  ...
1247     //   TrueVal = ...
1248     //   cmpTY ccX, r1, r2
1249     //   bCC copy1MBB
1250     //   fallthrough --> copy0MBB
1251     MachineBasicBlock *thisMBB = BB;
1252     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1253     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1254     unsigned Opc = getCondBrOpcodeForX86CC(MI->getOperand(3).getImmedValue());
1255     BuildMI(BB, Opc, 1).addMBB(sinkMBB);
1256     MachineFunction *F = BB->getParent();
1257     F->getBasicBlockList().insert(It, copy0MBB);
1258     F->getBasicBlockList().insert(It, sinkMBB);
1259     // Update machine-CFG edges
1260     BB->addSuccessor(copy0MBB);
1261     BB->addSuccessor(sinkMBB);
1262   
1263     //  copy0MBB:
1264     //   %FalseValue = ...
1265     //   # fallthrough to sinkMBB
1266     BB = copy0MBB;
1267   
1268     // Update machine-CFG edges
1269     BB->addSuccessor(sinkMBB);
1270   
1271     //  sinkMBB:
1272     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1273     //  ...
1274     BB = sinkMBB;
1275     BuildMI(BB, X86::PHI, 4, MI->getOperand(0).getReg())
1276       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1277       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1278
1279     delete MI;   // The pseudo instruction is gone now.
1280     return BB;
1281   }
1282
1283   case X86::FP_TO_INT16_IN_MEM:
1284   case X86::FP_TO_INT32_IN_MEM:
1285   case X86::FP_TO_INT64_IN_MEM: {
1286     // Change the floating point control register to use "round towards zero"
1287     // mode when truncating to an integer value.
1288     MachineFunction *F = BB->getParent();
1289     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1290     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1291
1292     // Load the old value of the high byte of the control word...
1293     unsigned OldCW =
1294       F->getSSARegMap()->createVirtualRegister(X86::R16RegisterClass);
1295     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
1296
1297     // Set the high part to be round to zero...
1298     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
1299
1300     // Reload the modified control word now...
1301     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1302
1303     // Restore the memory image of control word to original value
1304     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
1305
1306     // Get the X86 opcode to use.
1307     unsigned Opc;
1308     switch (MI->getOpcode()) {
1309     default: assert(0 && "illegal opcode!");
1310     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
1311     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
1312     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
1313     }
1314
1315     X86AddressMode AM;
1316     MachineOperand &Op = MI->getOperand(0);
1317     if (Op.isRegister()) {
1318       AM.BaseType = X86AddressMode::RegBase;
1319       AM.Base.Reg = Op.getReg();
1320     } else {
1321       AM.BaseType = X86AddressMode::FrameIndexBase;
1322       AM.Base.FrameIndex = Op.getFrameIndex();
1323     }
1324     Op = MI->getOperand(1);
1325     if (Op.isImmediate())
1326       AM.Scale = Op.getImmedValue();
1327     Op = MI->getOperand(2);
1328     if (Op.isImmediate())
1329       AM.IndexReg = Op.getImmedValue();
1330     Op = MI->getOperand(3);
1331     if (Op.isGlobalAddress()) {
1332       AM.GV = Op.getGlobal();
1333     } else {
1334       AM.Disp = Op.getImmedValue();
1335     }
1336     addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(MI->getOperand(4).getReg());
1337
1338     // Reload the original control word now.
1339     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1340
1341     delete MI;   // The pseudo instruction is gone now.
1342     return BB;
1343   }
1344   }
1345 }
1346
1347
1348 //===----------------------------------------------------------------------===//
1349 //                           X86 Custom Lowering Hooks
1350 //===----------------------------------------------------------------------===//
1351
1352 /// LowerOperation - Provide custom lowering hooks for some operations.
1353 ///
1354 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1355   switch (Op.getOpcode()) {
1356   default: assert(0 && "Should not custom lower this!");
1357   case ISD::ADD_PARTS:
1358   case ISD::SUB_PARTS: {
1359     assert(Op.getNumOperands() == 4 && Op.getValueType() == MVT::i32 &&
1360            "Not an i64 add/sub!");
1361     bool isAdd = Op.getOpcode() == ISD::ADD_PARTS;
1362     std::vector<MVT::ValueType> Tys;
1363     Tys.push_back(MVT::i32);
1364     Tys.push_back(MVT::Flag);
1365     std::vector<SDOperand> Ops;
1366     Ops.push_back(Op.getOperand(0));
1367     Ops.push_back(Op.getOperand(2));
1368     SDOperand Lo = DAG.getNode(isAdd ? X86ISD::ADD_FLAG : X86ISD::SUB_FLAG,
1369                                Tys, Ops);
1370     SDOperand Hi = DAG.getNode(isAdd ? X86ISD::ADC : X86ISD::SBB, MVT::i32,
1371                                Op.getOperand(1), Op.getOperand(3),
1372                                Lo.getValue(1));
1373     Tys.clear();
1374     Tys.push_back(MVT::i32);
1375     Tys.push_back(MVT::i32);
1376     Ops.clear();
1377     Ops.push_back(Lo);
1378     Ops.push_back(Hi);
1379     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1380   }
1381   case ISD::SHL_PARTS:
1382   case ISD::SRA_PARTS:
1383   case ISD::SRL_PARTS: {
1384     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
1385            "Not an i64 shift!");
1386     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
1387     SDOperand ShOpLo = Op.getOperand(0);
1388     SDOperand ShOpHi = Op.getOperand(1);
1389     SDOperand ShAmt  = Op.getOperand(2);
1390     SDOperand Tmp1 = isSRA ? DAG.getNode(ISD::SRA, MVT::i32, ShOpHi,
1391                                          DAG.getConstant(31, MVT::i8))
1392                            : DAG.getConstant(0, MVT::i32);
1393
1394     SDOperand Tmp2, Tmp3;
1395     if (Op.getOpcode() == ISD::SHL_PARTS) {
1396       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
1397       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
1398     } else {
1399       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
1400       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
1401     }
1402
1403     SDOperand InFlag = DAG.getNode(X86ISD::TEST, MVT::Flag,
1404                                    ShAmt, DAG.getConstant(32, MVT::i8));
1405
1406     SDOperand Hi, Lo;
1407     SDOperand CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1408
1409     std::vector<MVT::ValueType> Tys;
1410     Tys.push_back(MVT::i32);
1411     Tys.push_back(MVT::Flag);
1412     std::vector<SDOperand> Ops;
1413     if (Op.getOpcode() == ISD::SHL_PARTS) {
1414       Ops.push_back(Tmp2);
1415       Ops.push_back(Tmp3);
1416       Ops.push_back(CC);
1417       Ops.push_back(InFlag);
1418       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1419       InFlag = Hi.getValue(1);
1420
1421       Ops.clear();
1422       Ops.push_back(Tmp3);
1423       Ops.push_back(Tmp1);
1424       Ops.push_back(CC);
1425       Ops.push_back(InFlag);
1426       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1427     } else {
1428       Ops.push_back(Tmp2);
1429       Ops.push_back(Tmp3);
1430       Ops.push_back(CC);
1431       Ops.push_back(InFlag);
1432       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1433       InFlag = Lo.getValue(1);
1434
1435       Ops.clear();
1436       Ops.push_back(Tmp3);
1437       Ops.push_back(Tmp1);
1438       Ops.push_back(CC);
1439       Ops.push_back(InFlag);
1440       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1441     }
1442
1443     Tys.clear();
1444     Tys.push_back(MVT::i32);
1445     Tys.push_back(MVT::i32);
1446     Ops.clear();
1447     Ops.push_back(Lo);
1448     Ops.push_back(Hi);
1449     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1450   }
1451   case ISD::SINT_TO_FP: {
1452     assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
1453            Op.getOperand(0).getValueType() >= MVT::i16 &&
1454            "Unknown SINT_TO_FP to lower!");
1455
1456     SDOperand Result;
1457     MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
1458     unsigned Size = MVT::getSizeInBits(SrcVT)/8;
1459     MachineFunction &MF = DAG.getMachineFunction();
1460     int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1461     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1462     SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other,
1463                                   DAG.getEntryNode(), Op.getOperand(0),
1464                                   StackSlot, DAG.getSrcValue(NULL));
1465
1466     // Build the FILD
1467     std::vector<MVT::ValueType> Tys;
1468     Tys.push_back(MVT::f64);
1469     Tys.push_back(MVT::Other);
1470     Tys.push_back(MVT::Flag);
1471     std::vector<SDOperand> Ops;
1472     Ops.push_back(Chain);
1473     Ops.push_back(StackSlot);
1474     Ops.push_back(DAG.getValueType(SrcVT));
1475     Result = DAG.getNode(X86ISD::FILD, Tys, Ops);
1476
1477     if (X86ScalarSSE) {
1478       Chain = Result.getValue(1);
1479       SDOperand InFlag = Result.getValue(2);
1480
1481       // FIXME: Currently the FST is flagged to the FILD. This
1482       // shouldn't be necessary except that RFP cannot be live across
1483       // multiple blocks. When stackifier is fixed, they can be uncoupled.
1484       MachineFunction &MF = DAG.getMachineFunction();
1485       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1486       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1487       std::vector<MVT::ValueType> Tys;
1488       Tys.push_back(MVT::Other);
1489       std::vector<SDOperand> Ops;
1490       Ops.push_back(Chain);
1491       Ops.push_back(Result);
1492       Ops.push_back(StackSlot);
1493       Ops.push_back(DAG.getValueType(Op.getValueType()));
1494       Ops.push_back(InFlag);
1495       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1496       Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
1497                            DAG.getSrcValue(NULL));
1498     }
1499
1500     return Result;
1501   }
1502   case ISD::FP_TO_SINT: {
1503     assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
1504            "Unknown FP_TO_SINT to lower!");
1505     // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
1506     // stack slot.
1507     MachineFunction &MF = DAG.getMachineFunction();
1508     unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
1509     int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1510     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1511
1512     unsigned Opc;
1513     switch (Op.getValueType()) {
1514     default: assert(0 && "Invalid FP_TO_SINT to lower!");
1515     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
1516     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
1517     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
1518     }
1519
1520     SDOperand Chain = DAG.getEntryNode();
1521     SDOperand Value = Op.getOperand(0);
1522     if (X86ScalarSSE) {
1523       assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
1524       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, StackSlot, 
1525                           DAG.getSrcValue(0));
1526       std::vector<MVT::ValueType> Tys;
1527       Tys.push_back(MVT::f64);
1528       Tys.push_back(MVT::Other);
1529       std::vector<SDOperand> Ops;
1530       Ops.push_back(Chain);
1531       Ops.push_back(StackSlot);
1532       Ops.push_back(DAG.getValueType(Op.getOperand(0).getValueType()));
1533       Value = DAG.getNode(X86ISD::FLD, Tys, Ops);
1534       Chain = Value.getValue(1);
1535       SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1536       StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1537     }
1538
1539     // Build the FP_TO_INT*_IN_MEM
1540     std::vector<SDOperand> Ops;
1541     Ops.push_back(Chain);
1542     Ops.push_back(Value);
1543     Ops.push_back(StackSlot);
1544     SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
1545
1546     // Load the result.
1547     return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
1548                        DAG.getSrcValue(NULL));
1549   }
1550   case ISD::READCYCLECOUNTER: {
1551     std::vector<MVT::ValueType> Tys;
1552     Tys.push_back(MVT::Other);
1553     Tys.push_back(MVT::Flag);
1554     std::vector<SDOperand> Ops;
1555     Ops.push_back(Op.getOperand(0));
1556     SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, Ops);
1557     Ops.clear();
1558     Ops.push_back(DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1)));
1559     Ops.push_back(DAG.getCopyFromReg(Ops[0].getValue(1), X86::EDX, 
1560                                      MVT::i32, Ops[0].getValue(2)));
1561     Ops.push_back(Ops[1].getValue(1));
1562     Tys[0] = Tys[1] = MVT::i32;
1563     Tys.push_back(MVT::Other);
1564     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1565   }
1566   case ISD::FABS: {
1567     MVT::ValueType VT = Op.getValueType();
1568     SDOperand Mask = (VT == MVT::f64)
1569       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), MVT::f64)
1570       : DAG.getConstantFP(BitsToFloat (~(1U   << 31)), MVT::f32);
1571     return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
1572   }
1573   case ISD::SETCC: {
1574     assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
1575     SDOperand Cond;
1576     SDOperand CC = Op.getOperand(2);
1577     ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1578     bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
1579     bool Flip;
1580     unsigned X86CC;
1581     if (translateX86CC(CC, isFP, X86CC, Flip)) {
1582       if (Flip)
1583         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1584                            Op.getOperand(1), Op.getOperand(0));
1585       else
1586         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1587                            Op.getOperand(0), Op.getOperand(1));
1588       return DAG.getNode(X86ISD::SETCC, MVT::i8, 
1589                          DAG.getConstant(X86CC, MVT::i8), Cond);
1590     } else {
1591       assert(isFP && "Illegal integer SetCC!");
1592
1593       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1594                          Op.getOperand(0), Op.getOperand(1));
1595       std::vector<MVT::ValueType> Tys;
1596       std::vector<SDOperand> Ops;
1597       switch (SetCCOpcode) {
1598       default: assert(false && "Illegal floating point SetCC!");
1599       case ISD::SETOEQ: {  // !PF & ZF
1600         Tys.push_back(MVT::i8);
1601         Tys.push_back(MVT::Flag);
1602         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
1603         Ops.push_back(Cond);
1604         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1605         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1606                                      DAG.getConstant(X86ISD::COND_E, MVT::i8),
1607                                      Tmp1.getValue(1));
1608         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
1609       }
1610       case ISD::SETUNE: {  // PF | !ZF
1611         Tys.push_back(MVT::i8);
1612         Tys.push_back(MVT::Flag);
1613         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
1614         Ops.push_back(Cond);
1615         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1616         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1617                                      DAG.getConstant(X86ISD::COND_NE, MVT::i8),
1618                                      Tmp1.getValue(1));
1619         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
1620       }
1621       }
1622     }
1623   }
1624   case ISD::SELECT: {
1625     MVT::ValueType VT = Op.getValueType();
1626     bool isFP      = MVT::isFloatingPoint(VT);
1627     bool isFPStack = isFP && !X86ScalarSSE;
1628     bool isFPSSE   = isFP && X86ScalarSSE;
1629     bool addTest   = false;
1630     SDOperand Op0 = Op.getOperand(0);
1631     SDOperand Cond, CC;
1632     if (Op0.getOpcode() == ISD::SETCC)
1633       Op0 = LowerOperation(Op0, DAG);
1634
1635     if (Op0.getOpcode() == X86ISD::SETCC) {
1636       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1637       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1638       // have another use it will be eliminated.
1639       // If the X86ISD::SETCC has more than one use, then it's probably better
1640       // to use a test instead of duplicating the X86ISD::CMP (for register
1641       // pressure reason).
1642       if (Op0.getOperand(1).getOpcode() == X86ISD::CMP) {
1643         if (!Op0.hasOneUse()) {
1644           std::vector<MVT::ValueType> Tys;
1645           for (unsigned i = 0; i < Op0.Val->getNumValues(); ++i)
1646             Tys.push_back(Op0.Val->getValueType(i));
1647           std::vector<SDOperand> Ops;
1648           for (unsigned i = 0; i < Op0.getNumOperands(); ++i)
1649             Ops.push_back(Op0.getOperand(i));
1650           Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1651         }
1652
1653         CC   = Op0.getOperand(0);
1654         Cond = Op0.getOperand(1);
1655         // Make a copy as flag result cannot be used by more than one.
1656         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1657                            Cond.getOperand(0), Cond.getOperand(1));
1658         addTest =
1659           isFPStack && !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
1660       } else
1661         addTest = true;
1662     } else
1663       addTest = true;
1664
1665     if (addTest) {
1666       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1667       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Op0, Op0);
1668     }
1669
1670     std::vector<MVT::ValueType> Tys;
1671     Tys.push_back(Op.getValueType());
1672     Tys.push_back(MVT::Flag);
1673     std::vector<SDOperand> Ops;
1674     // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
1675     // condition is true.
1676     Ops.push_back(Op.getOperand(2));
1677     Ops.push_back(Op.getOperand(1));
1678     Ops.push_back(CC);
1679     Ops.push_back(Cond);
1680     return DAG.getNode(X86ISD::CMOV, Tys, Ops);
1681   }
1682   case ISD::BRCOND: {
1683     bool addTest = false;
1684     SDOperand Cond  = Op.getOperand(1);
1685     SDOperand Dest  = Op.getOperand(2);
1686     SDOperand CC;
1687     if (Cond.getOpcode() == ISD::SETCC)
1688       Cond = LowerOperation(Cond, DAG);
1689
1690     if (Cond.getOpcode() == X86ISD::SETCC) {
1691       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1692       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1693       // have another use it will be eliminated.
1694       // If the X86ISD::SETCC has more than one use, then it's probably better
1695       // to use a test instead of duplicating the X86ISD::CMP (for register
1696       // pressure reason).
1697       if (Cond.getOperand(1).getOpcode() == X86ISD::CMP) {
1698         if (!Cond.hasOneUse()) {
1699           std::vector<MVT::ValueType> Tys;
1700           for (unsigned i = 0; i < Cond.Val->getNumValues(); ++i)
1701             Tys.push_back(Cond.Val->getValueType(i));
1702           std::vector<SDOperand> Ops;
1703           for (unsigned i = 0; i < Cond.getNumOperands(); ++i)
1704             Ops.push_back(Cond.getOperand(i));
1705           Cond = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1706         }
1707
1708         CC   = Cond.getOperand(0);
1709         Cond = Cond.getOperand(1);
1710         // Make a copy as flag result cannot be used by more than one.
1711         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1712                            Cond.getOperand(0), Cond.getOperand(1));
1713       } else
1714         addTest = true;
1715     } else
1716       addTest = true;
1717
1718     if (addTest) {
1719       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1720       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Cond, Cond);
1721     }
1722     return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
1723                        Op.getOperand(0), Op.getOperand(2), CC, Cond);
1724   }
1725   case ISD::MEMSET: {
1726     SDOperand InFlag;
1727     SDOperand Chain = Op.getOperand(0);
1728     unsigned Align =
1729       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1730     if (Align == 0) Align = 1;
1731
1732     MVT::ValueType AVT;
1733     SDOperand Count;
1734     if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
1735       unsigned ValReg;
1736       unsigned Val = ValC->getValue() & 255;
1737
1738       // If the value is a constant, then we can potentially use larger sets.
1739       switch (Align & 3) {
1740       case 2:   // WORD aligned
1741         AVT = MVT::i16;
1742         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1743           Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1744         else
1745           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1746                               DAG.getConstant(1, MVT::i8));
1747         Val    = (Val << 8) | Val;
1748         ValReg = X86::AX;
1749         break;
1750       case 0:   // DWORD aligned
1751         AVT = MVT::i32;
1752         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1753           Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1754         else
1755           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1756                               DAG.getConstant(2, MVT::i8));
1757         Val = (Val << 8)  | Val;
1758         Val = (Val << 16) | Val;
1759         ValReg = X86::EAX;
1760         break;
1761       default:  // Byte aligned
1762         AVT = MVT::i8;
1763         Count = Op.getOperand(3);
1764         ValReg = X86::AL;
1765         break;
1766       }
1767
1768       Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
1769                                 InFlag);
1770       InFlag = Chain.getValue(1);
1771     } else {
1772       AVT    = MVT::i8;
1773       Count  = Op.getOperand(3);
1774       Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
1775       InFlag = Chain.getValue(1);
1776     }
1777
1778     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1779     InFlag = Chain.getValue(1);
1780     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1781     InFlag = Chain.getValue(1);
1782
1783     return DAG.getNode(X86ISD::REP_STOS, MVT::Other, Chain,
1784                        DAG.getValueType(AVT), InFlag);
1785   }
1786   case ISD::MEMCPY: {
1787     SDOperand Chain = Op.getOperand(0);
1788     unsigned Align =
1789       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1790     if (Align == 0) Align = 1;
1791
1792     MVT::ValueType AVT;
1793     SDOperand Count;
1794     switch (Align & 3) {
1795     case 2:   // WORD aligned
1796       AVT = MVT::i16;
1797       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1798         Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1799       else
1800         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1801                             DAG.getConstant(1, MVT::i8));
1802       break;
1803     case 0:   // DWORD aligned
1804       AVT = MVT::i32;
1805       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1806         Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1807       else
1808         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1809                             DAG.getConstant(2, MVT::i8));
1810       break;
1811     default:  // Byte aligned
1812       AVT = MVT::i8;
1813       Count = Op.getOperand(3);
1814       break;
1815     }
1816
1817     SDOperand InFlag;
1818     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1819     InFlag = Chain.getValue(1);
1820     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1821     InFlag = Chain.getValue(1);
1822     Chain  = DAG.getCopyToReg(Chain, X86::ESI, Op.getOperand(2), InFlag);
1823     InFlag = Chain.getValue(1);
1824
1825     return DAG.getNode(X86ISD::REP_MOVS, MVT::Other, Chain,
1826                        DAG.getValueType(AVT), InFlag);
1827   }
1828   case ISD::GlobalAddress: {
1829     SDOperand Result;
1830     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1831     // For Darwin, external and weak symbols are indirect, so we want to load
1832     // the value at address GV, not the value of GV itself.  This means that
1833     // the GlobalAddress must be in the base or index register of the address,
1834     // not the GV offset field.
1835     if (getTargetMachine().
1836         getSubtarget<X86Subtarget>().getIndirectExternAndWeakGlobals() &&
1837         (GV->hasWeakLinkage() || GV->isExternal()))
1838       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(),
1839                            DAG.getTargetGlobalAddress(GV, getPointerTy()),
1840                            DAG.getSrcValue(NULL));
1841     return Result;
1842   }
1843   case ISD::VASTART: {
1844     // vastart just stores the address of the VarArgsFrameIndex slot into the
1845     // memory location argument.
1846     // FIXME: Replace MVT::i32 with PointerTy
1847     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
1848     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
1849                        Op.getOperand(1), Op.getOperand(2));
1850   }
1851   case ISD::RET: {
1852     SDOperand Copy;
1853     
1854     switch(Op.getNumOperands()) {
1855     default:
1856       assert(0 && "Do not know how to return this many arguments!");
1857       abort();
1858     case 1: 
1859       return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Op.getOperand(0),
1860                          DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1861     case 2: {
1862       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
1863       if (MVT::isInteger(ArgVT))
1864         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EAX, Op.getOperand(1),
1865                                 SDOperand());
1866       else if (!X86ScalarSSE) {
1867         std::vector<MVT::ValueType> Tys;
1868         Tys.push_back(MVT::Other);
1869         Tys.push_back(MVT::Flag);
1870         std::vector<SDOperand> Ops;
1871         Ops.push_back(Op.getOperand(0));
1872         Ops.push_back(Op.getOperand(1));
1873         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
1874       } else {
1875         // Spill the value to memory and reload it into top of stack.
1876         unsigned Size = MVT::getSizeInBits(ArgVT)/8;
1877         MachineFunction &MF = DAG.getMachineFunction();
1878         int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1879         SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1880         SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), 
1881                                       Op.getOperand(1), StackSlot, 
1882                                       DAG.getSrcValue(0));
1883         std::vector<MVT::ValueType> Tys;
1884         Tys.push_back(MVT::f64);
1885         Tys.push_back(MVT::Other);
1886         std::vector<SDOperand> Ops;
1887         Ops.push_back(Chain);
1888         Ops.push_back(StackSlot);
1889         Ops.push_back(DAG.getValueType(ArgVT));
1890         Copy = DAG.getNode(X86ISD::FLD, Tys, Ops);
1891         Tys.clear();
1892         Tys.push_back(MVT::Other);
1893         Tys.push_back(MVT::Flag);
1894         Ops.clear();
1895         Ops.push_back(Copy.getValue(1));
1896         Ops.push_back(Copy);
1897         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
1898       }
1899       break;
1900     }
1901     case 3:
1902       Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EDX, Op.getOperand(2), 
1903                               SDOperand());
1904       Copy = DAG.getCopyToReg(Copy, X86::EAX,Op.getOperand(1),Copy.getValue(1));
1905       break;
1906     }
1907     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other,
1908                        Copy, DAG.getConstant(getBytesToPopOnReturn(), MVT::i16),
1909                        Copy.getValue(1));
1910   }
1911   }
1912 }
1913
1914 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
1915   switch (Opcode) {
1916   default: return NULL;
1917   case X86ISD::ADD_FLAG:           return "X86ISD::ADD_FLAG";
1918   case X86ISD::SUB_FLAG:           return "X86ISD::SUB_FLAG";
1919   case X86ISD::ADC:                return "X86ISD::ADC";
1920   case X86ISD::SBB:                return "X86ISD::SBB";
1921   case X86ISD::SHLD:               return "X86ISD::SHLD";
1922   case X86ISD::SHRD:               return "X86ISD::SHRD";
1923   case X86ISD::FAND:               return "X86ISD::FAND";
1924   case X86ISD::FILD:               return "X86ISD::FILD";
1925   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
1926   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
1927   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
1928   case X86ISD::FLD:                return "X86ISD::FLD";
1929   case X86ISD::FST:                return "X86ISD::FST";
1930   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
1931   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
1932   case X86ISD::CALL:               return "X86ISD::CALL";
1933   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
1934   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
1935   case X86ISD::CMP:                return "X86ISD::CMP";
1936   case X86ISD::TEST:               return "X86ISD::TEST";
1937   case X86ISD::SETCC:              return "X86ISD::SETCC";
1938   case X86ISD::CMOV:               return "X86ISD::CMOV";
1939   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
1940   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
1941   case X86ISD::REP_STOS:           return "X86ISD::RET_STOS";
1942   case X86ISD::REP_MOVS:           return "X86ISD::RET_MOVS";
1943   }
1944 }
1945
1946 bool X86TargetLowering::isMaskedValueZeroForTargetNode(const SDOperand &Op,
1947                                                        uint64_t Mask) const {
1948
1949   unsigned Opc = Op.getOpcode();
1950
1951   switch (Opc) {
1952   default:
1953     assert(Opc >= ISD::BUILTIN_OP_END && "Expected a target specific node");
1954     break;
1955   case X86ISD::SETCC: return (Mask & 1) == 0;
1956   }
1957
1958   return false;
1959 }