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