Use elf Object File directly
[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
111   // We don't support sin/cos/sqrt/pow
112   setOperationAction(ISD::FSIN , MVT::f64, Expand);
113   setOperationAction(ISD::FCOS , MVT::f64, Expand);
114   setOperationAction(ISD::FSIN , MVT::f32, Expand);
115   setOperationAction(ISD::FCOS , MVT::f32, Expand);
116
117   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
118   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
119
120   setOperationAction(ISD::FPOW , MVT::f32, Expand);
121   setOperationAction(ISD::FPOW , MVT::f64, Expand);
122
123   setOperationAction(ISD::SETCC, MVT::f32, Promote);
124
125   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Promote);
126
127   // We don't have line number support yet.
128   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
129   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
130   setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
131   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
132
133   // Not implemented yet.
134   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 
135   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
136   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
137
138   // We want to legalize GlobalAddress and ConstantPool and
139   // ExternalSymbols nodes into the appropriate instructions to
140   // materialize the address.
141   setOperationAction(ISD::GlobalAddress,  MVT::i64, Custom);
142   setOperationAction(ISD::ConstantPool,   MVT::i64, Custom);
143   setOperationAction(ISD::ExternalSymbol, MVT::i64, Custom);
144   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
145
146   setOperationAction(ISD::VASTART, MVT::Other, Custom);
147   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
148   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
149   setOperationAction(ISD::VAARG,   MVT::Other, Custom);
150   setOperationAction(ISD::VAARG,   MVT::i32,   Custom);
151
152   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
153   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
154
155   setStackPointerRegisterToSaveRestore(Alpha::R30);
156
157   addLegalFPImmediate(APFloat(+0.0)); //F31
158   addLegalFPImmediate(APFloat(+0.0f)); //F31
159   addLegalFPImmediate(APFloat(-0.0)); //-F31
160   addLegalFPImmediate(APFloat(-0.0f)); //-F31
161
162   setJumpBufSize(272);
163   setJumpBufAlignment(16);
164
165   computeRegisterProperties();
166 }
167
168 MVT AlphaTargetLowering::getSetCCResultType(MVT VT) const {
169   return MVT::i64;
170 }
171
172 const char *AlphaTargetLowering::getTargetNodeName(unsigned Opcode) const {
173   switch (Opcode) {
174   default: return 0;
175   case AlphaISD::CVTQT_: return "Alpha::CVTQT_";
176   case AlphaISD::CVTQS_: return "Alpha::CVTQS_";
177   case AlphaISD::CVTTQ_: return "Alpha::CVTTQ_";
178   case AlphaISD::GPRelHi: return "Alpha::GPRelHi";
179   case AlphaISD::GPRelLo: return "Alpha::GPRelLo";
180   case AlphaISD::RelLit: return "Alpha::RelLit";
181   case AlphaISD::GlobalRetAddr: return "Alpha::GlobalRetAddr";
182   case AlphaISD::CALL:   return "Alpha::CALL";
183   case AlphaISD::DivCall: return "Alpha::DivCall";
184   case AlphaISD::RET_FLAG: return "Alpha::RET_FLAG";
185   case AlphaISD::COND_BRANCH_I: return "Alpha::COND_BRANCH_I";
186   case AlphaISD::COND_BRANCH_F: return "Alpha::COND_BRANCH_F";
187   }
188 }
189
190 /// getFunctionAlignment - Return the Log2 alignment of this function.
191 unsigned AlphaTargetLowering::getFunctionAlignment(const Function *F) const {
192   return 4;
193 }
194
195 static SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
196   MVT PtrVT = Op.getValueType();
197   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
198   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
199   SDValue Zero = DAG.getConstant(0, PtrVT);
200   // FIXME there isn't really any debug info here
201   DebugLoc dl = Op.getDebugLoc();
202   
203   SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, JTI,
204                              DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
205   SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, JTI, Hi);
206   return Lo;
207 }
208
209 //http://www.cs.arizona.edu/computer.help/policy/DIGITAL_unix/
210 //AA-PY8AC-TET1_html/callCH3.html#BLOCK21
211
212 //For now, just use variable size stack frame format
213
214 //In a standard call, the first six items are passed in registers $16
215 //- $21 and/or registers $f16 - $f21. (See Section 4.1.2 for details
216 //of argument-to-register correspondence.) The remaining items are
217 //collected in a memory argument list that is a naturally aligned
218 //array of quadwords. In a standard call, this list, if present, must
219 //be passed at 0(SP).
220 //7 ... n         0(SP) ... (n-7)*8(SP)
221
222 // //#define FP    $15
223 // //#define RA    $26
224 // //#define PV    $27
225 // //#define GP    $29
226 // //#define SP    $30
227
228 #include "AlphaGenCallingConv.inc"
229
230 SDValue
231 AlphaTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
232                                unsigned CallConv, bool isVarArg,
233                                bool isTailCall,
234                                const SmallVectorImpl<ISD::OutputArg> &Outs,
235                                const SmallVectorImpl<ISD::InputArg> &Ins,
236                                DebugLoc dl, SelectionDAG &DAG,
237                                SmallVectorImpl<SDValue> &InVals) {
238
239   // Analyze operands of the call, assigning locations to each operand.
240   SmallVector<CCValAssign, 16> ArgLocs;
241   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
242                  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 = Outs[i].Val;
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                                          PseudoSourceValue::getStack(), 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 emited 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::Flag);
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                                      unsigned CallConv, bool isVarArg,
349                                      const SmallVectorImpl<ISD::InputArg> &Ins,
350                                      DebugLoc dl, SelectionDAG &DAG,
351                                      SmallVectorImpl<SDValue> &InVals) {
352
353   // Assign locations to each value returned by this call.
354   SmallVector<CCValAssign, 16> RVLocs;
355   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
356                  *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                                           unsigned CallConv, bool isVarArg,
391                                           const SmallVectorImpl<ISD::InputArg>
392                                             &Ins,
393                                           DebugLoc dl, SelectionDAG &DAG,
394                                           SmallVectorImpl<SDValue> &InVals) {
395
396   MachineFunction &MF = DAG.getMachineFunction();
397   MachineFrameInfo *MFI = MF.getFrameInfo();
398
399   unsigned args_int[] = {
400     Alpha::R16, Alpha::R17, Alpha::R18, Alpha::R19, Alpha::R20, Alpha::R21};
401   unsigned args_float[] = {
402     Alpha::F16, Alpha::F17, Alpha::F18, Alpha::F19, Alpha::F20, Alpha::F21};
403   
404   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
405     SDValue argt;
406     MVT ObjectVT = Ins[ArgNo].VT;
407     SDValue ArgVal;
408
409     if (ArgNo  < 6) {
410       switch (ObjectVT.getSimpleVT()) {
411       default:
412         assert(false && "Invalid value type!");
413       case MVT::f64:
414         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], 
415                                       &Alpha::F8RCRegClass);
416         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
417         break;
418       case MVT::f32:
419         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], 
420                                       &Alpha::F4RCRegClass);
421         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
422         break;
423       case MVT::i64:
424         args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo], 
425                                     &Alpha::GPRCRegClass);
426         ArgVal = DAG.getCopyFromReg(Chain, dl, args_int[ArgNo], MVT::i64);
427         break;
428       }
429     } else { //more args
430       // Create the frame index object for this incoming parameter...
431       int FI = MFI->CreateFixedObject(8, 8 * (ArgNo - 6));
432
433       // Create the SelectionDAG nodes corresponding to a load
434       //from this parameter
435       SDValue FIN = DAG.getFrameIndex(FI, MVT::i64);
436       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, NULL, 0);
437     }
438     InVals.push_back(ArgVal);
439   }
440
441   // If the functions takes variable number of arguments, copy all regs to stack
442   if (isVarArg) {
443     VarArgsOffset = Ins.size() * 8;
444     std::vector<SDValue> LS;
445     for (int i = 0; i < 6; ++i) {
446       if (TargetRegisterInfo::isPhysicalRegister(args_int[i]))
447         args_int[i] = AddLiveIn(MF, args_int[i], &Alpha::GPRCRegClass);
448       SDValue argt = DAG.getCopyFromReg(Chain, dl, args_int[i], MVT::i64);
449       int FI = MFI->CreateFixedObject(8, -8 * (6 - i));
450       if (i == 0) VarArgsBase = FI;
451       SDValue SDFI = DAG.getFrameIndex(FI, MVT::i64);
452       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, NULL, 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));
458       SDFI = DAG.getFrameIndex(FI, MVT::i64);
459       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, NULL, 0));
460     }
461
462     //Set up a token factor with all the stack traffic
463     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &LS[0], LS.size());
464   }
465
466   return Chain;
467 }
468
469 SDValue
470 AlphaTargetLowering::LowerReturn(SDValue Chain,
471                                  unsigned CallConv, bool isVarArg,
472                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
473                                  DebugLoc dl, SelectionDAG &DAG) {
474
475   SDValue Copy = DAG.getCopyToReg(Chain, dl, Alpha::R26,
476                                   DAG.getNode(AlphaISD::GlobalRetAddr,
477                                               DebugLoc::getUnknownLoc(),
478                                               MVT::i64),
479                                   SDValue());
480   switch (Outs.size()) {
481   default:
482     llvm_unreachable("Do not know how to return this many arguments!");
483   case 0:
484     break;
485     //return SDValue(); // ret void is legal
486   case 1: {
487     MVT ArgVT = Outs[0].Val.getValueType();
488     unsigned ArgReg;
489     if (ArgVT.isInteger())
490       ArgReg = Alpha::R0;
491     else {
492       assert(ArgVT.isFloatingPoint());
493       ArgReg = Alpha::F0;
494     }
495     Copy = DAG.getCopyToReg(Copy, dl, ArgReg, 
496                             Outs[0].Val, Copy.getValue(1));
497     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
498       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg);
499     break;
500   }
501   case 2: {
502     MVT ArgVT = Outs[0].Val.getValueType();
503     unsigned ArgReg1, ArgReg2;
504     if (ArgVT.isInteger()) {
505       ArgReg1 = Alpha::R0;
506       ArgReg2 = Alpha::R1;
507     } else {
508       assert(ArgVT.isFloatingPoint());
509       ArgReg1 = Alpha::F0;
510       ArgReg2 = Alpha::F1;
511     }
512     Copy = DAG.getCopyToReg(Copy, dl, ArgReg1, 
513                             Outs[0].Val, Copy.getValue(1));
514     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), 
515                   DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg1)
516         == DAG.getMachineFunction().getRegInfo().liveout_end())
517       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg1);
518     Copy = DAG.getCopyToReg(Copy, dl, ArgReg2, 
519                             Outs[1].Val, Copy.getValue(1));
520     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), 
521                    DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg2)
522         == DAG.getMachineFunction().getRegInfo().liveout_end())
523       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg2);
524     break;
525   }
526   }
527   return DAG.getNode(AlphaISD::RET_FLAG, dl, 
528                      MVT::Other, Copy, Copy.getValue(1));
529 }
530
531 void AlphaTargetLowering::LowerVAARG(SDNode *N, SDValue &Chain,
532                                      SDValue &DataPtr, SelectionDAG &DAG) {
533   Chain = N->getOperand(0);
534   SDValue VAListP = N->getOperand(1);
535   const Value *VAListS = cast<SrcValueSDNode>(N->getOperand(2))->getValue();
536   DebugLoc dl = N->getDebugLoc();
537
538   SDValue Base = DAG.getLoad(MVT::i64, dl, Chain, VAListP, VAListS, 0);
539   SDValue Tmp = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
540                               DAG.getConstant(8, MVT::i64));
541   SDValue Offset = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Base.getValue(1),
542                                     Tmp, NULL, 0, MVT::i32);
543   DataPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Base, Offset);
544   if (N->getValueType(0).isFloatingPoint())
545   {
546     //if fp && Offset < 6*8, then subtract 6*8 from DataPtr
547     SDValue FPDataPtr = DAG.getNode(ISD::SUB, dl, MVT::i64, DataPtr,
548                                       DAG.getConstant(8*6, MVT::i64));
549     SDValue CC = DAG.getSetCC(dl, MVT::i64, Offset,
550                                 DAG.getConstant(8*6, MVT::i64), ISD::SETLT);
551     DataPtr = DAG.getNode(ISD::SELECT, dl, MVT::i64, CC, FPDataPtr, DataPtr);
552   }
553
554   SDValue NewOffset = DAG.getNode(ISD::ADD, dl, MVT::i64, Offset,
555                                     DAG.getConstant(8, MVT::i64));
556   Chain = DAG.getTruncStore(Offset.getValue(1), dl, NewOffset, Tmp, NULL, 0,
557                             MVT::i32);
558 }
559
560 /// LowerOperation - Provide custom lowering hooks for some operations.
561 ///
562 SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
563   DebugLoc dl = Op.getDebugLoc();
564   switch (Op.getOpcode()) {
565   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
566   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
567
568   case ISD::INTRINSIC_WO_CHAIN: {
569     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
570     switch (IntNo) {
571     default: break;    // Don't custom lower most intrinsics.
572     case Intrinsic::alpha_umulh:
573       return DAG.getNode(ISD::MULHU, dl, MVT::i64, 
574                          Op.getOperand(1), Op.getOperand(2));
575     }
576   }
577
578   case ISD::SINT_TO_FP: {
579     assert(Op.getOperand(0).getValueType() == MVT::i64 &&
580            "Unhandled SINT_TO_FP type in custom expander!");
581     SDValue LD;
582     bool isDouble = Op.getValueType() == MVT::f64;
583     LD = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op.getOperand(0));
584     SDValue FP = DAG.getNode(isDouble?AlphaISD::CVTQT_:AlphaISD::CVTQS_, dl,
585                                isDouble?MVT::f64:MVT::f32, LD);
586     return FP;
587   }
588   case ISD::FP_TO_SINT: {
589     bool isDouble = Op.getOperand(0).getValueType() == MVT::f64;
590     SDValue src = Op.getOperand(0);
591
592     if (!isDouble) //Promote
593       src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, src);
594     
595     src = DAG.getNode(AlphaISD::CVTTQ_, dl, MVT::f64, src);
596
597     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, src);
598   }
599   case ISD::ConstantPool: {
600     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
601     Constant *C = CP->getConstVal();
602     SDValue CPI = DAG.getTargetConstantPool(C, MVT::i64, CP->getAlignment());
603     // FIXME there isn't really any debug info here
604     
605     SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, CPI,
606                                DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
607     SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, CPI, Hi);
608     return Lo;
609   }
610   case ISD::GlobalTLSAddress:
611     llvm_unreachable("TLS not implemented for Alpha.");
612   case ISD::GlobalAddress: {
613     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
614     GlobalValue *GV = GSDN->getGlobal();
615     SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i64, GSDN->getOffset());
616     // FIXME there isn't really any debug info here
617
618     //    if (!GV->hasWeakLinkage() && !GV->isDeclaration() && !GV->hasLinkOnceLinkage()) {
619     if (GV->hasLocalLinkage()) {
620       SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, GA,
621                                 DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
622       SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, GA, Hi);
623       return Lo;
624     } else
625       return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA, 
626                          DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
627   }
628   case ISD::ExternalSymbol: {
629     return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, 
630                        DAG.getTargetExternalSymbol(cast<ExternalSymbolSDNode>(Op)
631                                                    ->getSymbol(), MVT::i64),
632                        DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
633   }
634
635   case ISD::UREM:
636   case ISD::SREM:
637     //Expand only on constant case
638     if (Op.getOperand(1).getOpcode() == ISD::Constant) {
639       MVT VT = Op.getNode()->getValueType(0);
640       SDValue Tmp1 = Op.getNode()->getOpcode() == ISD::UREM ?
641         BuildUDIV(Op.getNode(), DAG, NULL) :
642         BuildSDIV(Op.getNode(), DAG, NULL);
643       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Op.getOperand(1));
644       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Op.getOperand(0), Tmp1);
645       return Tmp1;
646     }
647     //fall through
648   case ISD::SDIV:
649   case ISD::UDIV:
650     if (Op.getValueType().isInteger()) {
651       if (Op.getOperand(1).getOpcode() == ISD::Constant)
652         return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL) 
653           : BuildUDIV(Op.getNode(), DAG, NULL);
654       const char* opstr = 0;
655       switch (Op.getOpcode()) {
656       case ISD::UREM: opstr = "__remqu"; break;
657       case ISD::SREM: opstr = "__remq";  break;
658       case ISD::UDIV: opstr = "__divqu"; break;
659       case ISD::SDIV: opstr = "__divq";  break;
660       }
661       SDValue Tmp1 = Op.getOperand(0),
662         Tmp2 = Op.getOperand(1),
663         Addr = DAG.getExternalSymbol(opstr, MVT::i64);
664       return DAG.getNode(AlphaISD::DivCall, dl, MVT::i64, Addr, Tmp1, Tmp2);
665     }
666     break;
667
668   case ISD::VAARG: {
669     SDValue Chain, DataPtr;
670     LowerVAARG(Op.getNode(), Chain, DataPtr, DAG);
671
672     SDValue Result;
673     if (Op.getValueType() == MVT::i32)
674       Result = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Chain, DataPtr,
675                               NULL, 0, MVT::i32);
676     else
677       Result = DAG.getLoad(Op.getValueType(), dl, Chain, DataPtr, NULL, 0);
678     return Result;
679   }
680   case ISD::VACOPY: {
681     SDValue Chain = Op.getOperand(0);
682     SDValue DestP = Op.getOperand(1);
683     SDValue SrcP = Op.getOperand(2);
684     const Value *DestS = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
685     const Value *SrcS = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
686     
687     SDValue Val = DAG.getLoad(getPointerTy(), dl, Chain, SrcP, SrcS, 0);
688     SDValue Result = DAG.getStore(Val.getValue(1), dl, Val, DestP, DestS, 0);
689     SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP, 
690                                DAG.getConstant(8, MVT::i64));
691     Val = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Result, 
692                          NP, NULL,0, MVT::i32);
693     SDValue NPD = DAG.getNode(ISD::ADD, dl, MVT::i64, DestP,
694                                 DAG.getConstant(8, MVT::i64));
695     return DAG.getTruncStore(Val.getValue(1), dl, Val, NPD, NULL, 0, MVT::i32);
696   }
697   case ISD::VASTART: {
698     SDValue Chain = Op.getOperand(0);
699     SDValue VAListP = Op.getOperand(1);
700     const Value *VAListS = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
701     
702     // vastart stores the address of the VarArgsBase and VarArgsOffset
703     SDValue FR  = DAG.getFrameIndex(VarArgsBase, MVT::i64);
704     SDValue S1  = DAG.getStore(Chain, dl, FR, VAListP, VAListS, 0);
705     SDValue SA2 = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
706                                 DAG.getConstant(8, MVT::i64));
707     return DAG.getTruncStore(S1, dl, DAG.getConstant(VarArgsOffset, MVT::i64),
708                              SA2, NULL, 0, MVT::i32);
709   }
710   case ISD::RETURNADDR:        
711     return DAG.getNode(AlphaISD::GlobalRetAddr, DebugLoc::getUnknownLoc(),
712                        MVT::i64);
713       //FIXME: implement
714   case ISD::FRAMEADDR:          break;
715   }
716   
717   return SDValue();
718 }
719
720 void AlphaTargetLowering::ReplaceNodeResults(SDNode *N,
721                                              SmallVectorImpl<SDValue>&Results,
722                                              SelectionDAG &DAG) {
723   DebugLoc dl = N->getDebugLoc();
724   assert(N->getValueType(0) == MVT::i32 &&
725          N->getOpcode() == ISD::VAARG &&
726          "Unknown node to custom promote!");
727
728   SDValue Chain, DataPtr;
729   LowerVAARG(N, Chain, DataPtr, DAG);
730   SDValue Res = DAG.getLoad(N->getValueType(0), dl, Chain, DataPtr, NULL, 0);
731   Results.push_back(Res);
732   Results.push_back(SDValue(Res.getNode(), 1));
733 }
734
735
736 //Inline Asm
737
738 /// getConstraintType - Given a constraint letter, return the type of
739 /// constraint it is for this target.
740 AlphaTargetLowering::ConstraintType 
741 AlphaTargetLowering::getConstraintType(const std::string &Constraint) const {
742   if (Constraint.size() == 1) {
743     switch (Constraint[0]) {
744     default: break;
745     case 'f':
746     case 'r':
747       return C_RegisterClass;
748     }
749   }
750   return TargetLowering::getConstraintType(Constraint);
751 }
752
753 std::vector<unsigned> AlphaTargetLowering::
754 getRegClassForInlineAsmConstraint(const std::string &Constraint,
755                                   MVT VT) const {
756   if (Constraint.size() == 1) {
757     switch (Constraint[0]) {
758     default: break;  // Unknown constriant letter
759     case 'f': 
760       return make_vector<unsigned>(Alpha::F0 , Alpha::F1 , Alpha::F2 ,
761                                    Alpha::F3 , Alpha::F4 , Alpha::F5 ,
762                                    Alpha::F6 , Alpha::F7 , Alpha::F8 , 
763                                    Alpha::F9 , Alpha::F10, Alpha::F11, 
764                                    Alpha::F12, Alpha::F13, Alpha::F14, 
765                                    Alpha::F15, Alpha::F16, Alpha::F17, 
766                                    Alpha::F18, Alpha::F19, Alpha::F20, 
767                                    Alpha::F21, Alpha::F22, Alpha::F23, 
768                                    Alpha::F24, Alpha::F25, Alpha::F26, 
769                                    Alpha::F27, Alpha::F28, Alpha::F29, 
770                                    Alpha::F30, Alpha::F31, 0);
771     case 'r': 
772       return make_vector<unsigned>(Alpha::R0 , Alpha::R1 , Alpha::R2 , 
773                                    Alpha::R3 , Alpha::R4 , Alpha::R5 , 
774                                    Alpha::R6 , Alpha::R7 , Alpha::R8 , 
775                                    Alpha::R9 , Alpha::R10, Alpha::R11, 
776                                    Alpha::R12, Alpha::R13, Alpha::R14, 
777                                    Alpha::R15, Alpha::R16, Alpha::R17, 
778                                    Alpha::R18, Alpha::R19, Alpha::R20, 
779                                    Alpha::R21, Alpha::R22, Alpha::R23, 
780                                    Alpha::R24, Alpha::R25, Alpha::R26, 
781                                    Alpha::R27, Alpha::R28, Alpha::R29, 
782                                    Alpha::R30, Alpha::R31, 0);
783     }
784   }
785   
786   return std::vector<unsigned>();
787 }
788 //===----------------------------------------------------------------------===//
789 //  Other Lowering Code
790 //===----------------------------------------------------------------------===//
791
792 MachineBasicBlock *
793 AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
794                                                  MachineBasicBlock *BB) const {
795   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
796   assert((MI->getOpcode() == Alpha::CAS32 ||
797           MI->getOpcode() == Alpha::CAS64 ||
798           MI->getOpcode() == Alpha::LAS32 ||
799           MI->getOpcode() == Alpha::LAS64 ||
800           MI->getOpcode() == Alpha::SWAP32 ||
801           MI->getOpcode() == Alpha::SWAP64) &&
802          "Unexpected instr type to insert");
803
804   bool is32 = MI->getOpcode() == Alpha::CAS32 || 
805     MI->getOpcode() == Alpha::LAS32 ||
806     MI->getOpcode() == Alpha::SWAP32;
807   
808   //Load locked store conditional for atomic ops take on the same form
809   //start:
810   //ll
811   //do stuff (maybe branch to exit)
812   //sc
813   //test sc and maybe branck to start
814   //exit:
815   const BasicBlock *LLVM_BB = BB->getBasicBlock();
816   DebugLoc dl = MI->getDebugLoc();
817   MachineFunction::iterator It = BB;
818   ++It;
819   
820   MachineBasicBlock *thisMBB = BB;
821   MachineFunction *F = BB->getParent();
822   MachineBasicBlock *llscMBB = F->CreateMachineBasicBlock(LLVM_BB);
823   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
824
825   sinkMBB->transferSuccessors(thisMBB);
826
827   F->insert(It, llscMBB);
828   F->insert(It, sinkMBB);
829
830   BuildMI(thisMBB, dl, TII->get(Alpha::BR)).addMBB(llscMBB);
831   
832   unsigned reg_res = MI->getOperand(0).getReg(),
833     reg_ptr = MI->getOperand(1).getReg(),
834     reg_v2 = MI->getOperand(2).getReg(),
835     reg_store = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
836
837   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L), 
838           reg_res).addImm(0).addReg(reg_ptr);
839   switch (MI->getOpcode()) {
840   case Alpha::CAS32:
841   case Alpha::CAS64: {
842     unsigned reg_cmp 
843       = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
844     BuildMI(llscMBB, dl, TII->get(Alpha::CMPEQ), reg_cmp)
845       .addReg(reg_v2).addReg(reg_res);
846     BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
847       .addImm(0).addReg(reg_cmp).addMBB(sinkMBB);
848     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
849       .addReg(Alpha::R31).addReg(MI->getOperand(3).getReg());
850     break;
851   }
852   case Alpha::LAS32:
853   case Alpha::LAS64: {
854     BuildMI(llscMBB, dl,TII->get(is32 ? Alpha::ADDLr : Alpha::ADDQr), reg_store)
855       .addReg(reg_res).addReg(reg_v2);
856     break;
857   }
858   case Alpha::SWAP32:
859   case Alpha::SWAP64: {
860     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
861       .addReg(reg_v2).addReg(reg_v2);
862     break;
863   }
864   }
865   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::STL_C : Alpha::STQ_C), reg_store)
866     .addReg(reg_store).addImm(0).addReg(reg_ptr);
867   BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
868     .addImm(0).addReg(reg_store).addMBB(llscMBB);
869   BuildMI(llscMBB, dl, TII->get(Alpha::BR)).addMBB(sinkMBB);
870
871   thisMBB->addSuccessor(llscMBB);
872   llscMBB->addSuccessor(llscMBB);
873   llscMBB->addSuccessor(sinkMBB);
874   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
875
876   return sinkMBB;
877 }
878
879 bool
880 AlphaTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
881   // The Alpha target isn't yet aware of offsets.
882   return false;
883 }