assorted fixes:
[oota-llvm.git] / lib / Target / IA64 / IA64ISelPattern.cpp
1 //===-- IA64ISelPattern.cpp - A pattern matching inst selector for IA64 ---===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Duraid Madina and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for IA64.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "IA64.h"
15 #include "IA64InstrBuilder.h"
16 #include "IA64RegisterInfo.h"
17 #include "IA64MachineFunctionInfo.h"
18 #include "llvm/Constants.h"                   // FIXME: REMOVE
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineConstantPool.h" // FIXME: REMOVE
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 #include <set>
31 #include <algorithm>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 //  IA64TargetLowering - IA64 Implementation of the TargetLowering interface
36 namespace {
37   class IA64TargetLowering : public TargetLowering {
38     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
39     
40     //int ReturnAddrIndex;              // FrameIndex for return slot.
41     unsigned GP, SP, RP; // FIXME - clean this mess up
42   public:
43
44    unsigned VirtGPR; // this is public so it can be accessed in the selector
45    // for ISD::RET down below. add an accessor instead? FIXME
46
47    IA64TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
48       
49       // register class for general registers
50       addRegisterClass(MVT::i64, IA64::GRRegisterClass);
51
52       // register class for FP registers
53       addRegisterClass(MVT::f64, IA64::FPRegisterClass);
54       
55       // register class for predicate registers 
56       addRegisterClass(MVT::i1, IA64::PRRegisterClass);
57       
58       setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
59       setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
60
61       setSetCCResultType(MVT::i1); 
62       setShiftAmountType(MVT::i64);
63
64       setOperationAction(ISD::EXTLOAD          , MVT::i1   , Promote);
65       setOperationAction(ISD::EXTLOAD          , MVT::f32  , Promote);
66
67       setOperationAction(ISD::ZEXTLOAD         , MVT::i1   , Expand);
68       setOperationAction(ISD::ZEXTLOAD         , MVT::i32  , Expand);
69
70       setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
71       setOperationAction(ISD::SEXTLOAD         , MVT::i8   , Expand);
72       setOperationAction(ISD::SEXTLOAD         , MVT::i16  , Expand);
73
74       setOperationAction(ISD::SREM             , MVT::f32  , Expand);
75       setOperationAction(ISD::SREM             , MVT::f64  , Expand);
76
77       setOperationAction(ISD::UREM             , MVT::f32  , Expand);
78       setOperationAction(ISD::UREM             , MVT::f64  , Expand);
79       
80       setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
81       setOperationAction(ISD::MEMSET           , MVT::Other, Expand);
82       setOperationAction(ISD::MEMCPY           , MVT::Other, Expand);
83
84       computeRegisterProperties();
85
86       addLegalFPImmediate(+0.0);
87       addLegalFPImmediate(+1.0);
88       addLegalFPImmediate(-0.0);
89       addLegalFPImmediate(-1.0);
90     }
91
92     /// LowerArguments - This hook must be implemented to indicate how we should
93     /// lower the arguments for the specified function, into the specified DAG.
94     virtual std::vector<SDOperand>
95     LowerArguments(Function &F, SelectionDAG &DAG);
96
97     /// LowerCallTo - This hook lowers an abstract call to a function into an
98     /// actual call.
99     virtual std::pair<SDOperand, SDOperand>
100     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
101                 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
102
103     virtual std::pair<SDOperand, SDOperand>
104     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
105
106     virtual std::pair<SDOperand,SDOperand>
107     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
108                    const Type *ArgTy, SelectionDAG &DAG);
109
110     virtual std::pair<SDOperand, SDOperand>
111     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
112                             SelectionDAG &DAG);
113
114     void restoreGP_SP_RP(MachineBasicBlock* BB)
115     {
116       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(GP);
117       BuildMI(BB, IA64::MOV, 1, IA64::r12).addReg(SP);
118       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
119     }
120
121     void restoreSP_RP(MachineBasicBlock* BB)
122     {
123       BuildMI(BB, IA64::MOV, 1, IA64::r12).addReg(SP);
124       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
125     }
126
127     void restoreRP(MachineBasicBlock* BB)
128     {
129       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
130     }
131
132     void restoreGP(MachineBasicBlock* BB)
133     {
134       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(GP);
135     }
136
137   };
138 }
139
140
141 std::vector<SDOperand>
142 IA64TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
143   std::vector<SDOperand> ArgValues;
144
145   //
146   // add beautiful description of IA64 stack frame format
147   // here (from intel 24535803.pdf most likely)
148   //
149   MachineFunction &MF = DAG.getMachineFunction();
150   MachineFrameInfo *MFI = MF.getFrameInfo();
151
152   GP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
153   SP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
154   RP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
155
156   MachineBasicBlock& BB = MF.front();
157
158   unsigned args_int[] = {IA64::r32, IA64::r33, IA64::r34, IA64::r35, 
159                          IA64::r36, IA64::r37, IA64::r38, IA64::r39};
160  
161   unsigned args_FP[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11, 
162                         IA64::F12,IA64::F13,IA64::F14, IA64::F15};
163  
164   unsigned argVreg[8];
165   unsigned argPreg[8];
166   unsigned argOpc[8];
167
168   unsigned used_FPArgs = 0; // how many FP args have been used so far?
169  
170   unsigned ArgOffset = 0;
171   int count = 0;
172   
173   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
174     {
175       SDOperand newroot, argt;
176       if(count < 8) { // need to fix this logic? maybe.
177           
178         switch (getValueType(I->getType())) {
179           default:
180             std::cerr << "ERROR in LowerArgs: unknown type "
181               << getValueType(I->getType()) << "\n";
182             abort();
183           case MVT::f32:
184             // fixme? (well, will need to for weird FP structy stuff, 
185             // see intel ABI docs)
186           case MVT::f64:
187             BuildMI(&BB, IA64::IDEF, 0, args_FP[used_FPArgs]);
188             // floating point args go into f8..f15 as-needed, the increment
189             argVreg[count] =                              // is below..:
190             MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::f64));
191             // FP args go into f8..f15 as needed: (hence the ++)
192             argPreg[count] = args_FP[used_FPArgs++];
193             argOpc[count] = IA64::FMOV;
194             argt = newroot = DAG.getCopyFromReg(argVreg[count],
195                 getValueType(I->getType()), DAG.getRoot());
196             break;
197           case MVT::i1: // NOTE: as far as C abi stuff goes,
198                         // bools are just boring old ints
199           case MVT::i8:
200           case MVT::i16:
201           case MVT::i32:
202           case MVT::i64:
203             BuildMI(&BB, IA64::IDEF, 0, args_int[count]);
204             argVreg[count] = 
205             MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
206             argPreg[count] = args_int[count];
207             argOpc[count] = IA64::MOV; 
208             argt = newroot =
209               DAG.getCopyFromReg(argVreg[count], MVT::i64, DAG.getRoot());
210             if ( getValueType(I->getType()) != MVT::i64)
211               argt = DAG.getNode(ISD::TRUNCATE, getValueType(I->getType()),
212                   newroot);
213             break;
214         }
215       } else { // more than 8 args go into the frame
216         // Create the frame index object for this incoming parameter...
217         ArgOffset = 16 + 8 * (count - 8);
218         int FI = MFI->CreateFixedObject(8, ArgOffset);
219           
220         // Create the SelectionDAG nodes corresponding to a load 
221         //from this parameter
222         SDOperand FIN = DAG.getFrameIndex(FI, MVT::i64);
223         argt = newroot = DAG.getLoad(getValueType(I->getType()), 
224             DAG.getEntryNode(), FIN);
225       }
226       ++count;
227       DAG.setRoot(newroot.getValue(1));
228       ArgValues.push_back(argt);
229     }    
230
231        
232   // Create a vreg to hold the output of (what will become)
233   // the "alloc" instruction
234   VirtGPR = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
235   BuildMI(&BB, IA64::PSEUDO_ALLOC, 0, VirtGPR);
236   // we create a PSEUDO_ALLOC (pseudo)instruction for now
237
238   BuildMI(&BB, IA64::IDEF, 0, IA64::r1);
239
240   // hmm:
241   BuildMI(&BB, IA64::IDEF, 0, IA64::r12);
242   BuildMI(&BB, IA64::IDEF, 0, IA64::rp);
243   // ..hmm.
244
245   BuildMI(&BB, IA64::MOV, 1, GP).addReg(IA64::r1);
246
247   // hmm:
248   BuildMI(&BB, IA64::MOV, 1, SP).addReg(IA64::r12);
249   BuildMI(&BB, IA64::MOV, 1, RP).addReg(IA64::rp);
250   // ..hmm.
251
252   unsigned tempOffset=0;
253  
254   // if this is a varargs function, we simply lower llvm.va_start by
255   // pointing to the first entry
256   if(F.isVarArg()) {
257     tempOffset=0;
258     VarArgsFrameIndex = MFI->CreateFixedObject(8, tempOffset);
259   }
260  
261   // here we actually do the moving of args, and store them to the stack
262   // too if this is a varargs function:
263   for (int i = 0; i < count && i < 8; ++i) {
264     BuildMI(&BB, argOpc[i], 1, argVreg[i]).addReg(argPreg[i]);
265     if(F.isVarArg()) {
266       // if this is a varargs function, we copy the input registers to the stack
267       int FI = MFI->CreateFixedObject(8, tempOffset);
268       tempOffset+=8;   //XXX: is it safe to use r22 like this?
269       BuildMI(&BB, IA64::MOV, 1, IA64::r22).addFrameIndex(FI);
270       // FIXME: we should use st8.spill here, one day
271       BuildMI(&BB, IA64::ST8, 1, IA64::r22).addReg(argPreg[i]);
272     }
273   }
274
275   return ArgValues;
276 }
277   
278 std::pair<SDOperand, SDOperand>
279 IA64TargetLowering::LowerCallTo(SDOperand Chain,
280                                  const Type *RetTy, bool isVarArg,
281          SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG) {
282
283   MachineFunction &MF = DAG.getMachineFunction();
284
285   unsigned NumBytes = 16;
286   unsigned outRegsUsed = 0;
287
288   if (Args.size() > 8) {
289     NumBytes += (Args.size() - 8) * 8;
290     outRegsUsed = 8;
291   } else {
292     outRegsUsed = Args.size();
293   }
294  
295   // FIXME? this WILL fail if we ever try to pass around an arg that
296   // consumes more than a single output slot (a 'real' double, int128
297   // some sort of aggregate etc.), as we'll underestimate how many 'outX'
298   // registers we use. Hopefully, the assembler will notice.
299   MF.getInfo<IA64FunctionInfo>()->outRegsUsed=
300     std::max(outRegsUsed, MF.getInfo<IA64FunctionInfo>()->outRegsUsed);
301   
302   Chain = DAG.getNode(ISD::ADJCALLSTACKDOWN, MVT::Other, Chain,
303                         DAG.getConstant(NumBytes, getPointerTy()));
304  
305   std::vector<SDOperand> args_to_use;
306   for (unsigned i = 0, e = Args.size(); i != e; ++i)
307     {
308       switch (getValueType(Args[i].second)) {
309       default: assert(0 && "unexpected argument type!");
310       case MVT::i1:
311       case MVT::i8:
312       case MVT::i16:
313       case MVT::i32:
314         //promote to 64-bits, sign/zero extending based on type
315         //of the argument
316         if(Args[i].second->isSigned())
317           Args[i].first = DAG.getNode(ISD::SIGN_EXTEND, MVT::i64,
318               Args[i].first);
319         else
320           Args[i].first = DAG.getNode(ISD::ZERO_EXTEND, MVT::i64,
321               Args[i].first);
322         break;
323       case MVT::f32:
324         //promote to 64-bits
325         Args[i].first = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Args[i].first);
326       case MVT::f64:
327       case MVT::i64:
328         break;
329       }
330       args_to_use.push_back(Args[i].first);
331     }
332
333   std::vector<MVT::ValueType> RetVals;
334   MVT::ValueType RetTyVT = getValueType(RetTy);
335   if (RetTyVT != MVT::isVoid)
336     RetVals.push_back(RetTyVT);
337   RetVals.push_back(MVT::Other);
338
339   SDOperand TheCall = SDOperand(DAG.getCall(RetVals, Chain,
340         Callee, args_to_use), 0);
341   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
342   Chain = DAG.getNode(ISD::ADJCALLSTACKUP, MVT::Other, Chain,
343                       DAG.getConstant(NumBytes, getPointerTy()));
344   return std::make_pair(TheCall, Chain);
345 }
346
347 std::pair<SDOperand, SDOperand>
348 IA64TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
349   // vastart just returns the address of the VarArgsFrameIndex slot.
350   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i64), Chain);
351 }
352
353 std::pair<SDOperand,SDOperand> IA64TargetLowering::
354 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
355                const Type *ArgTy, SelectionDAG &DAG) {
356
357   MVT::ValueType ArgVT = getValueType(ArgTy);
358   SDOperand Result;
359   if (!isVANext) {
360     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList);
361   } else {
362     unsigned Amt;
363     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
364       Amt = 8;
365     else {
366       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
367              "Other types should have been promoted for varargs!");
368       Amt = 8;
369     }
370     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
371                          DAG.getConstant(Amt, VAList.getValueType()));
372   }
373   return std::make_pair(Result, Chain);
374 }
375
376 std::pair<SDOperand, SDOperand> IA64TargetLowering::
377 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
378                         SelectionDAG &DAG) {
379
380   assert(0 && "LowerFrameReturnAddress not done yet\n");
381   abort();
382 }
383
384
385 namespace {
386
387   //===--------------------------------------------------------------------===//
388   /// ISel - IA64 specific code to select IA64 machine instructions for
389   /// SelectionDAG operations.
390   ///
391   class ISel : public SelectionDAGISel {
392     /// IA64Lowering - This object fully describes how to lower LLVM code to an
393     /// IA64-specific SelectionDAG.
394     IA64TargetLowering IA64Lowering;
395
396     /// ExprMap - As shared expressions are codegen'd, we keep track of which
397     /// vreg the value is produced in, so we only emit one copy of each compiled
398     /// tree.
399     std::map<SDOperand, unsigned> ExprMap;
400     std::set<SDOperand> LoweredTokens;
401
402   public:
403     ISel(TargetMachine &TM) : SelectionDAGISel(IA64Lowering), IA64Lowering(TM) {
404     }
405
406     /// InstructionSelectBasicBlock - This callback is invoked by
407     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
408     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
409
410     unsigned SelectExpr(SDOperand N);
411     void Select(SDOperand N);
412   };
413 }
414
415 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
416 /// when it has created a SelectionDAG for us to codegen.
417 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
418
419   // Codegen the basic block.
420   Select(DAG.getRoot());
421
422   // Clear state used for selection.
423   ExprMap.clear();
424   LoweredTokens.clear();
425 }
426
427 /// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
428 /// returns zero when the input is not exactly a power of two.
429 static uint64_t ExactLog2(uint64_t Val) {
430   if (Val == 0 || (Val & (Val-1))) return 0;
431   unsigned Count = 0;
432   while (Val != 1) {
433     Val >>= 1;
434     ++Count;
435   }
436   return Count;
437 }
438
439 /// ponderIntegerDivisionBy - When handling integer divides, if the divide
440 /// is by a constant such that we can efficiently codegen it, this
441 /// function says what to do. Currently, it returns 0 if the division must
442 /// become a genuine divide, and 1 if the division can be turned into a
443 /// right shift.
444 static unsigned ponderIntegerDivisionBy(SDOperand N, bool isSigned,
445                                       unsigned& Imm) {
446   if (N.getOpcode() != ISD::Constant) return 0; // if not a divide by
447                                                 // a constant, give up.
448
449   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
450
451   if ((Imm = ExactLog2(v))) { // if a division by a power of two, say so 
452     return 1;
453   } 
454   
455   return 0; // fallthrough
456 }
457
458 static unsigned ponderIntegerAdditionWith(SDOperand N, unsigned& Imm) {
459   if (N.getOpcode() != ISD::Constant) return 0; // if not adding a
460                                                 // constant, give up.
461   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
462
463   if (v <= 8191 && v >= -8192) { // if this constants fits in 14 bits, say so
464     Imm = v & 0x3FFF; // 14 bits
465     return 1;
466   } 
467   return 0; // fallthrough
468 }
469
470 static unsigned ponderIntegerSubtractionFrom(SDOperand N, unsigned& Imm) {
471   if (N.getOpcode() != ISD::Constant) return 0; // if not subtracting a
472                                                 // constant, give up.
473   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
474
475   if (v <= 127 && v >= -128) { // if this constants fits in 8 bits, say so
476     Imm = v & 0xFF; // 8 bits
477     return 1;
478   } 
479   return 0; // fallthrough
480 }
481
482 unsigned ISel::SelectExpr(SDOperand N) {
483   unsigned Result;
484   unsigned Tmp1, Tmp2, Tmp3;
485   unsigned Opc = 0;
486   MVT::ValueType DestType = N.getValueType();
487
488   unsigned opcode = N.getOpcode();
489
490   SDNode *Node = N.Val;
491   SDOperand Op0, Op1;
492
493   if (Node->getOpcode() == ISD::CopyFromReg)
494     // Just use the specified register as our input.
495     return dyn_cast<RegSDNode>(Node)->getReg();
496   
497   unsigned &Reg = ExprMap[N];
498   if (Reg) return Reg;
499   
500   if (N.getOpcode() != ISD::CALL)
501     Reg = Result = (N.getValueType() != MVT::Other) ?
502       MakeReg(N.getValueType()) : 1;
503   else {
504     // If this is a call instruction, make sure to prepare ALL of the result
505     // values as well as the chain.
506     if (Node->getNumValues() == 1)
507       Reg = Result = 1;  // Void call, just a chain.
508     else {
509       Result = MakeReg(Node->getValueType(0));
510       ExprMap[N.getValue(0)] = Result;
511       for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
512         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
513       ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
514     }
515   }
516   
517   switch (N.getOpcode()) {
518   default:
519     Node->dump();
520     assert(0 && "Node not handled!\n");
521
522   case ISD::FrameIndex: {
523     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
524     BuildMI(BB, IA64::MOV, 1, Result).addFrameIndex(Tmp1);
525     return Result;
526   }
527
528   case ISD::ConstantPool: {
529     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
530     IA64Lowering.restoreGP(BB); // FIXME: do i really need this?
531     BuildMI(BB, IA64::ADD, 2, Result).addConstantPoolIndex(Tmp1)
532       .addReg(IA64::r1);
533     return Result;
534   }
535
536   case ISD::ConstantFP: {
537     Tmp1 = Result;   // Intermediate Register
538     if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
539         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
540       Tmp1 = MakeReg(MVT::f64);
541
542     if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
543         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
544       BuildMI(BB, IA64::FMOV, 1, Tmp1).addReg(IA64::F0); // load 0.0
545     else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
546              cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
547       BuildMI(BB, IA64::FMOV, 1, Tmp1).addReg(IA64::F1); // load 1.0
548     else
549       assert(0 && "Unexpected FP constant!");
550     if (Tmp1 != Result)
551       // we multiply by +1.0, negate (this is FNMA), and then add 0.0
552       BuildMI(BB, IA64::FNMA, 3, Result).addReg(Tmp1).addReg(IA64::F1)
553         .addReg(IA64::F0);
554     return Result;
555   }
556
557   case ISD::DYNAMIC_STACKALLOC: {
558     // Generate both result values.
559     if (Result != 1)
560       ExprMap[N.getValue(1)] = 1;   // Generate the token
561     else
562       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
563
564     // FIXME: We are currently ignoring the requested alignment for handling
565     // greater than the stack alignment.  This will need to be revisited at some
566     // point.  Align = N.getOperand(2);
567
568     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
569         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
570       std::cerr << "Cannot allocate stack object with greater alignment than"
571                 << " the stack alignment yet!";
572       abort();
573     }
574  
575 /*    
576     Select(N.getOperand(0));
577     if (ConstantSDNode* CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
578     {
579       if (CN->getValue() < 32000)
580       {
581         BuildMI(BB, IA64::ADDIMM22, 2, IA64::r12).addReg(IA64::r12)
582           .addImm(-CN->getValue());
583       } else {
584         Tmp1 = SelectExpr(N.getOperand(1));
585         // Subtract size from stack pointer, thereby allocating some space.
586         BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
587       }
588     } else {
589       Tmp1 = SelectExpr(N.getOperand(1));
590       // Subtract size from stack pointer, thereby allocating some space.
591       BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
592     }
593 */
594     Select(N.getOperand(0));
595     Tmp1 = SelectExpr(N.getOperand(1));
596     // Subtract size from stack pointer, thereby allocating some space.
597     BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
598     // Put a pointer to the space into the result register, by copying the
599     // stack pointer.
600     BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r12);
601     return Result;
602   }
603     
604   case ISD::SELECT: {
605       Tmp1 = SelectExpr(N.getOperand(0)); //Cond
606       Tmp2 = SelectExpr(N.getOperand(1)); //Use if TRUE
607       Tmp3 = SelectExpr(N.getOperand(2)); //Use if FALSE
608
609       unsigned bogoResult;
610       
611       switch (N.getOperand(1).getValueType()) {
612         default: assert(0 &&
613         "ISD::SELECT: 'select'ing something other than i64 or f64!\n");
614         case MVT::i64:
615           bogoResult=MakeReg(MVT::i64);
616           break;
617         case MVT::f64:
618           bogoResult=MakeReg(MVT::f64);
619           break;
620       }
621
622       BuildMI(BB, IA64::MOV, 1, bogoResult).addReg(Tmp3);
623       BuildMI(BB, IA64::CMOV, 2, Result).addReg(bogoResult).addReg(Tmp2)
624         .addReg(Tmp1); // FIXME: should be FMOV/FCMOV sometimes,
625                        // though this will work for now (no JIT)
626       return Result;
627   }
628   
629   case ISD::Constant: {
630     unsigned depositPos=0;
631     unsigned depositLen=0;
632     switch (N.getValueType()) {
633       default: assert(0 && "Cannot use constants of this type!");
634       case MVT::i1: { // if a bool, we don't 'load' so much as generate
635                       // the constant:
636                       if(cast<ConstantSDNode>(N)->getValue())  // true:
637                         BuildMI(BB, IA64::CMPEQ, 2, Result)
638                           .addReg(IA64::r0).addReg(IA64::r0);
639                       else // false:
640                         BuildMI(BB, IA64::CMPNE, 2, Result)
641                           .addReg(IA64::r0).addReg(IA64::r0);
642                       return Result; // early exit
643                     }
644       case MVT::i64: break;
645     }
646    
647     int64_t immediate = cast<ConstantSDNode>(N)->getValue();
648
649     if(immediate==0) { // if the constant is just zero,
650       BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r0); // just copy r0
651       return Result; // early exit
652     }
653
654     if (immediate <= 8191 && immediate >= -8192) {
655       // if this constants fits in 14 bits, we use a mov the assembler will
656       // turn into:   "adds rDest=imm,r0"  (and _not_ "andl"...)
657       BuildMI(BB, IA64::MOVSIMM14, 1, Result).addSImm(immediate);
658       return Result; // early exit
659     } 
660
661     if (immediate <= 2097151 && immediate >= -2097152) {
662       // if this constants fits in 22 bits, we use a mov the assembler will
663       // turn into:   "addl rDest=imm,r0"
664       BuildMI(BB, IA64::MOVSIMM22, 1, Result).addSImm(immediate);
665       return Result; // early exit
666     } 
667
668     /* otherwise, our immediate is big, so we use movl */
669     uint64_t Imm = immediate;
670     BuildMI(BB, IA64::MOVLIMM64, 1, Result).addU64Imm(Imm);
671     return Result;
672   }
673
674   case ISD::UNDEF: {
675     BuildMI(BB, IA64::IDEF, 0, Result);
676     return Result;
677   }
678     
679   case ISD::GlobalAddress: {
680     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
681     unsigned Tmp1 = MakeReg(MVT::i64);
682
683     BuildMI(BB, IA64::ADD, 2, Tmp1).addGlobalAddress(GV).addReg(IA64::r1);
684     BuildMI(BB, IA64::LD8, 1, Result).addReg(Tmp1);
685
686     return Result;
687   }
688   
689   case ISD::ExternalSymbol: {
690     const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
691 // assert(0 && "sorry, but what did you want an ExternalSymbol for again?");
692     BuildMI(BB, IA64::MOV, 1, Result).addExternalSymbol(Sym); // XXX
693     return Result;
694   }
695
696   case ISD::FP_EXTEND: {
697     Tmp1 = SelectExpr(N.getOperand(0));
698     BuildMI(BB, IA64::FMOV, 1, Result).addReg(Tmp1);
699     return Result;
700   }
701
702   case ISD::ZERO_EXTEND: {
703     Tmp1 = SelectExpr(N.getOperand(0)); // value
704     
705     switch (N.getOperand(0).getValueType()) {
706     default: assert(0 && "Cannot zero-extend this type!");
707     case MVT::i8:  Opc = IA64::ZXT1; break;
708     case MVT::i16: Opc = IA64::ZXT2; break;
709     case MVT::i32: Opc = IA64::ZXT4; break;
710
711     // we handle bools differently! : 
712     case MVT::i1: { // if the predicate reg has 1, we want a '1' in our GR.
713                     unsigned dummy = MakeReg(MVT::i64);
714                     // first load zero:
715                     BuildMI(BB, IA64::MOV, 1, dummy).addReg(IA64::r0);
716                     // ...then conditionally (PR:Tmp1) add 1:
717                     BuildMI(BB, IA64::TPCADDIMM22, 2, Result).addReg(dummy)
718                       .addImm(1).addReg(Tmp1);
719                     return Result; // XXX early exit!
720                   }
721     }
722
723     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
724     return Result;
725    }
726
727   case ISD::SIGN_EXTEND: {   // we should only have to handle i1 -> i64 here!!!
728
729 assert(0 && "hmm, ISD::SIGN_EXTEND: shouldn't ever be reached. bad luck!\n");
730
731     Tmp1 = SelectExpr(N.getOperand(0)); // value
732     
733     switch (N.getOperand(0).getValueType()) {
734     default: assert(0 && "Cannot sign-extend this type!");
735     case MVT::i1:  assert(0 && "trying to sign extend a bool? ow.\n");
736                    Opc = IA64::SXT1; break;
737                    // FIXME: for now, we treat bools the same as i8s
738     case MVT::i8:  Opc = IA64::SXT1; break;
739     case MVT::i16: Opc = IA64::SXT2; break;
740     case MVT::i32: Opc = IA64::SXT4; break;
741     }
742
743     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
744     return Result;
745    }
746
747   case ISD::TRUNCATE: {
748     // we use the funky dep.z (deposit (zero)) instruction to deposit bits
749     // of R0 appropriately.
750     switch (N.getOperand(0).getValueType()) {
751     default: assert(0 && "Unknown truncate!");
752     case MVT::i64: break;
753     }
754     Tmp1 = SelectExpr(N.getOperand(0));
755     unsigned depositPos, depositLen;
756
757     switch (N.getValueType()) {
758     default: assert(0 && "Unknown truncate!");
759     case MVT::i1: {
760       // if input (normal reg) is 0, 0!=0 -> false (0), if 1, 1!=0 ->true (1):
761                     BuildMI(BB, IA64::CMPNE, 2, Result).addReg(Tmp1)
762                       .addReg(IA64::r0);
763                     return Result; // XXX early exit!
764                   }
765     case MVT::i8:  depositPos=0; depositLen=8;  break;
766     case MVT::i16: depositPos=0; depositLen=16; break;
767     case MVT::i32: depositPos=0; depositLen=32; break;
768     }
769     BuildMI(BB, IA64::DEPZ, 1, Result).addReg(Tmp1)
770       .addImm(depositPos).addImm(depositLen);
771     return Result;
772   }
773
774 /*                      
775   case ISD::FP_ROUND: {
776     assert (DestType == MVT::f32 && N.getOperand(0).getValueType() == MVT::f64 &&
777         "error: trying to FP_ROUND something other than f64 -> f32!\n");
778     Tmp1 = SelectExpr(N.getOperand(0));
779     BuildMI(BB, IA64::FADDS, 2, Result).addReg(Tmp1).addReg(IA64::F0);
780     // we add 0.0 using a single precision add to do rounding
781     return Result;
782   }
783 */
784
785 // FIXME: the following 4 cases need cleaning
786   case ISD::SINT_TO_FP: {
787     Tmp1 = SelectExpr(N.getOperand(0));
788     Tmp2 = MakeReg(MVT::f64);
789     unsigned dummy = MakeReg(MVT::f64);
790     BuildMI(BB, IA64::SETFSIG, 1, Tmp2).addReg(Tmp1);
791     BuildMI(BB, IA64::FCVTXF, 1, dummy).addReg(Tmp2);
792     BuildMI(BB, IA64::FNORMD, 1, Result).addReg(dummy);
793     return Result;
794   }
795
796   case ISD::UINT_TO_FP: {
797     Tmp1 = SelectExpr(N.getOperand(0));
798     Tmp2 = MakeReg(MVT::f64);
799     unsigned dummy = MakeReg(MVT::f64);
800     BuildMI(BB, IA64::SETFSIG, 1, Tmp2).addReg(Tmp1);
801     BuildMI(BB, IA64::FCVTXUF, 1, dummy).addReg(Tmp2);
802     BuildMI(BB, IA64::FNORMD, 1, Result).addReg(dummy);
803     return Result;
804   }
805
806   case ISD::FP_TO_SINT: {
807     Tmp1 = SelectExpr(N.getOperand(0));
808     Tmp2 = MakeReg(MVT::f64);
809     BuildMI(BB, IA64::FCVTFXTRUNC, 1, Tmp2).addReg(Tmp1);
810     BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(Tmp2);
811     return Result;
812   }
813
814   case ISD::FP_TO_UINT: {
815     Tmp1 = SelectExpr(N.getOperand(0));
816     Tmp2 = MakeReg(MVT::f64);
817     BuildMI(BB, IA64::FCVTFXUTRUNC, 1, Tmp2).addReg(Tmp1);
818     BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(Tmp2);
819     return Result;
820   }
821
822   case ISD::ADD: {
823     if(DestType == MVT::f64 && N.getOperand(0).getOpcode() == ISD::MUL &&
824        N.getOperand(0).Val->hasOneUse()) { // if we can fold this add
825                                            // into an fma, do so:
826       // ++FusedFP; // Statistic
827       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
828       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
829       Tmp3 = SelectExpr(N.getOperand(1));
830       BuildMI(BB, IA64::FMA, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
831       return Result; // early exit
832     }
833     Tmp1 = SelectExpr(N.getOperand(0));
834     if(DestType != MVT::f64) { // integer addition:
835         switch (ponderIntegerAdditionWith(N.getOperand(1), Tmp3)) {
836           case 1: // adding a constant that's 14 bits
837             BuildMI(BB, IA64::ADDIMM14, 2, Result).addReg(Tmp1).addSImm(Tmp3);
838             return Result; // early exit
839         } // fallthrough and emit a reg+reg ADD:
840         Tmp2 = SelectExpr(N.getOperand(1));
841         BuildMI(BB, IA64::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
842     } else { // this is a floating point addition
843       Tmp2 = SelectExpr(N.getOperand(1));
844       BuildMI(BB, IA64::FADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
845     }
846     return Result;
847   }
848
849   case ISD::MUL: {
850     Tmp1 = SelectExpr(N.getOperand(0));
851     Tmp2 = SelectExpr(N.getOperand(1));
852
853     if(DestType != MVT::f64) { // TODO: speed!
854       // boring old integer multiply with xma
855       unsigned TempFR1=MakeReg(MVT::f64);
856       unsigned TempFR2=MakeReg(MVT::f64);
857       unsigned TempFR3=MakeReg(MVT::f64);
858       BuildMI(BB, IA64::SETFSIG, 1, TempFR1).addReg(Tmp1);
859       BuildMI(BB, IA64::SETFSIG, 1, TempFR2).addReg(Tmp2);
860       BuildMI(BB, IA64::XMAL, 1, TempFR3).addReg(TempFR1).addReg(TempFR2)
861         .addReg(IA64::F0);
862       BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(TempFR3);
863     }
864     else  // floating point multiply
865       BuildMI(BB, IA64::FMPY, 2, Result).addReg(Tmp1).addReg(Tmp2);
866     return Result;
867   }
868   
869   case ISD::SUB: {
870     if(DestType == MVT::f64 && N.getOperand(0).getOpcode() == ISD::MUL &&
871        N.getOperand(0).Val->hasOneUse()) { // if we can fold this sub
872                                            // into an fms, do so:
873       // ++FusedFP; // Statistic
874       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
875       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
876       Tmp3 = SelectExpr(N.getOperand(1));
877       BuildMI(BB, IA64::FMS, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
878       return Result; // early exit
879     }
880     Tmp2 = SelectExpr(N.getOperand(1));
881     if(DestType != MVT::f64) { // integer subtraction:
882         switch (ponderIntegerSubtractionFrom(N.getOperand(0), Tmp3)) {
883           case 1: // subtracting *from* an 8 bit constant:
884             BuildMI(BB, IA64::SUBIMM8, 2, Result).addSImm(Tmp3).addReg(Tmp2);
885             return Result; // early exit
886         } // fallthrough and emit a reg+reg SUB:
887         Tmp1 = SelectExpr(N.getOperand(0));
888         BuildMI(BB, IA64::SUB, 2, Result).addReg(Tmp1).addReg(Tmp2);
889     } else { // this is a floating point subtraction
890       Tmp1 = SelectExpr(N.getOperand(0));
891       BuildMI(BB, IA64::FSUB, 2, Result).addReg(Tmp1).addReg(Tmp2);
892     }
893     return Result;
894   }
895
896   case ISD::FABS: {
897     Tmp1 = SelectExpr(N.getOperand(0));
898     assert(DestType == MVT::f64 && "trying to fabs something other than f64?");
899     BuildMI(BB, IA64::FABS, 1, Result).addReg(Tmp1);
900     return Result;
901   }
902  
903   case ISD::FNEG: {
904     assert(DestType == MVT::f64 && "trying to fneg something other than f64?");
905
906     if (ISD::FABS == N.getOperand(0).getOpcode()) { // && hasOneUse()? 
907       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
908       BuildMI(BB, IA64::FNEGABS, 1, Result).addReg(Tmp1); // fold in abs
909     } else {
910       Tmp1 = SelectExpr(N.getOperand(0));
911       BuildMI(BB, IA64::FNEG, 1, Result).addReg(Tmp1); // plain old fneg
912     }
913
914     return Result;
915   }
916          
917   case ISD::AND: {
918      switch (N.getValueType()) {
919     default: assert(0 && "Cannot AND this type!");
920     case MVT::i1: { // if a bool, we emit a pseudocode AND
921       unsigned pA = SelectExpr(N.getOperand(0));
922       unsigned pB = SelectExpr(N.getOperand(1));
923        
924 /* our pseudocode for AND is:
925  *
926 (pA) cmp.eq.unc pC,p0 = r0,r0   // pC = pA
927      cmp.eq pTemp,p0 = r0,r0    // pTemp = NOT pB
928      ;;
929 (pB) cmp.ne pTemp,p0 = r0,r0
930      ;;
931 (pTemp)cmp.ne pC,p0 = r0,r0    // if (NOT pB) pC = 0
932
933 */
934       unsigned pTemp = MakeReg(MVT::i1);
935      
936       unsigned bogusTemp1 = MakeReg(MVT::i1);
937       unsigned bogusTemp2 = MakeReg(MVT::i1);
938       unsigned bogusTemp3 = MakeReg(MVT::i1);
939       unsigned bogusTemp4 = MakeReg(MVT::i1);
940     
941       BuildMI(BB, IA64::PCMPEQUNC, 3, bogusTemp1)
942         .addReg(IA64::r0).addReg(IA64::r0).addReg(pA);
943       BuildMI(BB, IA64::CMPEQ, 2, bogusTemp2)
944         .addReg(IA64::r0).addReg(IA64::r0);
945       BuildMI(BB, IA64::TPCMPNE, 3, pTemp)
946         .addReg(bogusTemp2).addReg(IA64::r0).addReg(IA64::r0).addReg(pB);
947       BuildMI(BB, IA64::TPCMPNE, 3, Result)
948         .addReg(bogusTemp1).addReg(IA64::r0).addReg(IA64::r0).addReg(pTemp);
949       break;
950     }
951     // if not a bool, we just AND away:
952     case MVT::i8:
953     case MVT::i16:
954     case MVT::i32:
955     case MVT::i64: {
956       Tmp1 = SelectExpr(N.getOperand(0));
957       Tmp2 = SelectExpr(N.getOperand(1));
958       BuildMI(BB, IA64::AND, 2, Result).addReg(Tmp1).addReg(Tmp2);
959       break;
960     }
961     }
962     return Result;
963   }
964  
965   case ISD::OR: {
966   switch (N.getValueType()) {
967     default: assert(0 && "Cannot OR this type!");
968     case MVT::i1: { // if a bool, we emit a pseudocode OR
969       unsigned pA = SelectExpr(N.getOperand(0));
970       unsigned pB = SelectExpr(N.getOperand(1));
971
972       unsigned pTemp1 = MakeReg(MVT::i1);
973        
974 /* our pseudocode for OR is:
975  *
976
977 pC = pA OR pB
978 -------------
979
980 (pA)    cmp.eq.unc pC,p0 = r0,r0  // pC = pA
981         ;;
982 (pB)    cmp.eq pC,p0 = r0,r0    // if (pB) pC = 1
983
984 */
985       BuildMI(BB, IA64::PCMPEQUNC, 3, pTemp1)
986         .addReg(IA64::r0).addReg(IA64::r0).addReg(pA);
987       BuildMI(BB, IA64::TPCMPEQ, 3, Result)
988         .addReg(pTemp1).addReg(IA64::r0).addReg(IA64::r0).addReg(pB);
989       break;
990     }
991     // if not a bool, we just OR away:
992     case MVT::i8:
993     case MVT::i16:
994     case MVT::i32:
995     case MVT::i64: {
996       Tmp1 = SelectExpr(N.getOperand(0));
997       Tmp2 = SelectExpr(N.getOperand(1));
998       BuildMI(BB, IA64::OR, 2, Result).addReg(Tmp1).addReg(Tmp2);
999       break;
1000     }
1001     }
1002     return Result;
1003   }
1004          
1005   case ISD::XOR: {
1006      switch (N.getValueType()) {
1007     default: assert(0 && "Cannot XOR this type!");
1008     case MVT::i1: { // if a bool, we emit a pseudocode XOR
1009       unsigned pY = SelectExpr(N.getOperand(0));
1010       unsigned pZ = SelectExpr(N.getOperand(1));
1011
1012 /* one possible routine for XOR is:
1013
1014       // Compute px = py ^ pz
1015         // using sum of products: px = (py & !pz) | (pz & !py)
1016         // Uses 5 instructions in 3 cycles.
1017         // cycle 1
1018 (pz)    cmp.eq.unc      px = r0, r0     // px = pz
1019 (py)    cmp.eq.unc      pt = r0, r0     // pt = py
1020         ;;
1021         // cycle 2
1022 (pt)    cmp.ne.and      px = r0, r0     // px = px & !pt (px = pz & !pt)
1023 (pz)    cmp.ne.and      pt = r0, r0     // pt = pt & !pz
1024         ;;
1025         } { .mmi
1026         // cycle 3
1027 (pt)    cmp.eq.or       px = r0, r0     // px = px | pt
1028
1029 *** Another, which we use here, requires one scratch GR. it is:
1030
1031         mov             rt = 0          // initialize rt off critical path
1032         ;;
1033
1034         // cycle 1
1035 (pz)    cmp.eq.unc      px = r0, r0     // px = pz
1036 (pz)    mov             rt = 1          // rt = pz
1037         ;;
1038         // cycle 2
1039 (py)    cmp.ne          px = 1, rt      // if (py) px = !pz
1040
1041 .. these routines kindly provided by Jim Hull
1042 */
1043       unsigned rt = MakeReg(MVT::i64);
1044
1045       // these two temporaries will never actually appear,
1046       // due to the two-address form of some of the instructions below
1047       unsigned bogoPR = MakeReg(MVT::i1);  // becomes Result
1048       unsigned bogoGR = MakeReg(MVT::i64); // becomes rt
1049
1050       BuildMI(BB, IA64::MOV, 1, bogoGR).addReg(IA64::r0);
1051       BuildMI(BB, IA64::PCMPEQUNC, 3, bogoPR)
1052         .addReg(IA64::r0).addReg(IA64::r0).addReg(pZ);
1053       BuildMI(BB, IA64::TPCADDIMM22, 2, rt)
1054         .addReg(bogoGR).addImm(1).addReg(pZ);
1055       BuildMI(BB, IA64::TPCMPIMM8NE, 3, Result)
1056         .addReg(bogoPR).addImm(1).addReg(rt).addReg(pY);
1057       break;
1058     }
1059     // if not a bool, we just XOR away:
1060     case MVT::i8:
1061     case MVT::i16:
1062     case MVT::i32:
1063     case MVT::i64: {
1064       Tmp1 = SelectExpr(N.getOperand(0));
1065       Tmp2 = SelectExpr(N.getOperand(1));
1066       BuildMI(BB, IA64::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1067       break;
1068     }
1069     }
1070     return Result;
1071   }
1072
1073   case ISD::SHL: {
1074     Tmp1 = SelectExpr(N.getOperand(0));
1075     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1076       Tmp2 = CN->getValue();
1077       BuildMI(BB, IA64::SHLI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1078     } else {
1079       Tmp2 = SelectExpr(N.getOperand(1));
1080       BuildMI(BB, IA64::SHL, 2, Result).addReg(Tmp1).addReg(Tmp2);
1081     }
1082     return Result;
1083   }
1084                  
1085   case ISD::SRL: {
1086     Tmp1 = SelectExpr(N.getOperand(0));
1087     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1088       Tmp2 = CN->getValue();
1089       BuildMI(BB, IA64::SHRUI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1090     } else {
1091       Tmp2 = SelectExpr(N.getOperand(1));
1092       BuildMI(BB, IA64::SHRU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1093     }
1094     return Result;
1095   }
1096                  
1097   case ISD::SRA: {
1098     Tmp1 = SelectExpr(N.getOperand(0));
1099     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1100       Tmp2 = CN->getValue();
1101       BuildMI(BB, IA64::SHRSI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1102     } else {
1103       Tmp2 = SelectExpr(N.getOperand(1));
1104       BuildMI(BB, IA64::SHRS, 2, Result).addReg(Tmp1).addReg(Tmp2);
1105     }
1106     return Result;
1107   }
1108
1109   case ISD::SDIV:
1110   case ISD::UDIV:
1111   case ISD::SREM:
1112   case ISD::UREM: {
1113
1114     Tmp1 = SelectExpr(N.getOperand(0));
1115     Tmp2 = SelectExpr(N.getOperand(1));
1116
1117     bool isFP=false;
1118
1119     if(DestType == MVT::f64) // XXX: we're not gonna be fed MVT::f32, are we?
1120       isFP=true;
1121
1122     bool isModulus=false; // is it a division or a modulus?
1123     bool isSigned=false;
1124
1125     switch(N.getOpcode()) {
1126       case ISD::SDIV:  isModulus=false; isSigned=true;  break;
1127       case ISD::UDIV:  isModulus=false; isSigned=false; break;
1128       case ISD::SREM:  isModulus=true;  isSigned=true;  break;
1129       case ISD::UREM:  isModulus=true;  isSigned=false; break;
1130     }
1131
1132     if(!isModulus && !isFP) { // if this is an integer divide,
1133       switch (ponderIntegerDivisionBy(N.getOperand(1), isSigned, Tmp3)) {
1134         case 1: // division by a constant that's a power of 2
1135           Tmp1 = SelectExpr(N.getOperand(0));
1136           if(isSigned) {  // argument could be negative, so emit some code:
1137             unsigned divAmt=Tmp3;
1138             unsigned tempGR1=MakeReg(MVT::i64);
1139             unsigned tempGR2=MakeReg(MVT::i64);
1140             unsigned tempGR3=MakeReg(MVT::i64);
1141             BuildMI(BB, IA64::SHRS, 2, tempGR1)
1142               .addReg(Tmp1).addImm(divAmt-1);
1143             BuildMI(BB, IA64::EXTRU, 3, tempGR2)
1144               .addReg(tempGR1).addImm(64-divAmt).addImm(divAmt);
1145             BuildMI(BB, IA64::ADD, 2, tempGR3)
1146               .addReg(Tmp1).addReg(tempGR2);
1147             BuildMI(BB, IA64::SHRS, 2, Result)
1148               .addReg(tempGR3).addImm(divAmt);
1149           }
1150           else // unsigned div-by-power-of-2 becomes a simple shift right:
1151             BuildMI(BB, IA64::SHRU, 2, Result).addReg(Tmp1).addImm(Tmp3);
1152           return Result; // early exit
1153       }
1154     }
1155
1156     unsigned TmpPR=MakeReg(MVT::i1);  // we need two scratch 
1157     unsigned TmpPR2=MakeReg(MVT::i1); // predicate registers,
1158     unsigned TmpF1=MakeReg(MVT::f64); // and one metric truckload of FP regs.
1159     unsigned TmpF2=MakeReg(MVT::f64); // lucky we have IA64?
1160     unsigned TmpF3=MakeReg(MVT::f64); // well, the real FIXME is to have
1161     unsigned TmpF4=MakeReg(MVT::f64); // isTwoAddress forms of these
1162     unsigned TmpF5=MakeReg(MVT::f64); // FP instructions so we can end up with
1163     unsigned TmpF6=MakeReg(MVT::f64); // stuff like setf.sig f10=f10 etc.
1164     unsigned TmpF7=MakeReg(MVT::f64);
1165     unsigned TmpF8=MakeReg(MVT::f64);
1166     unsigned TmpF9=MakeReg(MVT::f64);
1167     unsigned TmpF10=MakeReg(MVT::f64);
1168     unsigned TmpF11=MakeReg(MVT::f64);
1169     unsigned TmpF12=MakeReg(MVT::f64);
1170     unsigned TmpF13=MakeReg(MVT::f64);
1171     unsigned TmpF14=MakeReg(MVT::f64);
1172     unsigned TmpF15=MakeReg(MVT::f64);
1173  
1174     // OK, emit some code:
1175
1176     if(!isFP) {
1177       // first, load the inputs into FP regs.
1178       BuildMI(BB, IA64::SETFSIG, 1, TmpF1).addReg(Tmp1);
1179       BuildMI(BB, IA64::SETFSIG, 1, TmpF2).addReg(Tmp2);
1180       
1181       // next, convert the inputs to FP
1182       if(isSigned) {
1183         BuildMI(BB, IA64::FCVTXF, 1, TmpF3).addReg(TmpF1);
1184         BuildMI(BB, IA64::FCVTXF, 1, TmpF4).addReg(TmpF2);
1185       } else {
1186         BuildMI(BB, IA64::FCVTXUFS1, 1, TmpF3).addReg(TmpF1);
1187         BuildMI(BB, IA64::FCVTXUFS1, 1, TmpF4).addReg(TmpF2);
1188       }
1189       
1190     } else { // this is an FP divide/remainder, so we 'leak' some temp
1191              // regs and assign TmpF3=Tmp1, TmpF4=Tmp2
1192       TmpF3=Tmp1;
1193       TmpF4=Tmp2;
1194     }
1195
1196     // we start by computing an approximate reciprocal (good to 9 bits?)
1197     // note, this instruction writes _both_ TmpF5 (answer) and TmpPR (predicate)
1198     BuildMI(BB, IA64::FRCPAS1, 4)
1199       .addReg(TmpF5, MachineOperand::Def)
1200       .addReg(TmpPR, MachineOperand::Def)
1201       .addReg(TmpF3).addReg(TmpF4);
1202
1203     if(!isModulus) { // if this is a divide, we worry about div-by-zero
1204       unsigned bogusPR=MakeReg(MVT::i1); // won't appear, due to twoAddress
1205                                        // TPCMPNE below
1206       BuildMI(BB, IA64::CMPEQ, 2, bogusPR).addReg(IA64::r0).addReg(IA64::r0);
1207       BuildMI(BB, IA64::TPCMPNE, 3, TmpPR2).addReg(bogusPR)
1208         .addReg(IA64::r0).addReg(IA64::r0).addReg(TmpPR);
1209     }
1210
1211     // now we apply newton's method, thrice! (FIXME: this is ~72 bits of
1212     // precision, don't need this much for f32/i32)
1213     BuildMI(BB, IA64::CFNMAS1, 4, TmpF6)
1214       .addReg(TmpF4).addReg(TmpF5).addReg(IA64::F1).addReg(TmpPR);
1215     BuildMI(BB, IA64::CFMAS1,  4, TmpF7)
1216       .addReg(TmpF3).addReg(TmpF5).addReg(IA64::F0).addReg(TmpPR);
1217     BuildMI(BB, IA64::CFMAS1,  4, TmpF8)
1218       .addReg(TmpF6).addReg(TmpF6).addReg(IA64::F0).addReg(TmpPR);
1219     BuildMI(BB, IA64::CFMAS1,  4, TmpF9)
1220       .addReg(TmpF6).addReg(TmpF7).addReg(TmpF7).addReg(TmpPR);
1221     BuildMI(BB, IA64::CFMAS1,  4,TmpF10)
1222       .addReg(TmpF6).addReg(TmpF5).addReg(TmpF5).addReg(TmpPR);
1223     BuildMI(BB, IA64::CFMAS1,  4,TmpF11)
1224       .addReg(TmpF8).addReg(TmpF9).addReg(TmpF9).addReg(TmpPR);
1225     BuildMI(BB, IA64::CFMAS1,  4,TmpF12)
1226       .addReg(TmpF8).addReg(TmpF10).addReg(TmpF10).addReg(TmpPR);
1227     BuildMI(BB, IA64::CFNMAS1, 4,TmpF13)
1228       .addReg(TmpF4).addReg(TmpF11).addReg(TmpF3).addReg(TmpPR);
1229
1230        // FIXME: this is unfortunate :(
1231        // the story is that the dest reg of the fnma above and the fma below
1232        // (and therefore possibly the src of the fcvt.fx[u] as well) cannot
1233        // be the same register, or this code breaks if the first argument is
1234        // zero. (e.g. without this hack, 0%8 yields -64, not 0.)
1235     BuildMI(BB, IA64::CFMAS1,  4,TmpF14)
1236       .addReg(TmpF13).addReg(TmpF12).addReg(TmpF11).addReg(TmpPR);
1237
1238     if(isModulus) { // XXX: fragile! fixes _only_ mod, *breaks* div! !
1239       BuildMI(BB, IA64::IUSE, 1).addReg(TmpF13); // hack :(
1240     }
1241
1242     if(!isFP) {
1243       // round to an integer
1244       if(isSigned)
1245         BuildMI(BB, IA64::FCVTFXTRUNCS1, 1, TmpF15).addReg(TmpF14);
1246       else
1247         BuildMI(BB, IA64::FCVTFXUTRUNCS1, 1, TmpF15).addReg(TmpF14);
1248     } else {
1249       BuildMI(BB, IA64::FMOV, 1, TmpF15).addReg(TmpF14);
1250      // EXERCISE: can you see why TmpF15=TmpF14 does not work here, and
1251      // we really do need the above FMOV? ;)
1252     }
1253
1254     if(!isModulus) {
1255       if(isFP) { // extra worrying about div-by-zero
1256       unsigned bogoResult=MakeReg(MVT::f64);
1257
1258       // we do a 'conditional fmov' (of the correct result, depending
1259       // on how the frcpa predicate turned out)
1260       BuildMI(BB, IA64::PFMOV, 2, bogoResult)
1261         .addReg(TmpF12).addReg(TmpPR2); 
1262       BuildMI(BB, IA64::CFMOV, 2, Result)
1263         .addReg(bogoResult).addReg(TmpF15).addReg(TmpPR);
1264       }
1265       else {
1266         BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(TmpF15);
1267       }
1268     } else { // this is a modulus
1269       if(!isFP) {
1270         // answer = q * (-b) + a
1271         unsigned ModulusResult = MakeReg(MVT::f64);
1272         unsigned TmpF = MakeReg(MVT::f64);
1273         unsigned TmpI = MakeReg(MVT::i64);
1274         
1275         BuildMI(BB, IA64::SUB, 2, TmpI).addReg(IA64::r0).addReg(Tmp2);
1276         BuildMI(BB, IA64::SETFSIG, 1, TmpF).addReg(TmpI);
1277         BuildMI(BB, IA64::XMAL, 3, ModulusResult)
1278           .addReg(TmpF15).addReg(TmpF).addReg(TmpF1);
1279         BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(ModulusResult);
1280       } else { // FP modulus! The horror... the horror....
1281         assert(0 && "sorry, no FP modulus just yet!\n!\n");
1282       }
1283     }
1284
1285     return Result;
1286   }
1287
1288   case ISD::ZERO_EXTEND_INREG: {
1289     Tmp1 = SelectExpr(N.getOperand(0));
1290     MVTSDNode* MVN = dyn_cast<MVTSDNode>(Node);
1291     switch(MVN->getExtraValueType())
1292     {
1293     default:
1294       Node->dump();
1295       assert(0 && "don't know how to zero extend this type");
1296       break;
1297     case MVT::i8: Opc = IA64::ZXT1; break;
1298     case MVT::i16: Opc = IA64::ZXT2; break;
1299     case MVT::i32: Opc = IA64::ZXT4; break;
1300     }
1301     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1302     return Result;
1303   }
1304  
1305   case ISD::SIGN_EXTEND_INREG: {
1306     Tmp1 = SelectExpr(N.getOperand(0));
1307     MVTSDNode* MVN = dyn_cast<MVTSDNode>(Node);
1308     switch(MVN->getExtraValueType())
1309     {
1310     default:
1311       Node->dump();
1312       assert(0 && "don't know how to sign extend this type");
1313       break;
1314     case MVT::i8: Opc = IA64::SXT1; break;
1315     case MVT::i16: Opc = IA64::SXT2; break;
1316     case MVT::i32: Opc = IA64::SXT4; break;
1317     }
1318     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1319     return Result;
1320   }
1321
1322   case ISD::SETCC: {
1323     Tmp1 = SelectExpr(N.getOperand(0));
1324
1325     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
1326       if (MVT::isInteger(SetCC->getOperand(0).getValueType())) {
1327
1328         if(ConstantSDNode *CSDN =
1329              dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1330         // if we are comparing against a constant zero
1331         if(CSDN->getValue()==0)
1332           Tmp2 = IA64::r0; // then we can just compare against r0
1333         else
1334           Tmp2 = SelectExpr(N.getOperand(1));
1335         } else // not comparing against a constant
1336           Tmp2 = SelectExpr(N.getOperand(1));
1337         
1338         switch (SetCC->getCondition()) {
1339         default: assert(0 && "Unknown integer comparison!");
1340         case ISD::SETEQ:
1341           BuildMI(BB, IA64::CMPEQ, 2, Result).addReg(Tmp1).addReg(Tmp2);
1342           break;
1343         case ISD::SETGT:
1344           BuildMI(BB, IA64::CMPGT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1345           break;
1346         case ISD::SETGE:
1347           BuildMI(BB, IA64::CMPGE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1348           break;
1349         case ISD::SETLT:
1350           BuildMI(BB, IA64::CMPLT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1351           break;
1352         case ISD::SETLE:
1353           BuildMI(BB, IA64::CMPLE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1354           break;
1355         case ISD::SETNE:
1356           BuildMI(BB, IA64::CMPNE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1357           break;
1358         case ISD::SETULT:
1359           BuildMI(BB, IA64::CMPLTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1360           break;
1361         case ISD::SETUGT:
1362           BuildMI(BB, IA64::CMPGTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1363           break;
1364         case ISD::SETULE:
1365           BuildMI(BB, IA64::CMPLEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1366           break;
1367         case ISD::SETUGE:
1368           BuildMI(BB, IA64::CMPGEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1369           break;
1370         }
1371       }
1372       else { // if not integer, should be FP. FIXME: what about bools? ;)
1373         assert(SetCC->getOperand(0).getValueType() != MVT::f32 &&
1374             "error: SETCC should have had incoming f32 promoted to f64!\n");
1375
1376         if(ConstantFPSDNode *CFPSDN =
1377              dyn_cast<ConstantFPSDNode>(N.getOperand(1))) {
1378
1379           // if we are comparing against a constant +0.0 or +1.0
1380           if(CFPSDN->isExactlyValue(+0.0))
1381             Tmp2 = IA64::F0; // then we can just compare against f0
1382           else if(CFPSDN->isExactlyValue(+1.0))
1383             Tmp2 = IA64::F1; // or f1
1384           else
1385             Tmp2 = SelectExpr(N.getOperand(1));
1386         } else // not comparing against a constant
1387           Tmp2 = SelectExpr(N.getOperand(1));
1388
1389         switch (SetCC->getCondition()) {
1390         default: assert(0 && "Unknown FP comparison!");
1391         case ISD::SETEQ:
1392           BuildMI(BB, IA64::FCMPEQ, 2, Result).addReg(Tmp1).addReg(Tmp2);
1393           break;
1394         case ISD::SETGT:
1395           BuildMI(BB, IA64::FCMPGT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1396           break;
1397         case ISD::SETGE:
1398           BuildMI(BB, IA64::FCMPGE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1399           break;
1400         case ISD::SETLT:
1401           BuildMI(BB, IA64::FCMPLT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1402           break;
1403         case ISD::SETLE:
1404           BuildMI(BB, IA64::FCMPLE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1405           break;
1406         case ISD::SETNE:
1407           BuildMI(BB, IA64::FCMPNE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1408           break;
1409         case ISD::SETULT:
1410           BuildMI(BB, IA64::FCMPLTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1411           break;
1412         case ISD::SETUGT:
1413           BuildMI(BB, IA64::FCMPGTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1414           break;
1415         case ISD::SETULE:
1416           BuildMI(BB, IA64::FCMPLEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1417           break;
1418         case ISD::SETUGE:
1419           BuildMI(BB, IA64::FCMPGEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1420           break;
1421         }
1422       }
1423     }
1424     else
1425       assert(0 && "this setcc not implemented yet");
1426
1427     return Result;
1428   }
1429
1430   case ISD::EXTLOAD:
1431   case ISD::ZEXTLOAD:
1432   case ISD::LOAD: {
1433     // Make sure we generate both values.
1434     if (Result != 1)
1435       ExprMap[N.getValue(1)] = 1;   // Generate the token
1436     else
1437       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1438
1439     bool isBool=false;
1440     
1441     if(opcode == ISD::LOAD) { // this is a LOAD
1442       switch (Node->getValueType(0)) {
1443         default: assert(0 && "Cannot load this type!");
1444         case MVT::i1:  Opc = IA64::LD1; isBool=true; break;
1445               // FIXME: for now, we treat bool loads the same as i8 loads */
1446         case MVT::i8:  Opc = IA64::LD1; break;
1447         case MVT::i16: Opc = IA64::LD2; break;
1448         case MVT::i32: Opc = IA64::LD4; break;
1449         case MVT::i64: Opc = IA64::LD8; break;
1450                        
1451         case MVT::f32: Opc = IA64::LDF4; break;
1452         case MVT::f64: Opc = IA64::LDF8; break;
1453       }
1454     } else { // this is an EXTLOAD or ZEXTLOAD
1455       MVT::ValueType TypeBeingLoaded = cast<MVTSDNode>(Node)->getExtraValueType();
1456       switch (TypeBeingLoaded) {
1457         default: assert(0 && "Cannot extload/zextload this type!");
1458         // FIXME: bools?
1459         case MVT::i8: Opc = IA64::LD1; break;
1460         case MVT::i16: Opc = IA64::LD2; break;
1461         case MVT::i32: Opc = IA64::LD4; break;
1462         case MVT::f32: Opc = IA64::LDF4; break;
1463       }
1464     }
1465     
1466     SDOperand Chain = N.getOperand(0);
1467     SDOperand Address = N.getOperand(1);
1468
1469     if(Address.getOpcode() == ISD::GlobalAddress) {
1470       Select(Chain);
1471       unsigned dummy = MakeReg(MVT::i64);
1472       unsigned dummy2 = MakeReg(MVT::i64);
1473       BuildMI(BB, IA64::ADD, 2, dummy)
1474         .addGlobalAddress(cast<GlobalAddressSDNode>(Address)->getGlobal())
1475         .addReg(IA64::r1);
1476       BuildMI(BB, IA64::LD8, 1, dummy2).addReg(dummy);
1477       if(!isBool)
1478         BuildMI(BB, Opc, 1, Result).addReg(dummy2);
1479       else { // emit a little pseudocode to load a bool (stored in one byte)
1480              // into a predicate register
1481         assert(Opc==IA64::LD1 && "problem loading a bool");
1482         unsigned dummy3 = MakeReg(MVT::i64);
1483         BuildMI(BB, Opc, 1, dummy3).addReg(dummy2);
1484         // we compare to 0. true? 0. false? 1.
1485         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
1486       }
1487     } else if(ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
1488       Select(Chain);
1489       IA64Lowering.restoreGP(BB);
1490       unsigned dummy = MakeReg(MVT::i64);
1491       BuildMI(BB, IA64::ADD, 2, dummy).addConstantPoolIndex(CP->getIndex())
1492         .addReg(IA64::r1); // CPI+GP
1493       if(!isBool)
1494         BuildMI(BB, Opc, 1, Result).addReg(dummy);
1495       else { // emit a little pseudocode to load a bool (stored in one byte)
1496              // into a predicate register
1497         assert(Opc==IA64::LD1 && "problem loading a bool");
1498         unsigned dummy3 = MakeReg(MVT::i64);
1499         BuildMI(BB, Opc, 1, dummy3).addReg(dummy);
1500         // we compare to 0. true? 0. false? 1.
1501         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
1502       }
1503     } else if(Address.getOpcode() == ISD::FrameIndex) {
1504       Select(Chain);  // FIXME ? what about bools?
1505       unsigned dummy = MakeReg(MVT::i64);
1506       BuildMI(BB, IA64::MOV, 1, dummy)
1507         .addFrameIndex(cast<FrameIndexSDNode>(Address)->getIndex());
1508       if(!isBool)
1509         BuildMI(BB, Opc, 1, Result).addReg(dummy);
1510       else { // emit a little pseudocode to load a bool (stored in one byte)
1511              // into a predicate register
1512         assert(Opc==IA64::LD1 && "problem loading a bool");
1513         unsigned dummy3 = MakeReg(MVT::i64);
1514         BuildMI(BB, Opc, 1, dummy3).addReg(dummy);
1515         // we compare to 0. true? 0. false? 1.
1516         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
1517       }
1518     } else { // none of the above... 
1519       Select(Chain);
1520       Tmp2 = SelectExpr(Address);
1521       if(!isBool)
1522         BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
1523       else { // emit a little pseudocode to load a bool (stored in one byte)
1524              // into a predicate register
1525         assert(Opc==IA64::LD1 && "problem loading a bool");
1526         unsigned dummy = MakeReg(MVT::i64);
1527         BuildMI(BB, Opc, 1, dummy).addReg(Tmp2);
1528         // we compare to 0. true? 0. false? 1.
1529         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy).addReg(IA64::r0);
1530       } 
1531     }
1532
1533     return Result;
1534   }
1535   
1536   case ISD::CopyFromReg: {
1537     if (Result == 1)
1538         Result = ExprMap[N.getValue(0)] = 
1539           MakeReg(N.getValue(0).getValueType());
1540                                                                                 
1541       SDOperand Chain   = N.getOperand(0);
1542
1543       Select(Chain);
1544       unsigned r = dyn_cast<RegSDNode>(Node)->getReg();
1545
1546       if(N.getValueType() == MVT::i1) // if a bool, we use pseudocode
1547         BuildMI(BB, IA64::PCMPEQUNC, 3, Result)
1548           .addReg(IA64::r0).addReg(IA64::r0).addReg(r);
1549                             // (r) Result =cmp.eq.unc(r0,r0)
1550       else
1551         BuildMI(BB, IA64::MOV, 1, Result).addReg(r); // otherwise MOV
1552       return Result;
1553   }
1554
1555   case ISD::CALL: {
1556       Select(N.getOperand(0));
1557
1558       // The chain for this call is now lowered.
1559       ExprMap.insert(std::make_pair(N.getValue(Node->getNumValues()-1), 1));
1560       
1561       //grab the arguments
1562       std::vector<unsigned> argvregs;
1563
1564       for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
1565         argvregs.push_back(SelectExpr(N.getOperand(i)));
1566       
1567       // see section 8.5.8 of "Itanium Software Conventions and 
1568       // Runtime Architecture Guide to see some examples of what's going
1569       // on here. (in short: int args get mapped 1:1 'slot-wise' to out0->out7,
1570       // while FP args get mapped to F8->F15 as needed)
1571
1572       unsigned used_FPArgs=0; // how many FP Args have been used so far?
1573       
1574       // in reg args
1575       for(int i = 0, e = std::min(8, (int)argvregs.size()); i < e; ++i)
1576       {
1577         unsigned intArgs[] = {IA64::out0, IA64::out1, IA64::out2, IA64::out3, 
1578                               IA64::out4, IA64::out5, IA64::out6, IA64::out7 };
1579         unsigned FPArgs[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
1580                              IA64::F12, IA64::F13, IA64::F14, IA64::F15 };
1581
1582         switch(N.getOperand(i+2).getValueType())
1583         {
1584           default:  // XXX do we need to support MVT::i1 here?
1585             Node->dump();
1586             N.getOperand(i).Val->dump();
1587             std::cerr << "Type for " << i << " is: " << 
1588               N.getOperand(i+2).getValueType() << std::endl;
1589             assert(0 && "Unknown value type for call");
1590           case MVT::i64:
1591             BuildMI(BB, IA64::MOV, 1, intArgs[i]).addReg(argvregs[i]);
1592             break;
1593           case MVT::f64:
1594             BuildMI(BB, IA64::FMOV, 1, FPArgs[used_FPArgs++])
1595               .addReg(argvregs[i]);
1596             // FIXME: we don't need to do this _all_ the time:
1597             BuildMI(BB, IA64::GETFD, 1, intArgs[i]).addReg(argvregs[i]);
1598             break;
1599           }
1600       }
1601
1602       //in mem args
1603       for (int i = 8, e = argvregs.size(); i < e; ++i)
1604       {
1605         unsigned tempAddr = MakeReg(MVT::i64);
1606         
1607         switch(N.getOperand(i+2).getValueType()) {
1608         default: 
1609           Node->dump(); 
1610           N.getOperand(i).Val->dump();
1611           std::cerr << "Type for " << i << " is: " << 
1612             N.getOperand(i+2).getValueType() << "\n";
1613           assert(0 && "Unknown value type for call");
1614         case MVT::i1: // FIXME?
1615         case MVT::i8:
1616         case MVT::i16:
1617         case MVT::i32:
1618         case MVT::i64:
1619           BuildMI(BB, IA64::ADDIMM22, 2, tempAddr)
1620             .addReg(IA64::r12).addImm(16 + (i - 8) * 8); // r12 is SP
1621           BuildMI(BB, IA64::ST8, 2).addReg(tempAddr).addReg(argvregs[i]);
1622           break;
1623         case MVT::f32:
1624         case MVT::f64:
1625           BuildMI(BB, IA64::ADDIMM22, 2, tempAddr)
1626             .addReg(IA64::r12).addImm(16 + (i - 8) * 8); // r12 is SP
1627           BuildMI(BB, IA64::STF8, 2).addReg(tempAddr).addReg(argvregs[i]);
1628           break;
1629         }
1630       }
1631
1632       /*  XXX we want to re-enable direct branches! crippling them now
1633        *  to stress-test indirect branches.: 
1634     //build the right kind of call
1635     if (GlobalAddressSDNode *GASD =
1636                dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) 
1637       {
1638         BuildMI(BB, IA64::BRCALL, 1).addGlobalAddress(GASD->getGlobal(),true);
1639         IA64Lowering.restoreGP_SP_RP(BB);
1640       }
1641              ^^^^^^^^^^^^^ we want this code one day XXX */ 
1642     if (ExternalSymbolSDNode *ESSDN =
1643              dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) 
1644       { // FIXME : currently need this case for correctness, to avoid
1645         // "non-pic code with imm relocation against dynamic symbol" errors
1646         BuildMI(BB, IA64::BRCALL, 1)
1647           .addExternalSymbol(ESSDN->getSymbol(), true);
1648         IA64Lowering.restoreGP_SP_RP(BB);
1649       }
1650     else {
1651       Tmp1 = SelectExpr(N.getOperand(1));
1652
1653       unsigned targetEntryPoint=MakeReg(MVT::i64);
1654       unsigned targetGPAddr=MakeReg(MVT::i64);
1655       unsigned currentGP=MakeReg(MVT::i64);
1656       
1657       // b6 is a scratch branch register, we load the target entry point
1658       // from the base of the function descriptor
1659       BuildMI(BB, IA64::LD8, 1, targetEntryPoint).addReg(Tmp1);
1660       BuildMI(BB, IA64::MOV, 1, IA64::B6).addReg(targetEntryPoint);
1661
1662       // save the current GP:
1663       BuildMI(BB, IA64::MOV, 1, currentGP).addReg(IA64::r1);
1664      
1665       /* TODO: we need to make sure doing this never, ever loads a
1666        * bogus value into r1 (GP). */
1667       // load the target GP (which is at mem[functiondescriptor+8])
1668       BuildMI(BB, IA64::ADDIMM22, 2, targetGPAddr)
1669         .addReg(Tmp1).addImm(8); // FIXME: addimm22? why not postincrement ld
1670       BuildMI(BB, IA64::LD8, 1, IA64::r1).addReg(targetGPAddr);
1671
1672       // and then jump: (well, call)
1673       BuildMI(BB, IA64::BRCALL, 1).addReg(IA64::B6);
1674       // and finally restore the old GP
1675       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(currentGP);
1676       IA64Lowering.restoreSP_RP(BB);
1677     }
1678
1679     switch (Node->getValueType(0)) {
1680     default: assert(0 && "Unknown value type for call result!");
1681     case MVT::Other: return 1;
1682     case MVT::i1:
1683       BuildMI(BB, IA64::CMPNE, 2, Result)
1684         .addReg(IA64::r8).addReg(IA64::r0);
1685       break;
1686     case MVT::i8:
1687     case MVT::i16:
1688     case MVT::i32:
1689     case MVT::i64:
1690       BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r8);
1691       break;
1692     case MVT::f64:
1693       BuildMI(BB, IA64::FMOV, 1, Result).addReg(IA64::F8);
1694       break;
1695     }
1696     return Result+N.ResNo;
1697   }
1698
1699   } // <- uhhh XXX 
1700   return 0;
1701 }
1702
1703 void ISel::Select(SDOperand N) {
1704   unsigned Tmp1, Tmp2, Opc;
1705   unsigned opcode = N.getOpcode();
1706
1707   if (!LoweredTokens.insert(N).second)
1708     return;  // Already selected.
1709
1710   SDNode *Node = N.Val;
1711
1712   switch (Node->getOpcode()) {
1713   default:
1714     Node->dump(); std::cerr << "\n";
1715     assert(0 && "Node not handled yet!");
1716
1717   case ISD::EntryToken: return;  // Noop
1718   
1719   case ISD::TokenFactor: {
1720     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1721       Select(Node->getOperand(i));
1722     return;
1723   }
1724
1725   case ISD::CopyToReg: {
1726     Select(N.getOperand(0));
1727     Tmp1 = SelectExpr(N.getOperand(1));   
1728     Tmp2 = cast<RegSDNode>(N)->getReg();
1729     
1730     if (Tmp1 != Tmp2) {
1731       if(N.getValueType() == MVT::i1) // if a bool, we use pseudocode
1732         BuildMI(BB, IA64::PCMPEQUNC, 3, Tmp2)
1733           .addReg(IA64::r0).addReg(IA64::r0).addReg(Tmp1);
1734                                    // (Tmp1) Tmp2 = cmp.eq.unc(r0,r0)
1735       else
1736         BuildMI(BB, IA64::MOV, 1, Tmp2).addReg(Tmp1);
1737                       // XXX is this the right way 'round? ;)
1738     }
1739     return;
1740   }
1741   
1742   case ISD::RET: {
1743
1744   /* what the heck is going on here:
1745
1746 <_sabre_> ret with two operands is obvious: chain and value
1747 <camel_> yep
1748 <_sabre_> ret with 3 values happens when 'expansion' occurs
1749 <_sabre_> e.g. i64 gets split into 2x i32
1750 <camel_> oh right
1751 <_sabre_> you don't have this case on ia64
1752 <camel_> yep
1753 <_sabre_> so the two returned values go into EAX/EDX on ia32
1754 <camel_> ahhh *memories*
1755 <_sabre_> :)
1756 <camel_> ok, thanks :)
1757 <_sabre_> so yeah, everything that has a side effect takes a 'token chain'
1758 <_sabre_> this is the first operand always
1759 <_sabre_> these operand often define chains, they are the last operand
1760 <_sabre_> they are printed as 'ch' if you do DAG.dump()
1761   */
1762   
1763     switch (N.getNumOperands()) {
1764     default:
1765       assert(0 && "Unknown return instruction!");
1766     case 2:
1767         Select(N.getOperand(0));
1768         Tmp1 = SelectExpr(N.getOperand(1));
1769       switch (N.getOperand(1).getValueType()) {
1770       default: assert(0 && "All other types should have been promoted!!");
1771                // FIXME: do I need to add support for bools here?
1772                // (return '0' or '1' r8, basically...)
1773       case MVT::i64:
1774         BuildMI(BB, IA64::MOV, 1, IA64::r8).addReg(Tmp1);
1775         break;
1776       case MVT::f64:
1777         BuildMI(BB, IA64::FMOV, 1, IA64::F8).addReg(Tmp1);
1778       }
1779       break;
1780     case 1:
1781       Select(N.getOperand(0));
1782       break;
1783     }
1784     // before returning, restore the ar.pfs register (set by the 'alloc' up top)
1785     BuildMI(BB, IA64::MOV, 1).addReg(IA64::AR_PFS).addReg(IA64Lowering.VirtGPR);
1786     BuildMI(BB, IA64::RET, 0); // and then just emit a 'ret' instruction
1787     return;
1788   }
1789   
1790   case ISD::BR: {
1791     Select(N.getOperand(0));
1792     MachineBasicBlock *Dest =
1793       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
1794     BuildMI(BB, IA64::BRLCOND_NOTCALL, 1).addReg(IA64::p0).addMBB(Dest);
1795     // XXX HACK! we do _not_ need long branches all the time
1796     return;
1797   }
1798
1799   case ISD::ImplicitDef: {
1800     Select(N.getOperand(0));
1801     BuildMI(BB, IA64::IDEF, 0, cast<RegSDNode>(N)->getReg());
1802     return;
1803   }
1804
1805   case ISD::BRCOND: {
1806     MachineBasicBlock *Dest =
1807       cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
1808
1809     Select(N.getOperand(0));
1810     Tmp1 = SelectExpr(N.getOperand(1));
1811     BuildMI(BB, IA64::BRLCOND_NOTCALL, 1).addReg(Tmp1).addMBB(Dest);
1812     // XXX HACK! we do _not_ need long branches all the time
1813     return;
1814   }
1815   
1816   case ISD::EXTLOAD:
1817   case ISD::ZEXTLOAD:
1818   case ISD::SEXTLOAD:
1819   case ISD::LOAD:
1820   case ISD::CALL:
1821   case ISD::CopyFromReg:
1822   case ISD::DYNAMIC_STACKALLOC:
1823     SelectExpr(N);
1824     return;
1825
1826   case ISD::TRUNCSTORE:
1827   case ISD::STORE: {
1828       Select(N.getOperand(0));
1829       Tmp1 = SelectExpr(N.getOperand(1)); // value
1830
1831       bool isBool=false;
1832      
1833       if(opcode == ISD::STORE) {
1834         switch (N.getOperand(1).getValueType()) {
1835           default: assert(0 && "Cannot store this type!");
1836           case MVT::i1:  Opc = IA64::ST1; isBool=true; break;
1837               // FIXME?: for now, we treat bool loads the same as i8 stores */
1838           case MVT::i8:  Opc = IA64::ST1; break;
1839           case MVT::i16: Opc = IA64::ST2; break;
1840           case MVT::i32: Opc = IA64::ST4; break;
1841           case MVT::i64: Opc = IA64::ST8; break;
1842                          
1843           case MVT::f32: Opc = IA64::STF4; break;
1844           case MVT::f64: Opc = IA64::STF8; break;
1845         }
1846       } else { // truncstore
1847         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1848           default: assert(0 && "unknown type in truncstore");
1849           case MVT::i1: Opc = IA64::ST1; isBool=true; break;
1850                         //FIXME: DAG does not promote this load?
1851           case MVT::i8: Opc = IA64::ST1; break;
1852           case MVT::i16: Opc = IA64::ST2; break;
1853           case MVT::i32: Opc = IA64::ST4; break;
1854           case MVT::f32: Opc = IA64::STF4; break; 
1855         }
1856       }
1857
1858       if(N.getOperand(2).getOpcode() == ISD::GlobalAddress) {
1859         unsigned dummy = MakeReg(MVT::i64);
1860         unsigned dummy2 = MakeReg(MVT::i64);
1861         BuildMI(BB, IA64::ADD, 2, dummy)
1862           .addGlobalAddress(cast<GlobalAddressSDNode>
1863               (N.getOperand(2))->getGlobal()).addReg(IA64::r1);
1864         BuildMI(BB, IA64::LD8, 1, dummy2).addReg(dummy);
1865       
1866         if(!isBool)
1867           BuildMI(BB, Opc, 2).addReg(dummy2).addReg(Tmp1);
1868         else { // we are storing a bool, so emit a little pseudocode
1869                // to store a predicate register as one byte
1870           assert(Opc==IA64::ST1);
1871           unsigned dummy3 = MakeReg(MVT::i64);
1872           unsigned dummy4 = MakeReg(MVT::i64);
1873           BuildMI(BB, IA64::MOV, 1, dummy3).addReg(IA64::r0);
1874           BuildMI(BB, IA64::TPCADDIMM22, 2, dummy4)
1875             .addReg(dummy3).addImm(1).addReg(Tmp1); // if(Tmp1) dummy=0+1;
1876           BuildMI(BB, Opc, 2).addReg(dummy2).addReg(dummy4);
1877         }
1878       } else if(N.getOperand(2).getOpcode() == ISD::FrameIndex) {
1879
1880         // FIXME? (what about bools?)
1881         
1882         unsigned dummy = MakeReg(MVT::i64);
1883         BuildMI(BB, IA64::MOV, 1, dummy)
1884           .addFrameIndex(cast<FrameIndexSDNode>(N.getOperand(2))->getIndex());
1885         BuildMI(BB, Opc, 2).addReg(dummy).addReg(Tmp1);
1886       } else { // otherwise
1887         Tmp2 = SelectExpr(N.getOperand(2)); //address
1888         if(!isBool) 
1889           BuildMI(BB, Opc, 2).addReg(Tmp2).addReg(Tmp1);
1890         else { // we are storing a bool, so emit a little pseudocode
1891                // to store a predicate register as one byte
1892           assert(Opc==IA64::ST1);
1893           unsigned dummy3 = MakeReg(MVT::i64);
1894           unsigned dummy4 = MakeReg(MVT::i64);
1895           BuildMI(BB, IA64::MOV, 1, dummy3).addReg(IA64::r0);
1896           BuildMI(BB, IA64::TPCADDIMM22, 2, dummy4)
1897             .addReg(dummy3).addImm(1).addReg(Tmp1); // if(Tmp1) dummy=0+1;
1898           BuildMI(BB, Opc, 2).addReg(Tmp2).addReg(dummy4);
1899         }
1900       }
1901     return;
1902   }
1903   
1904   case ISD::ADJCALLSTACKDOWN:
1905   case ISD::ADJCALLSTACKUP: {
1906     Select(N.getOperand(0));
1907     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
1908    
1909     Opc = N.getOpcode() == ISD::ADJCALLSTACKDOWN ? IA64::ADJUSTCALLSTACKDOWN :
1910                                                    IA64::ADJUSTCALLSTACKUP;
1911     BuildMI(BB, Opc, 1).addImm(Tmp1);
1912     return;
1913   }
1914
1915     return;
1916   }
1917   assert(0 && "GAME OVER. INSERT COIN?");
1918 }
1919
1920
1921 /// createIA64PatternInstructionSelector - This pass converts an LLVM function
1922 /// into a machine code representation using pattern matching and a machine
1923 /// description file.
1924 ///
1925 FunctionPass *llvm::createIA64PatternInstructionSelector(TargetMachine &TM) {
1926   return new ISel(TM);  
1927 }
1928
1929