convert the targets off the non-MachinePointerInfo of getLoad.
[oota-llvm.git] / lib / Target / Alpha / AlphaISelLowering.cpp
1 //===-- AlphaISelLowering.cpp - Alpha DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AlphaISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AlphaISelLowering.h"
15 #include "AlphaTargetMachine.h"
16 #include "AlphaMachineFunctionInfo.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Function.h"
28 #include "llvm/Module.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 /// AddLiveIn - This helper function adds the specified physical register to the
36 /// MachineFunction as a live in value.  It also creates a corresponding virtual
37 /// register for it.
38 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
39                           TargetRegisterClass *RC) {
40   assert(RC->contains(PReg) && "Not the correct regclass!");
41   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
42   MF.getRegInfo().addLiveIn(PReg, VReg);
43   return VReg;
44 }
45
46 AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM)
47   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
48   // Set up the TargetLowering object.
49   //I am having problems with shr n i8 1
50   setShiftAmountType(MVT::i64);
51   setBooleanContents(ZeroOrOneBooleanContent);
52
53   addRegisterClass(MVT::i64, Alpha::GPRCRegisterClass);
54   addRegisterClass(MVT::f64, Alpha::F8RCRegisterClass);
55   addRegisterClass(MVT::f32, Alpha::F4RCRegisterClass);
56
57   // We want to custom lower some of our intrinsics.
58   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
59
60   setLoadExtAction(ISD::EXTLOAD, MVT::i1,  Promote);
61   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
62
63   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
64   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
65
66   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
67   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
68   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
69
70   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
71
72   //  setOperationAction(ISD::BRIND,        MVT::Other,   Expand);
73   setOperationAction(ISD::BR_JT,        MVT::Other, Expand);
74   setOperationAction(ISD::BR_CC,        MVT::Other, Expand);
75   setOperationAction(ISD::SELECT_CC,    MVT::Other, Expand);
76
77   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
78
79   setOperationAction(ISD::FREM, MVT::f32, Expand);
80   setOperationAction(ISD::FREM, MVT::f64, Expand);
81
82   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
83   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
84   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
85   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
86
87   if (!TM.getSubtarget<AlphaSubtarget>().hasCT()) {
88     setOperationAction(ISD::CTPOP    , MVT::i64  , Expand);
89     setOperationAction(ISD::CTTZ     , MVT::i64  , Expand);
90     setOperationAction(ISD::CTLZ     , MVT::i64  , Expand);
91   }
92   setOperationAction(ISD::BSWAP    , MVT::i64, Expand);
93   setOperationAction(ISD::ROTL     , MVT::i64, Expand);
94   setOperationAction(ISD::ROTR     , MVT::i64, Expand);
95
96   setOperationAction(ISD::SREM     , MVT::i64, Custom);
97   setOperationAction(ISD::UREM     , MVT::i64, Custom);
98   setOperationAction(ISD::SDIV     , MVT::i64, Custom);
99   setOperationAction(ISD::UDIV     , MVT::i64, Custom);
100
101   setOperationAction(ISD::ADDC     , MVT::i64, Expand);
102   setOperationAction(ISD::ADDE     , MVT::i64, Expand);
103   setOperationAction(ISD::SUBC     , MVT::i64, Expand);
104   setOperationAction(ISD::SUBE     , MVT::i64, Expand);
105
106   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
107   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
108
109   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
110   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
111   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
112
113   // We don't support sin/cos/sqrt/pow
114   setOperationAction(ISD::FSIN , MVT::f64, Expand);
115   setOperationAction(ISD::FCOS , MVT::f64, Expand);
116   setOperationAction(ISD::FSIN , MVT::f32, Expand);
117   setOperationAction(ISD::FCOS , MVT::f32, Expand);
118
119   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
120   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
121
122   setOperationAction(ISD::FPOW , MVT::f32, Expand);
123   setOperationAction(ISD::FPOW , MVT::f64, Expand);
124
125   setOperationAction(ISD::SETCC, MVT::f32, Promote);
126
127   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Promote);
128
129   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
130
131   // Not implemented yet.
132   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
133   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
134   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
135
136   // We want to legalize GlobalAddress and ConstantPool and
137   // ExternalSymbols nodes into the appropriate instructions to
138   // materialize the address.
139   setOperationAction(ISD::GlobalAddress,  MVT::i64, Custom);
140   setOperationAction(ISD::ConstantPool,   MVT::i64, Custom);
141   setOperationAction(ISD::ExternalSymbol, MVT::i64, Custom);
142   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
143
144   setOperationAction(ISD::VASTART, MVT::Other, Custom);
145   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
146   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
147   setOperationAction(ISD::VAARG,   MVT::Other, Custom);
148   setOperationAction(ISD::VAARG,   MVT::i32,   Custom);
149
150   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
151   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
152
153   setStackPointerRegisterToSaveRestore(Alpha::R30);
154
155   setJumpBufSize(272);
156   setJumpBufAlignment(16);
157
158   computeRegisterProperties();
159 }
160
161 MVT::SimpleValueType AlphaTargetLowering::getSetCCResultType(EVT VT) const {
162   return MVT::i64;
163 }
164
165 const char *AlphaTargetLowering::getTargetNodeName(unsigned Opcode) const {
166   switch (Opcode) {
167   default: return 0;
168   case AlphaISD::CVTQT_: return "Alpha::CVTQT_";
169   case AlphaISD::CVTQS_: return "Alpha::CVTQS_";
170   case AlphaISD::CVTTQ_: return "Alpha::CVTTQ_";
171   case AlphaISD::GPRelHi: return "Alpha::GPRelHi";
172   case AlphaISD::GPRelLo: return "Alpha::GPRelLo";
173   case AlphaISD::RelLit: return "Alpha::RelLit";
174   case AlphaISD::GlobalRetAddr: return "Alpha::GlobalRetAddr";
175   case AlphaISD::CALL:   return "Alpha::CALL";
176   case AlphaISD::DivCall: return "Alpha::DivCall";
177   case AlphaISD::RET_FLAG: return "Alpha::RET_FLAG";
178   case AlphaISD::COND_BRANCH_I: return "Alpha::COND_BRANCH_I";
179   case AlphaISD::COND_BRANCH_F: return "Alpha::COND_BRANCH_F";
180   }
181 }
182
183 /// getFunctionAlignment - Return the Log2 alignment of this function.
184 unsigned AlphaTargetLowering::getFunctionAlignment(const Function *F) const {
185   return 4;
186 }
187
188 static SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
189   EVT PtrVT = Op.getValueType();
190   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
191   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
192   // FIXME there isn't really any debug info here
193   DebugLoc dl = Op.getDebugLoc();
194
195   SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, JTI,
196                              DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
197   SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, JTI, Hi);
198   return Lo;
199 }
200
201 //http://www.cs.arizona.edu/computer.help/policy/DIGITAL_unix/
202 //AA-PY8AC-TET1_html/callCH3.html#BLOCK21
203
204 //For now, just use variable size stack frame format
205
206 //In a standard call, the first six items are passed in registers $16
207 //- $21 and/or registers $f16 - $f21. (See Section 4.1.2 for details
208 //of argument-to-register correspondence.) The remaining items are
209 //collected in a memory argument list that is a naturally aligned
210 //array of quadwords. In a standard call, this list, if present, must
211 //be passed at 0(SP).
212 //7 ... n         0(SP) ... (n-7)*8(SP)
213
214 // //#define FP    $15
215 // //#define RA    $26
216 // //#define PV    $27
217 // //#define GP    $29
218 // //#define SP    $30
219
220 #include "AlphaGenCallingConv.inc"
221
222 SDValue
223 AlphaTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
224                                CallingConv::ID CallConv, bool isVarArg,
225                                bool &isTailCall,
226                                const SmallVectorImpl<ISD::OutputArg> &Outs,
227                                const SmallVectorImpl<SDValue> &OutVals,
228                                const SmallVectorImpl<ISD::InputArg> &Ins,
229                                DebugLoc dl, SelectionDAG &DAG,
230                                SmallVectorImpl<SDValue> &InVals) const {
231   // Alpha target does not yet support tail call optimization.
232   isTailCall = false;
233
234   // Analyze operands of the call, assigning locations to each operand.
235   SmallVector<CCValAssign, 16> ArgLocs;
236   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
237                  ArgLocs, *DAG.getContext());
238
239   CCInfo.AnalyzeCallOperands(Outs, CC_Alpha);
240
241     // Get a count of how many bytes are to be pushed on the stack.
242   unsigned NumBytes = CCInfo.getNextStackOffset();
243
244   Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
245                                                       getPointerTy(), true));
246
247   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
248   SmallVector<SDValue, 12> MemOpChains;
249   SDValue StackPtr;
250
251   // Walk the register/memloc assignments, inserting copies/loads.
252   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
253     CCValAssign &VA = ArgLocs[i];
254
255     SDValue Arg = OutVals[i];
256
257     // Promote the value if needed.
258     switch (VA.getLocInfo()) {
259       default: assert(0 && "Unknown loc info!");
260       case CCValAssign::Full: break;
261       case CCValAssign::SExt:
262         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
263         break;
264       case CCValAssign::ZExt:
265         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
266         break;
267       case CCValAssign::AExt:
268         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
269         break;
270     }
271
272     // Arguments that can be passed on register must be kept at RegsToPass
273     // vector
274     if (VA.isRegLoc()) {
275       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
276     } else {
277       assert(VA.isMemLoc());
278
279       if (StackPtr.getNode() == 0)
280         StackPtr = DAG.getCopyFromReg(Chain, dl, Alpha::R30, MVT::i64);
281
282       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
283                                    StackPtr,
284                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
285
286       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
287                                          PseudoSourceValue::getStack(), 0,
288                                          false, false, 0));
289     }
290   }
291
292   // Transform all store nodes into one single node because all store nodes are
293   // independent of each other.
294   if (!MemOpChains.empty())
295     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
296                         &MemOpChains[0], MemOpChains.size());
297
298   // Build a sequence of copy-to-reg nodes chained together with token chain and
299   // flag operands which copy the outgoing args into registers.  The InFlag in
300   // necessary since all emited instructions must be stuck together.
301   SDValue InFlag;
302   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
303     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
304                              RegsToPass[i].second, InFlag);
305     InFlag = Chain.getValue(1);
306   }
307
308   // Returns a chain & a flag for retval copy to use.
309   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
310   SmallVector<SDValue, 8> Ops;
311   Ops.push_back(Chain);
312   Ops.push_back(Callee);
313
314   // Add argument registers to the end of the list so that they are
315   // known live into the call.
316   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
317     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
318                                   RegsToPass[i].second.getValueType()));
319
320   if (InFlag.getNode())
321     Ops.push_back(InFlag);
322
323   Chain = DAG.getNode(AlphaISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
324   InFlag = Chain.getValue(1);
325
326   // Create the CALLSEQ_END node.
327   Chain = DAG.getCALLSEQ_END(Chain,
328                              DAG.getConstant(NumBytes, getPointerTy(), true),
329                              DAG.getConstant(0, getPointerTy(), true),
330                              InFlag);
331   InFlag = Chain.getValue(1);
332
333   // Handle result values, copying them out of physregs into vregs that we
334   // return.
335   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
336                          Ins, dl, DAG, InVals);
337 }
338
339 /// LowerCallResult - Lower the result values of a call into the
340 /// appropriate copies out of appropriate physical registers.
341 ///
342 SDValue
343 AlphaTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
344                                      CallingConv::ID CallConv, bool isVarArg,
345                                      const SmallVectorImpl<ISD::InputArg> &Ins,
346                                      DebugLoc dl, SelectionDAG &DAG,
347                                      SmallVectorImpl<SDValue> &InVals) const {
348
349   // Assign locations to each value returned by this call.
350   SmallVector<CCValAssign, 16> RVLocs;
351   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
352                  *DAG.getContext());
353
354   CCInfo.AnalyzeCallResult(Ins, RetCC_Alpha);
355
356   // Copy all of the result registers out of their specified physreg.
357   for (unsigned i = 0; i != RVLocs.size(); ++i) {
358     CCValAssign &VA = RVLocs[i];
359
360     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
361                                VA.getLocVT(), InFlag).getValue(1);
362     SDValue RetValue = Chain.getValue(0);
363     InFlag = Chain.getValue(2);
364
365     // If this is an 8/16/32-bit value, it is really passed promoted to 64
366     // bits. Insert an assert[sz]ext to capture this, then truncate to the
367     // right size.
368     if (VA.getLocInfo() == CCValAssign::SExt)
369       RetValue = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), RetValue,
370                              DAG.getValueType(VA.getValVT()));
371     else if (VA.getLocInfo() == CCValAssign::ZExt)
372       RetValue = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), RetValue,
373                              DAG.getValueType(VA.getValVT()));
374
375     if (VA.getLocInfo() != CCValAssign::Full)
376       RetValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), RetValue);
377
378     InVals.push_back(RetValue);
379   }
380
381   return Chain;
382 }
383
384 SDValue
385 AlphaTargetLowering::LowerFormalArguments(SDValue Chain,
386                                           CallingConv::ID CallConv, bool isVarArg,
387                                           const SmallVectorImpl<ISD::InputArg>
388                                             &Ins,
389                                           DebugLoc dl, SelectionDAG &DAG,
390                                           SmallVectorImpl<SDValue> &InVals)
391                                             const {
392
393   MachineFunction &MF = DAG.getMachineFunction();
394   MachineFrameInfo *MFI = MF.getFrameInfo();
395   AlphaMachineFunctionInfo *FuncInfo = MF.getInfo<AlphaMachineFunctionInfo>();
396
397   unsigned args_int[] = {
398     Alpha::R16, Alpha::R17, Alpha::R18, Alpha::R19, Alpha::R20, Alpha::R21};
399   unsigned args_float[] = {
400     Alpha::F16, Alpha::F17, Alpha::F18, Alpha::F19, Alpha::F20, Alpha::F21};
401
402   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
403     SDValue argt;
404     EVT ObjectVT = Ins[ArgNo].VT;
405     SDValue ArgVal;
406
407     if (ArgNo  < 6) {
408       switch (ObjectVT.getSimpleVT().SimpleTy) {
409       default:
410         assert(false && "Invalid value type!");
411       case MVT::f64:
412         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo],
413                                       &Alpha::F8RCRegClass);
414         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
415         break;
416       case MVT::f32:
417         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo],
418                                       &Alpha::F4RCRegClass);
419         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
420         break;
421       case MVT::i64:
422         args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo],
423                                     &Alpha::GPRCRegClass);
424         ArgVal = DAG.getCopyFromReg(Chain, dl, args_int[ArgNo], MVT::i64);
425         break;
426       }
427     } else { //more args
428       // Create the frame index object for this incoming parameter...
429       int FI = MFI->CreateFixedObject(8, 8 * (ArgNo - 6), true);
430
431       // Create the SelectionDAG nodes corresponding to a load
432       //from this parameter
433       SDValue FIN = DAG.getFrameIndex(FI, MVT::i64);
434       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
435                            false, false, 0);
436     }
437     InVals.push_back(ArgVal);
438   }
439
440   // If the functions takes variable number of arguments, copy all regs to stack
441   if (isVarArg) {
442     FuncInfo->setVarArgsOffset(Ins.size() * 8);
443     std::vector<SDValue> LS;
444     for (int i = 0; i < 6; ++i) {
445       if (TargetRegisterInfo::isPhysicalRegister(args_int[i]))
446         args_int[i] = AddLiveIn(MF, args_int[i], &Alpha::GPRCRegClass);
447       SDValue argt = DAG.getCopyFromReg(Chain, dl, args_int[i], MVT::i64);
448       int FI = MFI->CreateFixedObject(8, -8 * (6 - i), true);
449       if (i == 0) FuncInfo->setVarArgsBase(FI);
450       SDValue SDFI = DAG.getFrameIndex(FI, MVT::i64);
451       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, NULL, 0,
452                                 false, false, 0));
453
454       if (TargetRegisterInfo::isPhysicalRegister(args_float[i]))
455         args_float[i] = AddLiveIn(MF, args_float[i], &Alpha::F8RCRegClass);
456       argt = DAG.getCopyFromReg(Chain, dl, args_float[i], MVT::f64);
457       FI = MFI->CreateFixedObject(8, - 8 * (12 - i), true);
458       SDFI = DAG.getFrameIndex(FI, MVT::i64);
459       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, NULL, 0,
460                                 false, false, 0));
461     }
462
463     //Set up a token factor with all the stack traffic
464     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &LS[0], LS.size());
465   }
466
467   return Chain;
468 }
469
470 SDValue
471 AlphaTargetLowering::LowerReturn(SDValue Chain,
472                                  CallingConv::ID CallConv, bool isVarArg,
473                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
474                                  const SmallVectorImpl<SDValue> &OutVals,
475                                  DebugLoc dl, SelectionDAG &DAG) const {
476
477   SDValue Copy = DAG.getCopyToReg(Chain, dl, Alpha::R26,
478                                   DAG.getNode(AlphaISD::GlobalRetAddr,
479                                               DebugLoc(), MVT::i64),
480                                   SDValue());
481   switch (Outs.size()) {
482   default:
483     llvm_unreachable("Do not know how to return this many arguments!");
484   case 0:
485     break;
486     //return SDValue(); // ret void is legal
487   case 1: {
488     EVT ArgVT = Outs[0].VT;
489     unsigned ArgReg;
490     if (ArgVT.isInteger())
491       ArgReg = Alpha::R0;
492     else {
493       assert(ArgVT.isFloatingPoint());
494       ArgReg = Alpha::F0;
495     }
496     Copy = DAG.getCopyToReg(Copy, dl, ArgReg,
497                             OutVals[0], Copy.getValue(1));
498     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
499       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg);
500     break;
501   }
502   case 2: {
503     EVT ArgVT = Outs[0].VT;
504     unsigned ArgReg1, ArgReg2;
505     if (ArgVT.isInteger()) {
506       ArgReg1 = Alpha::R0;
507       ArgReg2 = Alpha::R1;
508     } else {
509       assert(ArgVT.isFloatingPoint());
510       ArgReg1 = Alpha::F0;
511       ArgReg2 = Alpha::F1;
512     }
513     Copy = DAG.getCopyToReg(Copy, dl, ArgReg1,
514                             OutVals[0], Copy.getValue(1));
515     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(),
516                   DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg1)
517         == DAG.getMachineFunction().getRegInfo().liveout_end())
518       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg1);
519     Copy = DAG.getCopyToReg(Copy, dl, ArgReg2,
520                             OutVals[1], Copy.getValue(1));
521     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(),
522                    DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg2)
523         == DAG.getMachineFunction().getRegInfo().liveout_end())
524       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg2);
525     break;
526   }
527   }
528   return DAG.getNode(AlphaISD::RET_FLAG, dl,
529                      MVT::Other, Copy, Copy.getValue(1));
530 }
531
532 void AlphaTargetLowering::LowerVAARG(SDNode *N, SDValue &Chain,
533                                      SDValue &DataPtr,
534                                      SelectionDAG &DAG) const {
535   Chain = N->getOperand(0);
536   SDValue VAListP = N->getOperand(1);
537   const Value *VAListS = cast<SrcValueSDNode>(N->getOperand(2))->getValue();
538   DebugLoc dl = N->getDebugLoc();
539
540   SDValue Base = DAG.getLoad(MVT::i64, dl, Chain, VAListP,
541                              MachinePointerInfo(VAListS),
542                              false, false, 0);
543   SDValue Tmp = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
544                               DAG.getConstant(8, MVT::i64));
545   SDValue Offset = DAG.getExtLoad(ISD::SEXTLOAD, MVT::i64, dl, Base.getValue(1),
546                                   Tmp, NULL, 0, MVT::i32, false, false, 0);
547   DataPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Base, Offset);
548   if (N->getValueType(0).isFloatingPoint())
549   {
550     //if fp && Offset < 6*8, then subtract 6*8 from DataPtr
551     SDValue FPDataPtr = DAG.getNode(ISD::SUB, dl, MVT::i64, DataPtr,
552                                       DAG.getConstant(8*6, MVT::i64));
553     SDValue CC = DAG.getSetCC(dl, MVT::i64, Offset,
554                                 DAG.getConstant(8*6, MVT::i64), ISD::SETLT);
555     DataPtr = DAG.getNode(ISD::SELECT, dl, MVT::i64, CC, FPDataPtr, DataPtr);
556   }
557
558   SDValue NewOffset = DAG.getNode(ISD::ADD, dl, MVT::i64, Offset,
559                                     DAG.getConstant(8, MVT::i64));
560   Chain = DAG.getTruncStore(Offset.getValue(1), dl, NewOffset, Tmp, NULL, 0,
561                             MVT::i32, false, false, 0);
562 }
563
564 /// LowerOperation - Provide custom lowering hooks for some operations.
565 ///
566 SDValue AlphaTargetLowering::LowerOperation(SDValue Op,
567                                             SelectionDAG &DAG) const {
568   DebugLoc dl = Op.getDebugLoc();
569   switch (Op.getOpcode()) {
570   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
571   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
572
573   case ISD::INTRINSIC_WO_CHAIN: {
574     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
575     switch (IntNo) {
576     default: break;    // Don't custom lower most intrinsics.
577     case Intrinsic::alpha_umulh:
578       return DAG.getNode(ISD::MULHU, dl, MVT::i64,
579                          Op.getOperand(1), Op.getOperand(2));
580     }
581   }
582
583   case ISD::SRL_PARTS: {
584     SDValue ShOpLo = Op.getOperand(0);
585     SDValue ShOpHi = Op.getOperand(1);
586     SDValue ShAmt  = Op.getOperand(2);
587     SDValue bm = DAG.getNode(ISD::SUB, dl, MVT::i64,
588                              DAG.getConstant(64, MVT::i64), ShAmt);
589     SDValue BMCC = DAG.getSetCC(dl, MVT::i64, bm,
590                                 DAG.getConstant(0, MVT::i64), ISD::SETLE);
591     // if 64 - shAmt <= 0
592     SDValue Hi_Neg = DAG.getConstant(0, MVT::i64);
593     SDValue ShAmt_Neg = DAG.getNode(ISD::SUB, dl, MVT::i64,
594                                     DAG.getConstant(0, MVT::i64), bm);
595     SDValue Lo_Neg = DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpHi, ShAmt_Neg);
596     // else
597     SDValue carries = DAG.getNode(ISD::SHL, dl, MVT::i64, ShOpHi, bm);
598     SDValue Hi_Pos =  DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpHi, ShAmt);
599     SDValue Lo_Pos = DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpLo, ShAmt);
600     Lo_Pos = DAG.getNode(ISD::OR, dl, MVT::i64, Lo_Pos, carries);
601     // Merge
602     SDValue Hi = DAG.getNode(ISD::SELECT, dl, MVT::i64, BMCC, Hi_Neg, Hi_Pos);
603     SDValue Lo = DAG.getNode(ISD::SELECT, dl, MVT::i64, BMCC, Lo_Neg, Lo_Pos);
604     SDValue Ops[2] = { Lo, Hi };
605     return DAG.getMergeValues(Ops, 2, dl);
606   }
607     //  case ISD::SRA_PARTS:
608
609     //  case ISD::SHL_PARTS:
610
611
612   case ISD::SINT_TO_FP: {
613     assert(Op.getOperand(0).getValueType() == MVT::i64 &&
614            "Unhandled SINT_TO_FP type in custom expander!");
615     SDValue LD;
616     bool isDouble = Op.getValueType() == MVT::f64;
617     LD = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op.getOperand(0));
618     SDValue FP = DAG.getNode(isDouble?AlphaISD::CVTQT_:AlphaISD::CVTQS_, dl,
619                                isDouble?MVT::f64:MVT::f32, LD);
620     return FP;
621   }
622   case ISD::FP_TO_SINT: {
623     bool isDouble = Op.getOperand(0).getValueType() == MVT::f64;
624     SDValue src = Op.getOperand(0);
625
626     if (!isDouble) //Promote
627       src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, src);
628
629     src = DAG.getNode(AlphaISD::CVTTQ_, dl, MVT::f64, src);
630
631     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, src);
632   }
633   case ISD::ConstantPool: {
634     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
635     const Constant *C = CP->getConstVal();
636     SDValue CPI = DAG.getTargetConstantPool(C, MVT::i64, CP->getAlignment());
637     // FIXME there isn't really any debug info here
638
639     SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, CPI,
640                                DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
641     SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, CPI, Hi);
642     return Lo;
643   }
644   case ISD::GlobalTLSAddress:
645     llvm_unreachable("TLS not implemented for Alpha.");
646   case ISD::GlobalAddress: {
647     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
648     const GlobalValue *GV = GSDN->getGlobal();
649     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i64, 
650                                             GSDN->getOffset());
651     // FIXME there isn't really any debug info here
652
653     //    if (!GV->hasWeakLinkage() && !GV->isDeclaration() 
654     //        && !GV->hasLinkOnceLinkage()) {
655     if (GV->hasLocalLinkage()) {
656       SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, GA,
657                                 DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
658       SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, GA, Hi);
659       return Lo;
660     } else
661       return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA,
662                          DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
663   }
664   case ISD::ExternalSymbol: {
665     return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64,
666                        DAG.getTargetExternalSymbol(cast<ExternalSymbolSDNode>(Op)
667                                                    ->getSymbol(), MVT::i64),
668                        DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
669   }
670
671   case ISD::UREM:
672   case ISD::SREM:
673     //Expand only on constant case
674     if (Op.getOperand(1).getOpcode() == ISD::Constant) {
675       EVT VT = Op.getNode()->getValueType(0);
676       SDValue Tmp1 = Op.getNode()->getOpcode() == ISD::UREM ?
677         BuildUDIV(Op.getNode(), DAG, NULL) :
678         BuildSDIV(Op.getNode(), DAG, NULL);
679       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Op.getOperand(1));
680       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Op.getOperand(0), Tmp1);
681       return Tmp1;
682     }
683     //fall through
684   case ISD::SDIV:
685   case ISD::UDIV:
686     if (Op.getValueType().isInteger()) {
687       if (Op.getOperand(1).getOpcode() == ISD::Constant)
688         return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL)
689           : BuildUDIV(Op.getNode(), DAG, NULL);
690       const char* opstr = 0;
691       switch (Op.getOpcode()) {
692       case ISD::UREM: opstr = "__remqu"; break;
693       case ISD::SREM: opstr = "__remq";  break;
694       case ISD::UDIV: opstr = "__divqu"; break;
695       case ISD::SDIV: opstr = "__divq";  break;
696       }
697       SDValue Tmp1 = Op.getOperand(0),
698         Tmp2 = Op.getOperand(1),
699         Addr = DAG.getExternalSymbol(opstr, MVT::i64);
700       return DAG.getNode(AlphaISD::DivCall, dl, MVT::i64, Addr, Tmp1, Tmp2);
701     }
702     break;
703
704   case ISD::VAARG: {
705     SDValue Chain, DataPtr;
706     LowerVAARG(Op.getNode(), Chain, DataPtr, DAG);
707
708     SDValue Result;
709     if (Op.getValueType() == MVT::i32)
710       Result = DAG.getExtLoad(ISD::SEXTLOAD, MVT::i64, dl, Chain, DataPtr,
711                               NULL, 0, MVT::i32, false, false, 0);
712     else
713       Result = DAG.getLoad(Op.getValueType(), dl, Chain, DataPtr,
714                            MachinePointerInfo(),
715                            false, false, 0);
716     return Result;
717   }
718   case ISD::VACOPY: {
719     SDValue Chain = Op.getOperand(0);
720     SDValue DestP = Op.getOperand(1);
721     SDValue SrcP = Op.getOperand(2);
722     const Value *DestS = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
723     const Value *SrcS = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
724
725     SDValue Val = DAG.getLoad(getPointerTy(), dl, Chain, SrcP,
726                               MachinePointerInfo(SrcS),
727                               false, false, 0);
728     SDValue Result = DAG.getStore(Val.getValue(1), dl, Val, DestP, DestS, 0,
729                                   false, false, 0);
730     SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP,
731                                DAG.getConstant(8, MVT::i64));
732     Val = DAG.getExtLoad(ISD::SEXTLOAD, MVT::i64, dl, Result,
733                          NP, NULL,0, MVT::i32, false, false, 0);
734     SDValue NPD = DAG.getNode(ISD::ADD, dl, MVT::i64, DestP,
735                                 DAG.getConstant(8, MVT::i64));
736     return DAG.getTruncStore(Val.getValue(1), dl, Val, NPD, NULL, 0, MVT::i32,
737                              false, false, 0);
738   }
739   case ISD::VASTART: {
740     MachineFunction &MF = DAG.getMachineFunction();
741     AlphaMachineFunctionInfo *FuncInfo = MF.getInfo<AlphaMachineFunctionInfo>();
742
743     SDValue Chain = Op.getOperand(0);
744     SDValue VAListP = Op.getOperand(1);
745     const Value *VAListS = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
746
747     // vastart stores the address of the VarArgsBase and VarArgsOffset
748     SDValue FR  = DAG.getFrameIndex(FuncInfo->getVarArgsBase(), MVT::i64);
749     SDValue S1  = DAG.getStore(Chain, dl, FR, VAListP, VAListS, 0,
750                                false, false, 0);
751     SDValue SA2 = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
752                                 DAG.getConstant(8, MVT::i64));
753     return DAG.getTruncStore(S1, dl,
754                              DAG.getConstant(FuncInfo->getVarArgsOffset(),
755                                              MVT::i64),
756                              SA2, NULL, 0, MVT::i32, false, false, 0);
757   }
758   case ISD::RETURNADDR:
759     return DAG.getNode(AlphaISD::GlobalRetAddr, DebugLoc(), MVT::i64);
760       //FIXME: implement
761   case ISD::FRAMEADDR:          break;
762   }
763
764   return SDValue();
765 }
766
767 void AlphaTargetLowering::ReplaceNodeResults(SDNode *N,
768                                              SmallVectorImpl<SDValue>&Results,
769                                              SelectionDAG &DAG) const {
770   DebugLoc dl = N->getDebugLoc();
771   assert(N->getValueType(0) == MVT::i32 &&
772          N->getOpcode() == ISD::VAARG &&
773          "Unknown node to custom promote!");
774
775   SDValue Chain, DataPtr;
776   LowerVAARG(N, Chain, DataPtr, DAG);
777   SDValue Res = DAG.getLoad(N->getValueType(0), dl, Chain, DataPtr, 
778                             MachinePointerInfo(),
779                             false, false, 0);
780   Results.push_back(Res);
781   Results.push_back(SDValue(Res.getNode(), 1));
782 }
783
784
785 //Inline Asm
786
787 /// getConstraintType - Given a constraint letter, return the type of
788 /// constraint it is for this target.
789 AlphaTargetLowering::ConstraintType
790 AlphaTargetLowering::getConstraintType(const std::string &Constraint) const {
791   if (Constraint.size() == 1) {
792     switch (Constraint[0]) {
793     default: break;
794     case 'f':
795     case 'r':
796       return C_RegisterClass;
797     }
798   }
799   return TargetLowering::getConstraintType(Constraint);
800 }
801
802 std::vector<unsigned> AlphaTargetLowering::
803 getRegClassForInlineAsmConstraint(const std::string &Constraint,
804                                   EVT VT) const {
805   if (Constraint.size() == 1) {
806     switch (Constraint[0]) {
807     default: break;  // Unknown constriant letter
808     case 'f':
809       return make_vector<unsigned>(Alpha::F0 , Alpha::F1 , Alpha::F2 ,
810                                    Alpha::F3 , Alpha::F4 , Alpha::F5 ,
811                                    Alpha::F6 , Alpha::F7 , Alpha::F8 ,
812                                    Alpha::F9 , Alpha::F10, Alpha::F11,
813                                    Alpha::F12, Alpha::F13, Alpha::F14,
814                                    Alpha::F15, Alpha::F16, Alpha::F17,
815                                    Alpha::F18, Alpha::F19, Alpha::F20,
816                                    Alpha::F21, Alpha::F22, Alpha::F23,
817                                    Alpha::F24, Alpha::F25, Alpha::F26,
818                                    Alpha::F27, Alpha::F28, Alpha::F29,
819                                    Alpha::F30, Alpha::F31, 0);
820     case 'r':
821       return make_vector<unsigned>(Alpha::R0 , Alpha::R1 , Alpha::R2 ,
822                                    Alpha::R3 , Alpha::R4 , Alpha::R5 ,
823                                    Alpha::R6 , Alpha::R7 , Alpha::R8 ,
824                                    Alpha::R9 , Alpha::R10, Alpha::R11,
825                                    Alpha::R12, Alpha::R13, Alpha::R14,
826                                    Alpha::R15, Alpha::R16, Alpha::R17,
827                                    Alpha::R18, Alpha::R19, Alpha::R20,
828                                    Alpha::R21, Alpha::R22, Alpha::R23,
829                                    Alpha::R24, Alpha::R25, Alpha::R26,
830                                    Alpha::R27, Alpha::R28, Alpha::R29,
831                                    Alpha::R30, Alpha::R31, 0);
832     }
833   }
834
835   return std::vector<unsigned>();
836 }
837 //===----------------------------------------------------------------------===//
838 //  Other Lowering Code
839 //===----------------------------------------------------------------------===//
840
841 MachineBasicBlock *
842 AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
843                                                  MachineBasicBlock *BB) const {
844   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
845   assert((MI->getOpcode() == Alpha::CAS32 ||
846           MI->getOpcode() == Alpha::CAS64 ||
847           MI->getOpcode() == Alpha::LAS32 ||
848           MI->getOpcode() == Alpha::LAS64 ||
849           MI->getOpcode() == Alpha::SWAP32 ||
850           MI->getOpcode() == Alpha::SWAP64) &&
851          "Unexpected instr type to insert");
852
853   bool is32 = MI->getOpcode() == Alpha::CAS32 ||
854     MI->getOpcode() == Alpha::LAS32 ||
855     MI->getOpcode() == Alpha::SWAP32;
856
857   //Load locked store conditional for atomic ops take on the same form
858   //start:
859   //ll
860   //do stuff (maybe branch to exit)
861   //sc
862   //test sc and maybe branck to start
863   //exit:
864   const BasicBlock *LLVM_BB = BB->getBasicBlock();
865   DebugLoc dl = MI->getDebugLoc();
866   MachineFunction::iterator It = BB;
867   ++It;
868
869   MachineBasicBlock *thisMBB = BB;
870   MachineFunction *F = BB->getParent();
871   MachineBasicBlock *llscMBB = F->CreateMachineBasicBlock(LLVM_BB);
872   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
873
874   sinkMBB->splice(sinkMBB->begin(), thisMBB,
875                   llvm::next(MachineBasicBlock::iterator(MI)),
876                   thisMBB->end());
877   sinkMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
878
879   F->insert(It, llscMBB);
880   F->insert(It, sinkMBB);
881
882   BuildMI(thisMBB, dl, TII->get(Alpha::BR)).addMBB(llscMBB);
883
884   unsigned reg_res = MI->getOperand(0).getReg(),
885     reg_ptr = MI->getOperand(1).getReg(),
886     reg_v2 = MI->getOperand(2).getReg(),
887     reg_store = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
888
889   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L),
890           reg_res).addImm(0).addReg(reg_ptr);
891   switch (MI->getOpcode()) {
892   case Alpha::CAS32:
893   case Alpha::CAS64: {
894     unsigned reg_cmp
895       = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
896     BuildMI(llscMBB, dl, TII->get(Alpha::CMPEQ), reg_cmp)
897       .addReg(reg_v2).addReg(reg_res);
898     BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
899       .addImm(0).addReg(reg_cmp).addMBB(sinkMBB);
900     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
901       .addReg(Alpha::R31).addReg(MI->getOperand(3).getReg());
902     break;
903   }
904   case Alpha::LAS32:
905   case Alpha::LAS64: {
906     BuildMI(llscMBB, dl,TII->get(is32 ? Alpha::ADDLr : Alpha::ADDQr), reg_store)
907       .addReg(reg_res).addReg(reg_v2);
908     break;
909   }
910   case Alpha::SWAP32:
911   case Alpha::SWAP64: {
912     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
913       .addReg(reg_v2).addReg(reg_v2);
914     break;
915   }
916   }
917   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::STL_C : Alpha::STQ_C), reg_store)
918     .addReg(reg_store).addImm(0).addReg(reg_ptr);
919   BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
920     .addImm(0).addReg(reg_store).addMBB(llscMBB);
921   BuildMI(llscMBB, dl, TII->get(Alpha::BR)).addMBB(sinkMBB);
922
923   thisMBB->addSuccessor(llscMBB);
924   llscMBB->addSuccessor(llscMBB);
925   llscMBB->addSuccessor(sinkMBB);
926   MI->eraseFromParent();   // The pseudo instruction is gone now.
927
928   return sinkMBB;
929 }
930
931 bool
932 AlphaTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
933   // The Alpha target isn't yet aware of offsets.
934   return false;
935 }
936
937 bool AlphaTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
938   if (VT != MVT::f32 && VT != MVT::f64)
939     return false;
940   // +0.0   F31
941   // +0.0f  F31
942   // -0.0  -F31
943   // -0.0f -F31
944   return Imm.isZero() || Imm.isNegZero();
945 }