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