re-enable direct calls, this should just be a performance boost
[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 <map>
32 #include <algorithm>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //  IA64TargetLowering - IA64 Implementation of the TargetLowering interface
37 namespace {
38   class IA64TargetLowering : public TargetLowering {
39     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
40
41     //int ReturnAddrIndex;              // FrameIndex for return slot.
42     unsigned GP, SP, RP; // FIXME - clean this mess up
43   public:
44
45    unsigned VirtGPR; // this is public so it can be accessed in the selector
46    // for ISD::RET down below. add an accessor instead? FIXME
47
48    IA64TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
49
50       // register class for general registers
51       addRegisterClass(MVT::i64, IA64::GRRegisterClass);
52
53       // register class for FP registers
54       addRegisterClass(MVT::f64, IA64::FPRegisterClass);
55
56       // register class for predicate registers
57       addRegisterClass(MVT::i1, IA64::PRRegisterClass);
58
59       setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
60       setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
61
62       setSetCCResultType(MVT::i1);
63       setShiftAmountType(MVT::i64);
64
65       setOperationAction(ISD::EXTLOAD          , MVT::i1   , Promote);
66
67       setOperationAction(ISD::ZEXTLOAD         , MVT::i1   , Expand);
68
69       setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
70       setOperationAction(ISD::SEXTLOAD         , MVT::i8   , Expand);
71       setOperationAction(ISD::SEXTLOAD         , MVT::i16  , Expand);
72       setOperationAction(ISD::SEXTLOAD         , MVT::i32  , 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       // We don't support sin/cos/sqrt
85       setOperationAction(ISD::FSIN , MVT::f64, Expand);
86       setOperationAction(ISD::FCOS , MVT::f64, Expand);
87       setOperationAction(ISD::FSQRT, MVT::f64, Expand);
88       setOperationAction(ISD::FSIN , MVT::f32, Expand);
89       setOperationAction(ISD::FCOS , MVT::f32, Expand);
90       setOperationAction(ISD::FSQRT, MVT::f32, Expand);
91
92       //IA64 has these, but they are not implemented
93       setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
94       setOperationAction(ISD::CTLZ , MVT::i64  , Expand);
95
96       computeRegisterProperties();
97
98       addLegalFPImmediate(+0.0);
99       addLegalFPImmediate(+1.0);
100       addLegalFPImmediate(-0.0);
101       addLegalFPImmediate(-1.0);
102     }
103
104     /// LowerArguments - This hook must be implemented to indicate how we should
105     /// lower the arguments for the specified function, into the specified DAG.
106     virtual std::vector<SDOperand>
107     LowerArguments(Function &F, SelectionDAG &DAG);
108
109     /// LowerCallTo - This hook lowers an abstract call to a function into an
110     /// actual call.
111     virtual std::pair<SDOperand, SDOperand>
112     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
113                 bool isTailCall, SDOperand Callee, ArgListTy &Args,
114                 SelectionDAG &DAG);
115
116     virtual std::pair<SDOperand, SDOperand>
117     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
118
119     virtual std::pair<SDOperand,SDOperand>
120     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
121                    const Type *ArgTy, SelectionDAG &DAG);
122
123     virtual std::pair<SDOperand, SDOperand>
124     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
125                             SelectionDAG &DAG);
126
127     void restoreGP_SP_RP(MachineBasicBlock* BB)
128     {
129       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(GP);
130       BuildMI(BB, IA64::MOV, 1, IA64::r12).addReg(SP);
131       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
132     }
133
134     void restoreSP_RP(MachineBasicBlock* BB)
135     {
136       BuildMI(BB, IA64::MOV, 1, IA64::r12).addReg(SP);
137       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
138     }
139
140     void restoreRP(MachineBasicBlock* BB)
141     {
142       BuildMI(BB, IA64::MOV, 1, IA64::rp).addReg(RP);
143     }
144
145     void restoreGP(MachineBasicBlock* BB)
146     {
147       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(GP);
148     }
149
150   };
151 }
152
153
154 std::vector<SDOperand>
155 IA64TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
156   std::vector<SDOperand> ArgValues;
157
158   //
159   // add beautiful description of IA64 stack frame format
160   // here (from intel 24535803.pdf most likely)
161   //
162   MachineFunction &MF = DAG.getMachineFunction();
163   MachineFrameInfo *MFI = MF.getFrameInfo();
164
165   GP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
166   SP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
167   RP = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
168
169   MachineBasicBlock& BB = MF.front();
170
171   unsigned args_int[] = {IA64::r32, IA64::r33, IA64::r34, IA64::r35,
172                          IA64::r36, IA64::r37, IA64::r38, IA64::r39};
173
174   unsigned args_FP[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
175                         IA64::F12,IA64::F13,IA64::F14, IA64::F15};
176
177   unsigned argVreg[8];
178   unsigned argPreg[8];
179   unsigned argOpc[8];
180
181   unsigned used_FPArgs = 0; // how many FP args have been used so far?
182
183   unsigned ArgOffset = 0;
184   int count = 0;
185
186   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
187     {
188       SDOperand newroot, argt;
189       if(count < 8) { // need to fix this logic? maybe.
190
191         switch (getValueType(I->getType())) {
192           default:
193             std::cerr << "ERROR in LowerArgs: unknown type "
194               << getValueType(I->getType()) << "\n";
195             abort();
196           case MVT::f32:
197             // fixme? (well, will need to for weird FP structy stuff,
198             // see intel ABI docs)
199           case MVT::f64:
200 //XXX            BuildMI(&BB, IA64::IDEF, 0, args_FP[used_FPArgs]);
201             MF.addLiveIn(args_FP[used_FPArgs]); // mark this reg as liveIn
202             // floating point args go into f8..f15 as-needed, the increment
203             argVreg[count] =                              // is below..:
204             MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::f64));
205             // FP args go into f8..f15 as needed: (hence the ++)
206             argPreg[count] = args_FP[used_FPArgs++];
207             argOpc[count] = IA64::FMOV;
208             argt = newroot = DAG.getCopyFromReg(argVreg[count],
209                 getValueType(I->getType()), DAG.getRoot());
210             break;
211           case MVT::i1: // NOTE: as far as C abi stuff goes,
212                         // bools are just boring old ints
213           case MVT::i8:
214           case MVT::i16:
215           case MVT::i32:
216           case MVT::i64:
217 //XXX            BuildMI(&BB, IA64::IDEF, 0, args_int[count]);
218             MF.addLiveIn(args_int[count]); // mark this register as liveIn
219             argVreg[count] =
220             MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
221             argPreg[count] = args_int[count];
222             argOpc[count] = IA64::MOV;
223             argt = newroot =
224               DAG.getCopyFromReg(argVreg[count], MVT::i64, DAG.getRoot());
225             if ( getValueType(I->getType()) != MVT::i64)
226               argt = DAG.getNode(ISD::TRUNCATE, getValueType(I->getType()),
227                   newroot);
228             break;
229         }
230       } else { // more than 8 args go into the frame
231         // Create the frame index object for this incoming parameter...
232         ArgOffset = 16 + 8 * (count - 8);
233         int FI = MFI->CreateFixedObject(8, ArgOffset);
234         
235         // Create the SelectionDAG nodes corresponding to a load
236         //from this parameter
237         SDOperand FIN = DAG.getFrameIndex(FI, MVT::i64);
238         argt = newroot = DAG.getLoad(getValueType(I->getType()),
239                                      DAG.getEntryNode(), FIN, DAG.getSrcValue(NULL));
240       }
241       ++count;
242       DAG.setRoot(newroot.getValue(1));
243       ArgValues.push_back(argt);
244     }
245
246
247   // Create a vreg to hold the output of (what will become)
248   // the "alloc" instruction
249   VirtGPR = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i64));
250   BuildMI(&BB, IA64::PSEUDO_ALLOC, 0, VirtGPR);
251   // we create a PSEUDO_ALLOC (pseudo)instruction for now
252
253   BuildMI(&BB, IA64::IDEF, 0, IA64::r1);
254
255   // hmm:
256   BuildMI(&BB, IA64::IDEF, 0, IA64::r12);
257   BuildMI(&BB, IA64::IDEF, 0, IA64::rp);
258   // ..hmm.
259
260   BuildMI(&BB, IA64::MOV, 1, GP).addReg(IA64::r1);
261
262   // hmm:
263   BuildMI(&BB, IA64::MOV, 1, SP).addReg(IA64::r12);
264   BuildMI(&BB, IA64::MOV, 1, RP).addReg(IA64::rp);
265   // ..hmm.
266
267   unsigned tempOffset=0;
268
269   // if this is a varargs function, we simply lower llvm.va_start by
270   // pointing to the first entry
271   if(F.isVarArg()) {
272     tempOffset=0;
273     VarArgsFrameIndex = MFI->CreateFixedObject(8, tempOffset);
274   }
275
276   // here we actually do the moving of args, and store them to the stack
277   // too if this is a varargs function:
278   for (int i = 0; i < count && i < 8; ++i) {
279     BuildMI(&BB, argOpc[i], 1, argVreg[i]).addReg(argPreg[i]);
280     if(F.isVarArg()) {
281       // if this is a varargs function, we copy the input registers to the stack
282       int FI = MFI->CreateFixedObject(8, tempOffset);
283       tempOffset+=8;   //XXX: is it safe to use r22 like this?
284       BuildMI(&BB, IA64::MOV, 1, IA64::r22).addFrameIndex(FI);
285       // FIXME: we should use st8.spill here, one day
286       BuildMI(&BB, IA64::ST8, 1, IA64::r22).addReg(argPreg[i]);
287     }
288   }
289
290   // Finally, inform the code generator which regs we return values in.
291   // (see the ISD::RET: case down below)
292   switch (getValueType(F.getReturnType())) {
293   default: assert(0 && "i have no idea where to return this type!");
294   case MVT::isVoid: break;
295   case MVT::i1:
296   case MVT::i8:
297   case MVT::i16:
298   case MVT::i32:
299   case MVT::i64:
300     MF.addLiveOut(IA64::r8);
301     break;
302   case MVT::f32:
303   case MVT::f64:
304     MF.addLiveOut(IA64::F8);
305     break;
306   }
307
308   return ArgValues;
309 }
310
311 std::pair<SDOperand, SDOperand>
312 IA64TargetLowering::LowerCallTo(SDOperand Chain,
313                                 const Type *RetTy, bool isVarArg,
314                                 unsigned CallingConv, bool isTailCall,
315                                 SDOperand Callee, ArgListTy &Args, 
316                                 SelectionDAG &DAG) {
317
318   MachineFunction &MF = DAG.getMachineFunction();
319
320   unsigned NumBytes = 16;
321   unsigned outRegsUsed = 0;
322
323   if (Args.size() > 8) {
324     NumBytes += (Args.size() - 8) * 8;
325     outRegsUsed = 8;
326   } else {
327     outRegsUsed = Args.size();
328   }
329
330   // FIXME? this WILL fail if we ever try to pass around an arg that
331   // consumes more than a single output slot (a 'real' double, int128
332   // some sort of aggregate etc.), as we'll underestimate how many 'outX'
333   // registers we use. Hopefully, the assembler will notice.
334   MF.getInfo<IA64FunctionInfo>()->outRegsUsed=
335     std::max(outRegsUsed, MF.getInfo<IA64FunctionInfo>()->outRegsUsed);
336
337   Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
338                         DAG.getConstant(NumBytes, getPointerTy()));
339
340   std::vector<SDOperand> args_to_use;
341   for (unsigned i = 0, e = Args.size(); i != e; ++i)
342     {
343       switch (getValueType(Args[i].second)) {
344       default: assert(0 && "unexpected argument type!");
345       case MVT::i1:
346       case MVT::i8:
347       case MVT::i16:
348       case MVT::i32:
349         //promote to 64-bits, sign/zero extending based on type
350         //of the argument
351         if(Args[i].second->isSigned())
352           Args[i].first = DAG.getNode(ISD::SIGN_EXTEND, MVT::i64,
353               Args[i].first);
354         else
355           Args[i].first = DAG.getNode(ISD::ZERO_EXTEND, MVT::i64,
356               Args[i].first);
357         break;
358       case MVT::f32:
359         //promote to 64-bits
360         Args[i].first = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Args[i].first);
361       case MVT::f64:
362       case MVT::i64:
363         break;
364       }
365       args_to_use.push_back(Args[i].first);
366     }
367
368   std::vector<MVT::ValueType> RetVals;
369   MVT::ValueType RetTyVT = getValueType(RetTy);
370   if (RetTyVT != MVT::isVoid)
371     RetVals.push_back(RetTyVT);
372   RetVals.push_back(MVT::Other);
373
374   SDOperand TheCall = SDOperand(DAG.getCall(RetVals, Chain,
375                                             Callee, args_to_use), 0);
376   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
377   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
378                       DAG.getConstant(NumBytes, getPointerTy()));
379   return std::make_pair(TheCall, Chain);
380 }
381
382 std::pair<SDOperand, SDOperand>
383 IA64TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
384   // vastart just returns the address of the VarArgsFrameIndex slot.
385   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i64), Chain);
386 }
387
388 std::pair<SDOperand,SDOperand> IA64TargetLowering::
389 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
390                const Type *ArgTy, SelectionDAG &DAG) {
391
392   MVT::ValueType ArgVT = getValueType(ArgTy);
393   SDOperand Result;
394   if (!isVANext) {
395     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList, DAG.getSrcValue(NULL));
396   } else {
397     unsigned Amt;
398     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
399       Amt = 8;
400     else {
401       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
402              "Other types should have been promoted for varargs!");
403       Amt = 8;
404     }
405     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
406                          DAG.getConstant(Amt, VAList.getValueType()));
407   }
408   return std::make_pair(Result, Chain);
409 }
410
411 std::pair<SDOperand, SDOperand> IA64TargetLowering::
412 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
413                         SelectionDAG &DAG) {
414
415   assert(0 && "LowerFrameReturnAddress not done yet\n");
416   abort();
417 }
418
419
420 namespace {
421
422   //===--------------------------------------------------------------------===//
423   /// ISel - IA64 specific code to select IA64 machine instructions for
424   /// SelectionDAG operations.
425   ///
426   class ISel : public SelectionDAGISel {
427     /// IA64Lowering - This object fully describes how to lower LLVM code to an
428     /// IA64-specific SelectionDAG.
429     IA64TargetLowering IA64Lowering;
430     SelectionDAG *ISelDAG; // Hack to support us having a dag->dag transform
431                            // for sdiv and udiv until it is put into the future
432                            // dag combiner
433
434     /// ExprMap - As shared expressions are codegen'd, we keep track of which
435     /// vreg the value is produced in, so we only emit one copy of each compiled
436     /// tree.
437     std::map<SDOperand, unsigned> ExprMap;
438     std::set<SDOperand> LoweredTokens;
439
440   public:
441     ISel(TargetMachine &TM) : SelectionDAGISel(IA64Lowering), IA64Lowering(TM),
442                               ISelDAG(0) { }
443
444     /// InstructionSelectBasicBlock - This callback is invoked by
445     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
446     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
447
448     unsigned SelectExpr(SDOperand N);
449     void Select(SDOperand N);
450     // a dag->dag to transform mul-by-constant-int to shifts+adds/subs
451     SDOperand BuildConstmulSequence(SDOperand N);
452
453   };
454 }
455
456 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
457 /// when it has created a SelectionDAG for us to codegen.
458 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
459
460   // Codegen the basic block.
461   ISelDAG = &DAG;
462   Select(DAG.getRoot());
463
464   // Clear state used for selection.
465   ExprMap.clear();
466   LoweredTokens.clear();
467   ISelDAG = 0;
468 }
469
470 // strip leading '0' characters from a string
471 void munchLeadingZeros(std::string& inString) {
472   while(inString.c_str()[0]=='0') {
473     inString.erase(0, 1);
474   }
475 }
476
477 // strip trailing '0' characters from a string
478 void munchTrailingZeros(std::string& inString) {
479   int curPos=inString.length()-1;
480
481   while(inString.c_str()[curPos]=='0') {
482     inString.erase(curPos, 1);
483     curPos--;
484   }
485 }
486
487 // return how many consecutive '0' characters are at the end of a string
488 unsigned int countTrailingZeros(std::string& inString) {
489   int curPos=inString.length()-1;
490   unsigned int zeroCount=0;
491   // assert goes here
492   while(inString.c_str()[curPos--]=='0') {
493     zeroCount++;
494   }
495   return zeroCount;
496 }
497
498 // booth encode a string of '1' and '0' characters (returns string of 'P' (+1)
499 // '0' and 'N' (-1) characters)
500 void boothEncode(std::string inString, std::string& boothEncodedString) {
501
502   int curpos=0;
503   int replacements=0;
504   int lim=inString.size();
505
506   while(curpos<lim) {
507     if(inString[curpos]=='1') { // if we see a '1', look for a run of them 
508       int runlength=0;
509       std::string replaceString="N";
510      
511       // find the run length
512       for(;inString[curpos+runlength]=='1';runlength++) ;
513
514       for(int i=0; i<runlength-1; i++)
515         replaceString+="0";
516       replaceString+="1";
517
518       if(runlength>1) {
519         inString.replace(curpos, runlength+1, replaceString);
520         curpos+=runlength-1;
521       } else
522         curpos++;
523     } else { // a zero, we just keep chugging along
524       curpos++;
525     }
526   }
527
528   // clean up (trim the string, reverse it and turn '1's into 'P's)
529   munchTrailingZeros(inString);
530   boothEncodedString="";
531
532   for(int i=inString.size()-1;i>=0;i--)
533     if(inString[i]=='1')
534       boothEncodedString+="P";
535     else
536       boothEncodedString+=inString[i];
537
538 }
539
540 struct shiftaddblob { // this encodes stuff like (x=) "A << B [+-] C << D"
541   unsigned firstVal;    // A
542   unsigned firstShift;  // B 
543   unsigned secondVal;   // C
544   unsigned secondShift; // D
545   bool isSub;
546 };
547
548 /* this implements Lefevre's "pattern-based" constant multiplication,
549  * see "Multiplication by an Integer Constant", INRIA report 1999-06
550  *
551  * TODO: implement a method to try rewriting P0N<->0PP / N0P<->0NN
552  * to get better booth encodings - this does help in practice
553  * TODO: weight shifts appropriately (most architectures can't
554  * fuse a shift and an add for arbitrary shift amounts) */
555 unsigned lefevre(const std::string inString,
556                  std::vector<struct shiftaddblob> &ops) {
557   std::string retstring;
558   std::string s = inString;
559   munchTrailingZeros(s);
560
561   int length=s.length()-1;
562
563   if(length==0) {
564     return(0);
565   }
566
567   std::vector<int> p,n;
568   
569   for(int i=0; i<=length; i++) {
570     if (s.c_str()[length-i]=='P') {
571       p.push_back(i);
572     } else if (s.c_str()[length-i]=='N') {
573       n.push_back(i);
574     }
575   }
576
577   std::string t, u;
578   int c;
579   bool f;
580   std::map<const int, int> w;
581
582   for(unsigned i=0; i<p.size(); i++) {
583     for(unsigned j=0; j<i; j++) {
584       w[p[i]-p[j]]++;
585     }
586   }
587
588   for(unsigned i=1; i<n.size(); i++) {
589     for(unsigned j=0; j<i; j++) {
590       w[n[i]-n[j]]++;
591     }
592   }
593
594   for(unsigned i=0; i<p.size(); i++) {
595     for(unsigned j=0; j<n.size(); j++) {
596       w[-abs(p[i]-n[j])]++;
597     }
598   }
599
600   std::map<const int, int>::const_iterator ii;
601   std::vector<int> d;
602   std::multimap<int, int> sorted_by_value;
603
604   for(ii = w.begin(); ii!=w.end(); ii++)
605     sorted_by_value.insert(std::pair<int, int>((*ii).second,(*ii).first));
606
607   for (std::multimap<int, int>::iterator it = sorted_by_value.begin();
608        it != sorted_by_value.end(); ++it) {
609     d.push_back((*it).second);
610   }
611
612   int int_W=0;
613   int int_d;
614
615   while(d.size()>0 && (w[int_d=d.back()] > int_W)) {
616     d.pop_back();
617     retstring=s; // hmmm
618     int x=0;
619     int z=abs(int_d)-1;
620
621     if(int_d>0) {
622       
623       for(unsigned base=0; base<retstring.size(); base++) {
624         if( ((base+z+1) < retstring.size()) &&
625            retstring.c_str()[base]=='P' &&
626            retstring.c_str()[base+z+1]=='P')
627         {
628           // match
629           x++;
630           retstring.replace(base, 1, "0");
631           retstring.replace(base+z+1, 1, "p");
632         }
633       }
634
635       for(unsigned base=0; base<retstring.size(); base++) {
636         if( ((base+z+1) < retstring.size()) &&
637            retstring.c_str()[base]=='N' &&
638            retstring.c_str()[base+z+1]=='N')
639         {
640           // match
641           x++;
642           retstring.replace(base, 1, "0");
643           retstring.replace(base+z+1, 1, "n");
644         }
645       }
646
647     } else {
648       for(unsigned base=0; base<retstring.size(); base++) {
649         if( ((base+z+1) < retstring.size()) &&
650             ((retstring.c_str()[base]=='P' &&
651              retstring.c_str()[base+z+1]=='N') ||
652             (retstring.c_str()[base]=='N' &&
653              retstring.c_str()[base+z+1]=='P')) ) {
654           // match
655           x++;
656           
657           if(retstring.c_str()[base]=='P') {
658             retstring.replace(base, 1, "0");
659             retstring.replace(base+z+1, 1, "p");
660           } else { // retstring[base]=='N'
661             retstring.replace(base, 1, "0");
662             retstring.replace(base+z+1, 1, "n");
663           }
664         }
665       }
666     }
667
668     if(x>int_W) {
669       int_W = x;
670       t = retstring;
671       c = int_d; // tofix
672     }
673     
674   } d.pop_back(); // hmm
675
676   u = t;
677   
678   for(unsigned i=0; i<t.length(); i++) {
679     if(t.c_str()[i]=='p' || t.c_str()[i]=='n')
680       t.replace(i, 1, "0");
681   }
682
683   for(unsigned i=0; i<u.length(); i++) {
684     if(u[i]=='P' || u[i]=='N')
685       u.replace(i, 1, "0");
686     if(u[i]=='p')
687       u.replace(i, 1, "P");
688     if(u[i]=='n')
689       u.replace(i, 1, "N");
690   }
691
692   if( c<0 ) {
693     f=true;
694     c=-c;
695   } else
696     f=false;
697   
698   int pos=0;
699   while(u[pos]=='0')
700     pos++;
701
702   bool hit=(u[pos]=='N');
703
704   int g=0;
705   if(hit) {
706     g=1;
707     for(unsigned p=0; p<u.length(); p++) {
708       bool isP=(u[p]=='P');
709       bool isN=(u[p]=='N');
710
711       if(isP)
712         u.replace(p, 1, "N");
713       if(isN)
714         u.replace(p, 1, "P");
715     }
716   }
717
718   munchLeadingZeros(u);
719
720   int i = lefevre(u, ops);
721
722   shiftaddblob blob;
723   
724   blob.firstVal=i; blob.firstShift=c;
725   blob.isSub=f;
726   blob.secondVal=i; blob.secondShift=0;
727
728   ops.push_back(blob);
729
730   i = ops.size();
731
732   munchLeadingZeros(t);
733
734   if(t.length()==0)
735     return i;
736
737   if(t.c_str()[0]!='P') {
738     g=2;
739     for(unsigned p=0; p<t.length(); p++) {
740       bool isP=(t.c_str()[p]=='P');
741       bool isN=(t.c_str()[p]=='N');
742
743       if(isP)
744         t.replace(p, 1, "N");
745       if(isN)
746         t.replace(p, 1, "P");
747     }
748   }
749
750   int j = lefevre(t, ops);
751
752   int trail=countTrailingZeros(u);
753   blob.secondVal=i; blob.secondShift=trail;
754
755   trail=countTrailingZeros(t);
756   blob.firstVal=j; blob.firstShift=trail;
757
758   switch(g) {
759     case 0:
760       blob.isSub=false; // first + second
761       break;
762     case 1:
763       blob.isSub=true; // first - second
764       break;
765     case 2:
766       blob.isSub=true; // second - first
767       int tmpval, tmpshift;
768       tmpval=blob.firstVal;
769       tmpshift=blob.firstShift;
770       blob.firstVal=blob.secondVal;
771       blob.firstShift=blob.secondShift;
772       blob.secondVal=tmpval;
773       blob.secondShift=tmpshift;
774       break;
775       //assert
776   }
777  
778   ops.push_back(blob);
779   return ops.size();
780 }
781
782 SDOperand ISel::BuildConstmulSequence(SDOperand N) {
783   //FIXME: we should shortcut this stuff for multiplies by 2^n+1
784   //       in particular, *3 is nicer as *2+1, not *4-1
785   int64_t constant=cast<ConstantSDNode>(N.getOperand(1))->getValue();
786
787   bool flippedSign;
788   unsigned preliminaryShift=0;
789
790   assert(constant != 0 && "erk, you're trying to multiply by constant zero\n");
791
792   // first, we make the constant to multiply by positive
793   if(constant<0) {
794     constant=-constant;
795     flippedSign=true;
796   } else {
797     flippedSign=false;
798   }
799
800   // next, we make it odd.
801   for(; (constant%2==0); preliminaryShift++)
802     constant>>=1;
803
804   //OK, we have a positive, odd number of 64 bits or less. Convert it
805   //to a binary string, constantString[0] is the LSB
806   char constantString[65];
807   for(int i=0; i<64; i++)
808     constantString[i]='0'+((constant>>i)&0x1);
809   constantString[64]=0;
810
811   // now, Booth encode it
812   std::string boothEncodedString;
813   boothEncode(constantString, boothEncodedString);
814
815   std::vector<struct shiftaddblob> ops;
816   // do the transformation, filling out 'ops'
817   lefevre(boothEncodedString, ops);
818
819   assert(ops.size() < 80 && "constmul code has gone haywire\n");
820   SDOperand results[80]; // temporary results (of adds/subs of shifts)
821   
822   // now turn 'ops' into DAG bits
823   for(unsigned i=0; i<ops.size(); i++) {
824     SDOperand amt = ISelDAG->getConstant(ops[i].firstShift, MVT::i64);
825     SDOperand val = (ops[i].firstVal == 0) ? N.getOperand(0) :
826       results[ops[i].firstVal-1];
827     SDOperand left = ISelDAG->getNode(ISD::SHL, MVT::i64, val, amt);
828     amt = ISelDAG->getConstant(ops[i].secondShift, MVT::i64);
829     val = (ops[i].secondVal == 0) ? N.getOperand(0) :
830       results[ops[i].secondVal-1];
831     SDOperand right = ISelDAG->getNode(ISD::SHL, MVT::i64, val, amt);
832     if(ops[i].isSub)
833       results[i] = ISelDAG->getNode(ISD::SUB, MVT::i64, left, right);
834     else
835       results[i] = ISelDAG->getNode(ISD::ADD, MVT::i64, left, right);
836   }
837
838   // don't forget flippedSign and preliminaryShift!
839   SDOperand shiftedresult;
840   if(preliminaryShift) {
841     SDOperand finalshift = ISelDAG->getConstant(preliminaryShift, MVT::i64);
842     shiftedresult = ISelDAG->getNode(ISD::SHL, MVT::i64,
843         results[ops.size()-1], finalshift);
844   } else { // there was no preliminary divide-by-power-of-2 required
845     shiftedresult = results[ops.size()-1];
846   }
847  
848   SDOperand finalresult;
849   if(flippedSign) { // if we were multiplying by a negative constant:
850     SDOperand zero = ISelDAG->getConstant(0, MVT::i64);
851     // subtract the result from 0 to flip its sign
852     finalresult = ISelDAG->getNode(ISD::SUB, MVT::i64, zero, shiftedresult);
853   } else { // there was no preliminary multiply by -1 required
854     finalresult = shiftedresult;
855   }
856   
857   return finalresult; 
858 }
859
860 /// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
861 /// returns zero when the input is not exactly a power of two.
862 static unsigned ExactLog2(uint64_t Val) {
863   if (Val == 0 || (Val & (Val-1))) return 0;
864   unsigned Count = 0;
865   while (Val != 1) {
866     Val >>= 1;
867     ++Count;
868   }
869   return Count;
870 }
871
872 /// ExactLog2sub1 - This function solves for (Val == (1 << (N-1))-1)
873 /// and returns N.  It returns 666 if Val is not 2^n -1 for some n.
874 static unsigned ExactLog2sub1(uint64_t Val) {
875   unsigned int n;
876   for(n=0; n<64; n++) {
877     if(Val==(uint64_t)((1LL<<n)-1))
878       return n;
879   }
880   return 666;
881 }
882
883 /// ponderIntegerDivisionBy - When handling integer divides, if the divide
884 /// is by a constant such that we can efficiently codegen it, this
885 /// function says what to do. Currently, it returns 0 if the division must
886 /// become a genuine divide, and 1 if the division can be turned into a
887 /// right shift.
888 static unsigned ponderIntegerDivisionBy(SDOperand N, bool isSigned,
889                                       unsigned& Imm) {
890   if (N.getOpcode() != ISD::Constant) return 0; // if not a divide by
891                                                 // a constant, give up.
892
893   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
894
895   if ((Imm = ExactLog2(v))) { // if a division by a power of two, say so
896     return 1;
897   }
898
899   return 0; // fallthrough
900 }
901
902 static unsigned ponderIntegerAndWith(SDOperand N, unsigned& Imm) {
903   if (N.getOpcode() != ISD::Constant) return 0; // if not ANDing with
904                                                 // a constant, give up.
905
906   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
907
908   if ((Imm = ExactLog2sub1(v))!=666) { // if ANDing with ((2^n)-1) for some n
909     return 1; // say so
910   }
911
912   return 0; // fallthrough
913 }
914
915 static unsigned ponderIntegerAdditionWith(SDOperand N, unsigned& Imm) {
916   if (N.getOpcode() != ISD::Constant) return 0; // if not adding a
917                                                 // constant, give up.
918   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
919
920   if (v <= 8191 && v >= -8192) { // if this constants fits in 14 bits, say so
921     Imm = v & 0x3FFF; // 14 bits
922     return 1;
923   }
924   return 0; // fallthrough
925 }
926
927 static unsigned ponderIntegerSubtractionFrom(SDOperand N, unsigned& Imm) {
928   if (N.getOpcode() != ISD::Constant) return 0; // if not subtracting a
929                                                 // constant, give up.
930   int64_t v = (int64_t)cast<ConstantSDNode>(N)->getSignExtended();
931
932   if (v <= 127 && v >= -128) { // if this constants fits in 8 bits, say so
933     Imm = v & 0xFF; // 8 bits
934     return 1;
935   }
936   return 0; // fallthrough
937 }
938
939 unsigned ISel::SelectExpr(SDOperand N) {
940   unsigned Result;
941   unsigned Tmp1, Tmp2, Tmp3;
942   unsigned Opc = 0;
943   MVT::ValueType DestType = N.getValueType();
944
945   unsigned opcode = N.getOpcode();
946
947   SDNode *Node = N.Val;
948   SDOperand Op0, Op1;
949
950   if (Node->getOpcode() == ISD::CopyFromReg)
951     // Just use the specified register as our input.
952     return dyn_cast<RegSDNode>(Node)->getReg();
953
954   unsigned &Reg = ExprMap[N];
955   if (Reg) return Reg;
956
957   if (N.getOpcode() != ISD::CALL && N.getOpcode() != ISD::TAILCALL)
958     Reg = Result = (N.getValueType() != MVT::Other) ?
959       MakeReg(N.getValueType()) : 1;
960   else {
961     // If this is a call instruction, make sure to prepare ALL of the result
962     // values as well as the chain.
963     if (Node->getNumValues() == 1)
964       Reg = Result = 1;  // Void call, just a chain.
965     else {
966       Result = MakeReg(Node->getValueType(0));
967       ExprMap[N.getValue(0)] = Result;
968       for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
969         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
970       ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
971     }
972   }
973
974   switch (N.getOpcode()) {
975   default:
976     Node->dump();
977     assert(0 && "Node not handled!\n");
978
979   case ISD::FrameIndex: {
980     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
981     BuildMI(BB, IA64::MOV, 1, Result).addFrameIndex(Tmp1);
982     return Result;
983   }
984
985   case ISD::ConstantPool: {
986     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
987     IA64Lowering.restoreGP(BB); // FIXME: do i really need this?
988     BuildMI(BB, IA64::ADD, 2, Result).addConstantPoolIndex(Tmp1)
989       .addReg(IA64::r1);
990     return Result;
991   }
992
993   case ISD::ConstantFP: {
994     Tmp1 = Result;   // Intermediate Register
995     if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
996         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
997       Tmp1 = MakeReg(MVT::f64);
998
999     if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
1000         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
1001       BuildMI(BB, IA64::FMOV, 1, Tmp1).addReg(IA64::F0); // load 0.0
1002     else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
1003              cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
1004       BuildMI(BB, IA64::FMOV, 1, Tmp1).addReg(IA64::F1); // load 1.0
1005     else
1006       assert(0 && "Unexpected FP constant!");
1007     if (Tmp1 != Result)
1008       // we multiply by +1.0, negate (this is FNMA), and then add 0.0
1009       BuildMI(BB, IA64::FNMA, 3, Result).addReg(Tmp1).addReg(IA64::F1)
1010         .addReg(IA64::F0);
1011     return Result;
1012   }
1013
1014   case ISD::DYNAMIC_STACKALLOC: {
1015     // Generate both result values.
1016     if (Result != 1)
1017       ExprMap[N.getValue(1)] = 1;   // Generate the token
1018     else
1019       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1020
1021     // FIXME: We are currently ignoring the requested alignment for handling
1022     // greater than the stack alignment.  This will need to be revisited at some
1023     // point.  Align = N.getOperand(2);
1024
1025     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
1026         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
1027       std::cerr << "Cannot allocate stack object with greater alignment than"
1028                 << " the stack alignment yet!";
1029       abort();
1030     }
1031
1032 /*
1033     Select(N.getOperand(0));
1034     if (ConstantSDNode* CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1035     {
1036       if (CN->getValue() < 32000)
1037       {
1038         BuildMI(BB, IA64::ADDIMM22, 2, IA64::r12).addReg(IA64::r12)
1039           .addImm(-CN->getValue());
1040       } else {
1041         Tmp1 = SelectExpr(N.getOperand(1));
1042         // Subtract size from stack pointer, thereby allocating some space.
1043         BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
1044       }
1045     } else {
1046       Tmp1 = SelectExpr(N.getOperand(1));
1047       // Subtract size from stack pointer, thereby allocating some space.
1048       BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
1049     }
1050 */
1051     Select(N.getOperand(0));
1052     Tmp1 = SelectExpr(N.getOperand(1));
1053     // Subtract size from stack pointer, thereby allocating some space.
1054     BuildMI(BB, IA64::SUB, 2, IA64::r12).addReg(IA64::r12).addReg(Tmp1);
1055     // Put a pointer to the space into the result register, by copying the
1056     // stack pointer.
1057     BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r12);
1058     return Result;
1059   }
1060
1061   case ISD::SELECT: {
1062       Tmp1 = SelectExpr(N.getOperand(0)); //Cond
1063       Tmp2 = SelectExpr(N.getOperand(1)); //Use if TRUE
1064       Tmp3 = SelectExpr(N.getOperand(2)); //Use if FALSE
1065
1066       unsigned bogoResult;
1067
1068       switch (N.getOperand(1).getValueType()) {
1069         default: assert(0 &&
1070         "ISD::SELECT: 'select'ing something other than i1, i64 or f64!\n");
1071         // for i1, we load the condition into an integer register, then
1072         // conditionally copy Tmp2 and Tmp3 to Tmp1 in parallel (only one
1073         // of them will go through, since the integer register will hold
1074         // either 0 or 1)
1075         case MVT::i1: {
1076           bogoResult=MakeReg(MVT::i1);
1077
1078           // load the condition into an integer register
1079           unsigned condReg=MakeReg(MVT::i64);
1080           unsigned dummy=MakeReg(MVT::i64);
1081           BuildMI(BB, IA64::MOV, 1, dummy).addReg(IA64::r0);
1082           BuildMI(BB, IA64::TPCADDIMM22, 2, condReg).addReg(dummy)
1083             .addImm(1).addReg(Tmp1);
1084
1085           // initialize Result (bool) to false (hence UNC) and if
1086           // the select condition (condReg) is false (0), copy Tmp3
1087           BuildMI(BB, IA64::PCMPEQUNC, 3, bogoResult)
1088             .addReg(condReg).addReg(IA64::r0).addReg(Tmp3);
1089
1090           // now, if the selection condition is true, write 1 to the
1091           // result if Tmp2 is 1
1092           BuildMI(BB, IA64::TPCMPNE, 3, Result).addReg(bogoResult)
1093             .addReg(condReg).addReg(IA64::r0).addReg(Tmp2);
1094           break;
1095         }
1096         // for i64/f64, we just copy Tmp3 and then conditionally overwrite it
1097         // with Tmp2 if Tmp1 is true
1098         case MVT::i64:
1099           bogoResult=MakeReg(MVT::i64);
1100           BuildMI(BB, IA64::MOV, 1, bogoResult).addReg(Tmp3);
1101           BuildMI(BB, IA64::CMOV, 2, Result).addReg(bogoResult).addReg(Tmp2)
1102             .addReg(Tmp1);
1103           break;
1104         case MVT::f64:
1105           bogoResult=MakeReg(MVT::f64);
1106           BuildMI(BB, IA64::FMOV, 1, bogoResult).addReg(Tmp3);
1107           BuildMI(BB, IA64::CFMOV, 2, Result).addReg(bogoResult).addReg(Tmp2)
1108             .addReg(Tmp1);
1109           break;
1110       }
1111       
1112       return Result;
1113   }
1114
1115   case ISD::Constant: {
1116     unsigned depositPos=0;
1117     unsigned depositLen=0;
1118     switch (N.getValueType()) {
1119       default: assert(0 && "Cannot use constants of this type!");
1120       case MVT::i1: { // if a bool, we don't 'load' so much as generate
1121         // the constant:
1122         if(cast<ConstantSDNode>(N)->getValue())  // true:
1123           BuildMI(BB, IA64::CMPEQ, 2, Result).addReg(IA64::r0).addReg(IA64::r0);
1124         else // false:
1125           BuildMI(BB, IA64::CMPNE, 2, Result).addReg(IA64::r0).addReg(IA64::r0);
1126         return Result; // early exit
1127       }
1128       case MVT::i64: break;
1129     }
1130
1131     int64_t immediate = cast<ConstantSDNode>(N)->getValue();
1132
1133     if(immediate==0) { // if the constant is just zero,
1134       BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r0); // just copy r0
1135       return Result; // early exit
1136     }
1137
1138     if (immediate <= 8191 && immediate >= -8192) {
1139       // if this constants fits in 14 bits, we use a mov the assembler will
1140       // turn into:   "adds rDest=imm,r0"  (and _not_ "andl"...)
1141       BuildMI(BB, IA64::MOVSIMM14, 1, Result).addSImm(immediate);
1142       return Result; // early exit
1143     }
1144
1145     if (immediate <= 2097151 && immediate >= -2097152) {
1146       // if this constants fits in 22 bits, we use a mov the assembler will
1147       // turn into:   "addl rDest=imm,r0"
1148       BuildMI(BB, IA64::MOVSIMM22, 1, Result).addSImm(immediate);
1149       return Result; // early exit
1150     }
1151
1152     /* otherwise, our immediate is big, so we use movl */
1153     uint64_t Imm = immediate;
1154     BuildMI(BB, IA64::MOVLIMM64, 1, Result).addImm64(Imm);
1155     return Result;
1156   }
1157
1158   case ISD::UNDEF: {
1159     BuildMI(BB, IA64::IDEF, 0, Result);
1160     return Result;
1161   }
1162
1163   case ISD::GlobalAddress: {
1164     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1165     unsigned Tmp1 = MakeReg(MVT::i64);
1166
1167     BuildMI(BB, IA64::ADD, 2, Tmp1).addGlobalAddress(GV).addReg(IA64::r1);
1168     BuildMI(BB, IA64::LD8, 1, Result).addReg(Tmp1);
1169
1170     return Result;
1171   }
1172
1173   case ISD::ExternalSymbol: {
1174     const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
1175 // assert(0 && "sorry, but what did you want an ExternalSymbol for again?");
1176     BuildMI(BB, IA64::MOV, 1, Result).addExternalSymbol(Sym); // XXX
1177     return Result;
1178   }
1179
1180   case ISD::FP_EXTEND: {
1181     Tmp1 = SelectExpr(N.getOperand(0));
1182     BuildMI(BB, IA64::FMOV, 1, Result).addReg(Tmp1);
1183     return Result;
1184   }
1185
1186   case ISD::ZERO_EXTEND: {
1187     Tmp1 = SelectExpr(N.getOperand(0)); // value
1188
1189     switch (N.getOperand(0).getValueType()) {
1190     default: assert(0 && "Cannot zero-extend this type!");
1191     case MVT::i8:  Opc = IA64::ZXT1; break;
1192     case MVT::i16: Opc = IA64::ZXT2; break;
1193     case MVT::i32: Opc = IA64::ZXT4; break;
1194
1195     // we handle bools differently! :
1196     case MVT::i1: { // if the predicate reg has 1, we want a '1' in our GR.
1197       unsigned dummy = MakeReg(MVT::i64);
1198       // first load zero:
1199       BuildMI(BB, IA64::MOV, 1, dummy).addReg(IA64::r0);
1200       // ...then conditionally (PR:Tmp1) add 1:
1201       BuildMI(BB, IA64::TPCADDIMM22, 2, Result).addReg(dummy)
1202         .addImm(1).addReg(Tmp1);
1203       return Result; // XXX early exit!
1204     }
1205     }
1206
1207     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1208     return Result;
1209    }
1210
1211   case ISD::SIGN_EXTEND: {   // we should only have to handle i1 -> i64 here!!!
1212
1213 assert(0 && "hmm, ISD::SIGN_EXTEND: shouldn't ever be reached. bad luck!\n");
1214
1215     Tmp1 = SelectExpr(N.getOperand(0)); // value
1216
1217     switch (N.getOperand(0).getValueType()) {
1218     default: assert(0 && "Cannot sign-extend this type!");
1219     case MVT::i1:  assert(0 && "trying to sign extend a bool? ow.\n");
1220       Opc = IA64::SXT1; break;
1221       // FIXME: for now, we treat bools the same as i8s
1222     case MVT::i8:  Opc = IA64::SXT1; break;
1223     case MVT::i16: Opc = IA64::SXT2; break;
1224     case MVT::i32: Opc = IA64::SXT4; break;
1225     }
1226
1227     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1228     return Result;
1229    }
1230
1231   case ISD::TRUNCATE: {
1232     // we use the funky dep.z (deposit (zero)) instruction to deposit bits
1233     // of R0 appropriately.
1234     switch (N.getOperand(0).getValueType()) {
1235     default: assert(0 && "Unknown truncate!");
1236     case MVT::i64: break;
1237     }
1238     Tmp1 = SelectExpr(N.getOperand(0));
1239     unsigned depositPos, depositLen;
1240
1241     switch (N.getValueType()) {
1242     default: assert(0 && "Unknown truncate!");
1243     case MVT::i1: {
1244       // if input (normal reg) is 0, 0!=0 -> false (0), if 1, 1!=0 ->true (1):
1245         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(Tmp1)
1246           .addReg(IA64::r0);
1247         return Result; // XXX early exit!
1248       }
1249     case MVT::i8:  depositPos=0; depositLen=8;  break;
1250     case MVT::i16: depositPos=0; depositLen=16; break;
1251     case MVT::i32: depositPos=0; depositLen=32; break;
1252     }
1253     BuildMI(BB, IA64::DEPZ, 1, Result).addReg(Tmp1)
1254       .addImm(depositPos).addImm(depositLen);
1255     return Result;
1256   }
1257
1258 /*
1259   case ISD::FP_ROUND: {
1260     assert (DestType == MVT::f32 && N.getOperand(0).getValueType() == MVT::f64 &&
1261   "error: trying to FP_ROUND something other than f64 -> f32!\n");
1262     Tmp1 = SelectExpr(N.getOperand(0));
1263     BuildMI(BB, IA64::FADDS, 2, Result).addReg(Tmp1).addReg(IA64::F0);
1264     // we add 0.0 using a single precision add to do rounding
1265     return Result;
1266   }
1267 */
1268
1269 // FIXME: the following 4 cases need cleaning
1270   case ISD::SINT_TO_FP: {
1271     Tmp1 = SelectExpr(N.getOperand(0));
1272     Tmp2 = MakeReg(MVT::f64);
1273     unsigned dummy = MakeReg(MVT::f64);
1274     BuildMI(BB, IA64::SETFSIG, 1, Tmp2).addReg(Tmp1);
1275     BuildMI(BB, IA64::FCVTXF, 1, dummy).addReg(Tmp2);
1276     BuildMI(BB, IA64::FNORMD, 1, Result).addReg(dummy);
1277     return Result;
1278   }
1279
1280   case ISD::UINT_TO_FP: {
1281     Tmp1 = SelectExpr(N.getOperand(0));
1282     Tmp2 = MakeReg(MVT::f64);
1283     unsigned dummy = MakeReg(MVT::f64);
1284     BuildMI(BB, IA64::SETFSIG, 1, Tmp2).addReg(Tmp1);
1285     BuildMI(BB, IA64::FCVTXUF, 1, dummy).addReg(Tmp2);
1286     BuildMI(BB, IA64::FNORMD, 1, Result).addReg(dummy);
1287     return Result;
1288   }
1289
1290   case ISD::FP_TO_SINT: {
1291     Tmp1 = SelectExpr(N.getOperand(0));
1292     Tmp2 = MakeReg(MVT::f64);
1293     BuildMI(BB, IA64::FCVTFXTRUNC, 1, Tmp2).addReg(Tmp1);
1294     BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(Tmp2);
1295     return Result;
1296   }
1297
1298   case ISD::FP_TO_UINT: {
1299     Tmp1 = SelectExpr(N.getOperand(0));
1300     Tmp2 = MakeReg(MVT::f64);
1301     BuildMI(BB, IA64::FCVTFXUTRUNC, 1, Tmp2).addReg(Tmp1);
1302     BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(Tmp2);
1303     return Result;
1304   }
1305
1306   case ISD::ADD: {
1307     if(DestType == MVT::f64 && N.getOperand(0).getOpcode() == ISD::MUL &&
1308        N.getOperand(0).Val->hasOneUse()) { // if we can fold this add
1309                                            // into an fma, do so:
1310       // ++FusedFP; // Statistic
1311       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1312       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1313       Tmp3 = SelectExpr(N.getOperand(1));
1314       BuildMI(BB, IA64::FMA, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1315       return Result; // early exit
1316     }
1317
1318     if(DestType != MVT::f64 && N.getOperand(0).getOpcode() == ISD::SHL &&
1319         N.getOperand(0).Val->hasOneUse()) { // if we might be able to fold
1320                                             // this add into a shladd, try:
1321       ConstantSDNode *CSD = NULL;
1322       if((CSD = dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) &&
1323           (CSD->getValue() >= 1) && (CSD->getValue() <= 4) ) { // we can:
1324
1325         // ++FusedSHLADD; // Statistic
1326         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1327         int shl_amt = CSD->getValue();
1328         Tmp3 = SelectExpr(N.getOperand(1));
1329         
1330         BuildMI(BB, IA64::SHLADD, 3, Result)
1331           .addReg(Tmp1).addImm(shl_amt).addReg(Tmp3);
1332         return Result; // early exit
1333       }
1334     }
1335
1336     //else, fallthrough:
1337     Tmp1 = SelectExpr(N.getOperand(0));
1338     if(DestType != MVT::f64) { // integer addition:
1339         switch (ponderIntegerAdditionWith(N.getOperand(1), Tmp3)) {
1340           case 1: // adding a constant that's 14 bits
1341             BuildMI(BB, IA64::ADDIMM14, 2, Result).addReg(Tmp1).addSImm(Tmp3);
1342             return Result; // early exit
1343         } // fallthrough and emit a reg+reg ADD:
1344         Tmp2 = SelectExpr(N.getOperand(1));
1345         BuildMI(BB, IA64::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1346     } else { // this is a floating point addition
1347       Tmp2 = SelectExpr(N.getOperand(1));
1348       BuildMI(BB, IA64::FADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1349     }
1350     return Result;
1351   }
1352
1353   case ISD::MUL: {
1354
1355     if(DestType != MVT::f64) { // TODO: speed!
1356       if(N.getOperand(1).getOpcode() != ISD::Constant) { // if not a const mul
1357         // boring old integer multiply with xma
1358         Tmp1 = SelectExpr(N.getOperand(0));
1359         Tmp2 = SelectExpr(N.getOperand(1));
1360
1361         unsigned TempFR1=MakeReg(MVT::f64);
1362         unsigned TempFR2=MakeReg(MVT::f64);
1363         unsigned TempFR3=MakeReg(MVT::f64);
1364         BuildMI(BB, IA64::SETFSIG, 1, TempFR1).addReg(Tmp1);
1365         BuildMI(BB, IA64::SETFSIG, 1, TempFR2).addReg(Tmp2);
1366         BuildMI(BB, IA64::XMAL, 1, TempFR3).addReg(TempFR1).addReg(TempFR2)
1367           .addReg(IA64::F0);
1368         BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(TempFR3);
1369         return Result; // early exit
1370       } else { // we are multiplying by an integer constant! yay
1371         return Reg = SelectExpr(BuildConstmulSequence(N)); // avert your eyes!
1372       }
1373     }
1374     else { // floating point multiply
1375       Tmp1 = SelectExpr(N.getOperand(0));
1376       Tmp2 = SelectExpr(N.getOperand(1));
1377       BuildMI(BB, IA64::FMPY, 2, Result).addReg(Tmp1).addReg(Tmp2);
1378       return Result;
1379     }
1380   }
1381
1382   case ISD::SUB: {
1383     if(DestType == MVT::f64 && N.getOperand(0).getOpcode() == ISD::MUL &&
1384        N.getOperand(0).Val->hasOneUse()) { // if we can fold this sub
1385                                            // into an fms, do so:
1386       // ++FusedFP; // Statistic
1387       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1388       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1389       Tmp3 = SelectExpr(N.getOperand(1));
1390       BuildMI(BB, IA64::FMS, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1391       return Result; // early exit
1392     }
1393     Tmp2 = SelectExpr(N.getOperand(1));
1394     if(DestType != MVT::f64) { // integer subtraction:
1395         switch (ponderIntegerSubtractionFrom(N.getOperand(0), Tmp3)) {
1396           case 1: // subtracting *from* an 8 bit constant:
1397             BuildMI(BB, IA64::SUBIMM8, 2, Result).addSImm(Tmp3).addReg(Tmp2);
1398             return Result; // early exit
1399         } // fallthrough and emit a reg+reg SUB:
1400         Tmp1 = SelectExpr(N.getOperand(0));
1401         BuildMI(BB, IA64::SUB, 2, Result).addReg(Tmp1).addReg(Tmp2);
1402     } else { // this is a floating point subtraction
1403       Tmp1 = SelectExpr(N.getOperand(0));
1404       BuildMI(BB, IA64::FSUB, 2, Result).addReg(Tmp1).addReg(Tmp2);
1405     }
1406     return Result;
1407   }
1408
1409   case ISD::FABS: {
1410     Tmp1 = SelectExpr(N.getOperand(0));
1411     assert(DestType == MVT::f64 && "trying to fabs something other than f64?");
1412     BuildMI(BB, IA64::FABS, 1, Result).addReg(Tmp1);
1413     return Result;
1414   }
1415
1416   case ISD::FNEG: {
1417     assert(DestType == MVT::f64 && "trying to fneg something other than f64?");
1418
1419     if (ISD::FABS == N.getOperand(0).getOpcode()) { // && hasOneUse()?
1420       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1421       BuildMI(BB, IA64::FNEGABS, 1, Result).addReg(Tmp1); // fold in abs
1422     } else {
1423       Tmp1 = SelectExpr(N.getOperand(0));
1424       BuildMI(BB, IA64::FNEG, 1, Result).addReg(Tmp1); // plain old fneg
1425     }
1426
1427     return Result;
1428   }
1429
1430   case ISD::AND: {
1431      switch (N.getValueType()) {
1432     default: assert(0 && "Cannot AND this type!");
1433     case MVT::i1: { // if a bool, we emit a pseudocode AND
1434       unsigned pA = SelectExpr(N.getOperand(0));
1435       unsigned pB = SelectExpr(N.getOperand(1));
1436
1437 /* our pseudocode for AND is:
1438  *
1439 (pA) cmp.eq.unc pC,p0 = r0,r0   // pC = pA
1440      cmp.eq pTemp,p0 = r0,r0    // pTemp = NOT pB
1441      ;;
1442 (pB) cmp.ne pTemp,p0 = r0,r0
1443      ;;
1444 (pTemp)cmp.ne pC,p0 = r0,r0    // if (NOT pB) pC = 0
1445
1446 */
1447       unsigned pTemp = MakeReg(MVT::i1);
1448
1449       unsigned bogusTemp1 = MakeReg(MVT::i1);
1450       unsigned bogusTemp2 = MakeReg(MVT::i1);
1451       unsigned bogusTemp3 = MakeReg(MVT::i1);
1452       unsigned bogusTemp4 = MakeReg(MVT::i1);
1453
1454       BuildMI(BB, IA64::PCMPEQUNC, 3, bogusTemp1)
1455         .addReg(IA64::r0).addReg(IA64::r0).addReg(pA);
1456       BuildMI(BB, IA64::CMPEQ, 2, bogusTemp2)
1457         .addReg(IA64::r0).addReg(IA64::r0);
1458       BuildMI(BB, IA64::TPCMPNE, 3, pTemp)
1459         .addReg(bogusTemp2).addReg(IA64::r0).addReg(IA64::r0).addReg(pB);
1460       BuildMI(BB, IA64::TPCMPNE, 3, Result)
1461         .addReg(bogusTemp1).addReg(IA64::r0).addReg(IA64::r0).addReg(pTemp);
1462       break;
1463     }
1464
1465     // if not a bool, we just AND away:
1466     case MVT::i8:
1467     case MVT::i16:
1468     case MVT::i32:
1469     case MVT::i64: {
1470       Tmp1 = SelectExpr(N.getOperand(0));
1471       switch (ponderIntegerAndWith(N.getOperand(1), Tmp3)) {
1472         case 1: // ANDing a constant that is 2^n-1 for some n
1473           switch (Tmp3) {
1474             case 8:  // if AND 0x00000000000000FF, be quaint and use zxt1
1475               BuildMI(BB, IA64::ZXT1, 1, Result).addReg(Tmp1);
1476               break;
1477             case 16: // if AND 0x000000000000FFFF, be quaint and use zxt2
1478               BuildMI(BB, IA64::ZXT2, 1, Result).addReg(Tmp1);
1479               break;
1480             case 32: // if AND 0x00000000FFFFFFFF, be quaint and use zxt4
1481               BuildMI(BB, IA64::ZXT4, 1, Result).addReg(Tmp1);
1482               break;
1483             default: // otherwise, use dep.z to paste zeros
1484               BuildMI(BB, IA64::DEPZ, 3, Result).addReg(Tmp1)
1485                 .addImm(0).addImm(Tmp3);
1486               break;
1487           }
1488           return Result; // early exit
1489       } // fallthrough and emit a simple AND:
1490       Tmp2 = SelectExpr(N.getOperand(1));
1491       BuildMI(BB, IA64::AND, 2, Result).addReg(Tmp1).addReg(Tmp2);
1492     }
1493     }
1494     return Result;
1495   }
1496
1497   case ISD::OR: {
1498   switch (N.getValueType()) {
1499     default: assert(0 && "Cannot OR this type!");
1500     case MVT::i1: { // if a bool, we emit a pseudocode OR
1501       unsigned pA = SelectExpr(N.getOperand(0));
1502       unsigned pB = SelectExpr(N.getOperand(1));
1503
1504       unsigned pTemp1 = MakeReg(MVT::i1);
1505
1506 /* our pseudocode for OR is:
1507  *
1508
1509 pC = pA OR pB
1510 -------------
1511
1512 (pA) cmp.eq.unc pC,p0 = r0,r0  // pC = pA
1513  ;;
1514 (pB) cmp.eq pC,p0 = r0,r0 // if (pB) pC = 1
1515
1516 */
1517       BuildMI(BB, IA64::PCMPEQUNC, 3, pTemp1)
1518         .addReg(IA64::r0).addReg(IA64::r0).addReg(pA);
1519       BuildMI(BB, IA64::TPCMPEQ, 3, Result)
1520         .addReg(pTemp1).addReg(IA64::r0).addReg(IA64::r0).addReg(pB);
1521       break;
1522     }
1523     // if not a bool, we just OR away:
1524     case MVT::i8:
1525     case MVT::i16:
1526     case MVT::i32:
1527     case MVT::i64: {
1528       Tmp1 = SelectExpr(N.getOperand(0));
1529       Tmp2 = SelectExpr(N.getOperand(1));
1530       BuildMI(BB, IA64::OR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1531       break;
1532     }
1533     }
1534     return Result;
1535   }
1536
1537   case ISD::XOR: {
1538      switch (N.getValueType()) {
1539     default: assert(0 && "Cannot XOR this type!");
1540     case MVT::i1: { // if a bool, we emit a pseudocode XOR
1541       unsigned pY = SelectExpr(N.getOperand(0));
1542       unsigned pZ = SelectExpr(N.getOperand(1));
1543
1544 /* one possible routine for XOR is:
1545
1546       // Compute px = py ^ pz
1547         // using sum of products: px = (py & !pz) | (pz & !py)
1548         // Uses 5 instructions in 3 cycles.
1549         // cycle 1
1550 (pz)    cmp.eq.unc      px = r0, r0     // px = pz
1551 (py)    cmp.eq.unc      pt = r0, r0     // pt = py
1552         ;;
1553         // cycle 2
1554 (pt)    cmp.ne.and      px = r0, r0     // px = px & !pt (px = pz & !pt)
1555 (pz)    cmp.ne.and      pt = r0, r0     // pt = pt & !pz
1556         ;;
1557         } { .mmi
1558         // cycle 3
1559 (pt)    cmp.eq.or       px = r0, r0     // px = px | pt
1560
1561 *** Another, which we use here, requires one scratch GR. it is:
1562
1563         mov             rt = 0          // initialize rt off critical path
1564         ;;
1565
1566         // cycle 1
1567 (pz)    cmp.eq.unc      px = r0, r0     // px = pz
1568 (pz)    mov             rt = 1          // rt = pz
1569         ;;
1570         // cycle 2
1571 (py)    cmp.ne          px = 1, rt      // if (py) px = !pz
1572
1573 .. these routines kindly provided by Jim Hull
1574 */
1575       unsigned rt = MakeReg(MVT::i64);
1576
1577       // these two temporaries will never actually appear,
1578       // due to the two-address form of some of the instructions below
1579       unsigned bogoPR = MakeReg(MVT::i1);  // becomes Result
1580       unsigned bogoGR = MakeReg(MVT::i64); // becomes rt
1581
1582       BuildMI(BB, IA64::MOV, 1, bogoGR).addReg(IA64::r0);
1583       BuildMI(BB, IA64::PCMPEQUNC, 3, bogoPR)
1584         .addReg(IA64::r0).addReg(IA64::r0).addReg(pZ);
1585       BuildMI(BB, IA64::TPCADDIMM22, 2, rt)
1586         .addReg(bogoGR).addImm(1).addReg(pZ);
1587       BuildMI(BB, IA64::TPCMPIMM8NE, 3, Result)
1588         .addReg(bogoPR).addImm(1).addReg(rt).addReg(pY);
1589       break;
1590     }
1591     // if not a bool, we just XOR away:
1592     case MVT::i8:
1593     case MVT::i16:
1594     case MVT::i32:
1595     case MVT::i64: {
1596       Tmp1 = SelectExpr(N.getOperand(0));
1597       Tmp2 = SelectExpr(N.getOperand(1));
1598       BuildMI(BB, IA64::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1599       break;
1600     }
1601     }
1602     return Result;
1603   }
1604
1605   case ISD::CTPOP: {
1606     Tmp1 = SelectExpr(N.getOperand(0));
1607     BuildMI(BB, IA64::POPCNT, 1, Result).addReg(Tmp1);
1608     return Result;
1609   }
1610
1611   case ISD::SHL: {
1612     Tmp1 = SelectExpr(N.getOperand(0));
1613     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1614       Tmp2 = CN->getValue();
1615       BuildMI(BB, IA64::SHLI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1616     } else {
1617       Tmp2 = SelectExpr(N.getOperand(1));
1618       BuildMI(BB, IA64::SHL, 2, Result).addReg(Tmp1).addReg(Tmp2);
1619     }
1620     return Result;
1621   }
1622
1623   case ISD::SRL: {
1624     Tmp1 = SelectExpr(N.getOperand(0));
1625     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1626       Tmp2 = CN->getValue();
1627       BuildMI(BB, IA64::SHRUI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1628     } else {
1629       Tmp2 = SelectExpr(N.getOperand(1));
1630       BuildMI(BB, IA64::SHRU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1631     }
1632     return Result;
1633   }
1634
1635   case ISD::SRA: {
1636     Tmp1 = SelectExpr(N.getOperand(0));
1637     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1638       Tmp2 = CN->getValue();
1639       BuildMI(BB, IA64::SHRSI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1640     } else {
1641       Tmp2 = SelectExpr(N.getOperand(1));
1642       BuildMI(BB, IA64::SHRS, 2, Result).addReg(Tmp1).addReg(Tmp2);
1643     }
1644     return Result;
1645   }
1646
1647   case ISD::SDIV:
1648   case ISD::UDIV:
1649   case ISD::SREM:
1650   case ISD::UREM: {
1651
1652     Tmp1 = SelectExpr(N.getOperand(0));
1653     Tmp2 = SelectExpr(N.getOperand(1));
1654
1655     bool isFP=false;
1656
1657     if(DestType == MVT::f64) // XXX: we're not gonna be fed MVT::f32, are we?
1658       isFP=true;
1659
1660     bool isModulus=false; // is it a division or a modulus?
1661     bool isSigned=false;
1662
1663     switch(N.getOpcode()) {
1664       case ISD::SDIV:  isModulus=false; isSigned=true;  break;
1665       case ISD::UDIV:  isModulus=false; isSigned=false; break;
1666       case ISD::SREM:  isModulus=true;  isSigned=true;  break;
1667       case ISD::UREM:  isModulus=true;  isSigned=false; break;
1668     }
1669
1670     if(!isModulus && !isFP) { // if this is an integer divide,
1671       switch (ponderIntegerDivisionBy(N.getOperand(1), isSigned, Tmp3)) {
1672         case 1: // division by a constant that's a power of 2
1673           Tmp1 = SelectExpr(N.getOperand(0));
1674           if(isSigned) {  // argument could be negative, so emit some code:
1675             unsigned divAmt=Tmp3;
1676             unsigned tempGR1=MakeReg(MVT::i64);
1677             unsigned tempGR2=MakeReg(MVT::i64);
1678             unsigned tempGR3=MakeReg(MVT::i64);
1679             BuildMI(BB, IA64::SHRS, 2, tempGR1)
1680               .addReg(Tmp1).addImm(divAmt-1);
1681             BuildMI(BB, IA64::EXTRU, 3, tempGR2)
1682               .addReg(tempGR1).addImm(64-divAmt).addImm(divAmt);
1683             BuildMI(BB, IA64::ADD, 2, tempGR3)
1684               .addReg(Tmp1).addReg(tempGR2);
1685             BuildMI(BB, IA64::SHRS, 2, Result)
1686               .addReg(tempGR3).addImm(divAmt);
1687           }
1688           else // unsigned div-by-power-of-2 becomes a simple shift right:
1689             BuildMI(BB, IA64::SHRU, 2, Result).addReg(Tmp1).addImm(Tmp3);
1690           return Result; // early exit
1691       }
1692     }
1693
1694     unsigned TmpPR=MakeReg(MVT::i1);  // we need two scratch
1695     unsigned TmpPR2=MakeReg(MVT::i1); // predicate registers,
1696     unsigned TmpF1=MakeReg(MVT::f64); // and one metric truckload of FP regs.
1697     unsigned TmpF2=MakeReg(MVT::f64); // lucky we have IA64?
1698     unsigned TmpF3=MakeReg(MVT::f64); // well, the real FIXME is to have
1699     unsigned TmpF4=MakeReg(MVT::f64); // isTwoAddress forms of these
1700     unsigned TmpF5=MakeReg(MVT::f64); // FP instructions so we can end up with
1701     unsigned TmpF6=MakeReg(MVT::f64); // stuff like setf.sig f10=f10 etc.
1702     unsigned TmpF7=MakeReg(MVT::f64);
1703     unsigned TmpF8=MakeReg(MVT::f64);
1704     unsigned TmpF9=MakeReg(MVT::f64);
1705     unsigned TmpF10=MakeReg(MVT::f64);
1706     unsigned TmpF11=MakeReg(MVT::f64);
1707     unsigned TmpF12=MakeReg(MVT::f64);
1708     unsigned TmpF13=MakeReg(MVT::f64);
1709     unsigned TmpF14=MakeReg(MVT::f64);
1710     unsigned TmpF15=MakeReg(MVT::f64);
1711
1712     // OK, emit some code:
1713
1714     if(!isFP) {
1715       // first, load the inputs into FP regs.
1716       BuildMI(BB, IA64::SETFSIG, 1, TmpF1).addReg(Tmp1);
1717       BuildMI(BB, IA64::SETFSIG, 1, TmpF2).addReg(Tmp2);
1718
1719       // next, convert the inputs to FP
1720       if(isSigned) {
1721         BuildMI(BB, IA64::FCVTXF, 1, TmpF3).addReg(TmpF1);
1722         BuildMI(BB, IA64::FCVTXF, 1, TmpF4).addReg(TmpF2);
1723       } else {
1724         BuildMI(BB, IA64::FCVTXUFS1, 1, TmpF3).addReg(TmpF1);
1725         BuildMI(BB, IA64::FCVTXUFS1, 1, TmpF4).addReg(TmpF2);
1726       }
1727
1728     } else { // this is an FP divide/remainder, so we 'leak' some temp
1729              // regs and assign TmpF3=Tmp1, TmpF4=Tmp2
1730       TmpF3=Tmp1;
1731       TmpF4=Tmp2;
1732     }
1733
1734     // we start by computing an approximate reciprocal (good to 9 bits?)
1735     // note, this instruction writes _both_ TmpF5 (answer) and TmpPR (predicate)
1736     BuildMI(BB, IA64::FRCPAS1, 4)
1737       .addReg(TmpF5, MachineOperand::Def)
1738       .addReg(TmpPR, MachineOperand::Def)
1739       .addReg(TmpF3).addReg(TmpF4);
1740
1741     if(!isModulus) { // if this is a divide, we worry about div-by-zero
1742       unsigned bogusPR=MakeReg(MVT::i1); // won't appear, due to twoAddress
1743                                        // TPCMPNE below
1744       BuildMI(BB, IA64::CMPEQ, 2, bogusPR).addReg(IA64::r0).addReg(IA64::r0);
1745       BuildMI(BB, IA64::TPCMPNE, 3, TmpPR2).addReg(bogusPR)
1746         .addReg(IA64::r0).addReg(IA64::r0).addReg(TmpPR);
1747     }
1748
1749     // now we apply newton's method, thrice! (FIXME: this is ~72 bits of
1750     // precision, don't need this much for f32/i32)
1751     BuildMI(BB, IA64::CFNMAS1, 4, TmpF6)
1752       .addReg(TmpF4).addReg(TmpF5).addReg(IA64::F1).addReg(TmpPR);
1753     BuildMI(BB, IA64::CFMAS1,  4, TmpF7)
1754       .addReg(TmpF3).addReg(TmpF5).addReg(IA64::F0).addReg(TmpPR);
1755     BuildMI(BB, IA64::CFMAS1,  4, TmpF8)
1756       .addReg(TmpF6).addReg(TmpF6).addReg(IA64::F0).addReg(TmpPR);
1757     BuildMI(BB, IA64::CFMAS1,  4, TmpF9)
1758       .addReg(TmpF6).addReg(TmpF7).addReg(TmpF7).addReg(TmpPR);
1759     BuildMI(BB, IA64::CFMAS1,  4,TmpF10)
1760       .addReg(TmpF6).addReg(TmpF5).addReg(TmpF5).addReg(TmpPR);
1761     BuildMI(BB, IA64::CFMAS1,  4,TmpF11)
1762       .addReg(TmpF8).addReg(TmpF9).addReg(TmpF9).addReg(TmpPR);
1763     BuildMI(BB, IA64::CFMAS1,  4,TmpF12)
1764       .addReg(TmpF8).addReg(TmpF10).addReg(TmpF10).addReg(TmpPR);
1765     BuildMI(BB, IA64::CFNMAS1, 4,TmpF13)
1766       .addReg(TmpF4).addReg(TmpF11).addReg(TmpF3).addReg(TmpPR);
1767
1768        // FIXME: this is unfortunate :(
1769        // the story is that the dest reg of the fnma above and the fma below
1770        // (and therefore possibly the src of the fcvt.fx[u] as well) cannot
1771        // be the same register, or this code breaks if the first argument is
1772        // zero. (e.g. without this hack, 0%8 yields -64, not 0.)
1773     BuildMI(BB, IA64::CFMAS1,  4,TmpF14)
1774       .addReg(TmpF13).addReg(TmpF12).addReg(TmpF11).addReg(TmpPR);
1775
1776     if(isModulus) { // XXX: fragile! fixes _only_ mod, *breaks* div! !
1777       BuildMI(BB, IA64::IUSE, 1).addReg(TmpF13); // hack :(
1778     }
1779
1780     if(!isFP) {
1781       // round to an integer
1782       if(isSigned)
1783         BuildMI(BB, IA64::FCVTFXTRUNCS1, 1, TmpF15).addReg(TmpF14);
1784       else
1785         BuildMI(BB, IA64::FCVTFXUTRUNCS1, 1, TmpF15).addReg(TmpF14);
1786     } else {
1787       BuildMI(BB, IA64::FMOV, 1, TmpF15).addReg(TmpF14);
1788      // EXERCISE: can you see why TmpF15=TmpF14 does not work here, and
1789      // we really do need the above FMOV? ;)
1790     }
1791
1792     if(!isModulus) {
1793       if(isFP) { // extra worrying about div-by-zero
1794       unsigned bogoResult=MakeReg(MVT::f64);
1795
1796       // we do a 'conditional fmov' (of the correct result, depending
1797       // on how the frcpa predicate turned out)
1798       BuildMI(BB, IA64::PFMOV, 2, bogoResult)
1799         .addReg(TmpF12).addReg(TmpPR2);
1800       BuildMI(BB, IA64::CFMOV, 2, Result)
1801         .addReg(bogoResult).addReg(TmpF15).addReg(TmpPR);
1802       }
1803       else {
1804         BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(TmpF15);
1805       }
1806     } else { // this is a modulus
1807       if(!isFP) {
1808         // answer = q * (-b) + a
1809         unsigned ModulusResult = MakeReg(MVT::f64);
1810         unsigned TmpF = MakeReg(MVT::f64);
1811         unsigned TmpI = MakeReg(MVT::i64);
1812         
1813         BuildMI(BB, IA64::SUB, 2, TmpI).addReg(IA64::r0).addReg(Tmp2);
1814         BuildMI(BB, IA64::SETFSIG, 1, TmpF).addReg(TmpI);
1815         BuildMI(BB, IA64::XMAL, 3, ModulusResult)
1816           .addReg(TmpF15).addReg(TmpF).addReg(TmpF1);
1817         BuildMI(BB, IA64::GETFSIG, 1, Result).addReg(ModulusResult);
1818       } else { // FP modulus! The horror... the horror....
1819         assert(0 && "sorry, no FP modulus just yet!\n!\n");
1820       }
1821     }
1822
1823     return Result;
1824   }
1825
1826   case ISD::SIGN_EXTEND_INREG: {
1827     Tmp1 = SelectExpr(N.getOperand(0));
1828     MVTSDNode* MVN = dyn_cast<MVTSDNode>(Node);
1829     switch(MVN->getExtraValueType())
1830     {
1831     default:
1832       Node->dump();
1833       assert(0 && "don't know how to sign extend this type");
1834       break;
1835     case MVT::i8: Opc = IA64::SXT1; break;
1836     case MVT::i16: Opc = IA64::SXT2; break;
1837     case MVT::i32: Opc = IA64::SXT4; break;
1838     }
1839     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1840     return Result;
1841   }
1842
1843   case ISD::SETCC: {
1844     Tmp1 = SelectExpr(N.getOperand(0));
1845
1846     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
1847       if (MVT::isInteger(SetCC->getOperand(0).getValueType())) {
1848
1849         if(ConstantSDNode *CSDN =
1850              dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1851         // if we are comparing against a constant zero
1852         if(CSDN->getValue()==0)
1853           Tmp2 = IA64::r0; // then we can just compare against r0
1854         else
1855           Tmp2 = SelectExpr(N.getOperand(1));
1856         } else // not comparing against a constant
1857           Tmp2 = SelectExpr(N.getOperand(1));
1858         
1859         switch (SetCC->getCondition()) {
1860         default: assert(0 && "Unknown integer comparison!");
1861         case ISD::SETEQ:
1862           BuildMI(BB, IA64::CMPEQ, 2, Result).addReg(Tmp1).addReg(Tmp2);
1863           break;
1864         case ISD::SETGT:
1865           BuildMI(BB, IA64::CMPGT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1866           break;
1867         case ISD::SETGE:
1868           BuildMI(BB, IA64::CMPGE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1869           break;
1870         case ISD::SETLT:
1871           BuildMI(BB, IA64::CMPLT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1872           break;
1873         case ISD::SETLE:
1874           BuildMI(BB, IA64::CMPLE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1875           break;
1876         case ISD::SETNE:
1877           BuildMI(BB, IA64::CMPNE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1878           break;
1879         case ISD::SETULT:
1880           BuildMI(BB, IA64::CMPLTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1881           break;
1882         case ISD::SETUGT:
1883           BuildMI(BB, IA64::CMPGTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1884           break;
1885         case ISD::SETULE:
1886           BuildMI(BB, IA64::CMPLEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1887           break;
1888         case ISD::SETUGE:
1889           BuildMI(BB, IA64::CMPGEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1890           break;
1891         }
1892       }
1893       else { // if not integer, should be FP. FIXME: what about bools? ;)
1894         assert(SetCC->getOperand(0).getValueType() != MVT::f32 &&
1895             "error: SETCC should have had incoming f32 promoted to f64!\n");
1896
1897         if(ConstantFPSDNode *CFPSDN =
1898              dyn_cast<ConstantFPSDNode>(N.getOperand(1))) {
1899
1900           // if we are comparing against a constant +0.0 or +1.0
1901           if(CFPSDN->isExactlyValue(+0.0))
1902             Tmp2 = IA64::F0; // then we can just compare against f0
1903           else if(CFPSDN->isExactlyValue(+1.0))
1904             Tmp2 = IA64::F1; // or f1
1905           else
1906             Tmp2 = SelectExpr(N.getOperand(1));
1907         } else // not comparing against a constant
1908           Tmp2 = SelectExpr(N.getOperand(1));
1909
1910         switch (SetCC->getCondition()) {
1911         default: assert(0 && "Unknown FP comparison!");
1912         case ISD::SETEQ:
1913           BuildMI(BB, IA64::FCMPEQ, 2, Result).addReg(Tmp1).addReg(Tmp2);
1914           break;
1915         case ISD::SETGT:
1916           BuildMI(BB, IA64::FCMPGT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1917           break;
1918         case ISD::SETGE:
1919           BuildMI(BB, IA64::FCMPGE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1920           break;
1921         case ISD::SETLT:
1922           BuildMI(BB, IA64::FCMPLT, 2, Result).addReg(Tmp1).addReg(Tmp2);
1923           break;
1924         case ISD::SETLE:
1925           BuildMI(BB, IA64::FCMPLE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1926           break;
1927         case ISD::SETNE:
1928           BuildMI(BB, IA64::FCMPNE, 2, Result).addReg(Tmp1).addReg(Tmp2);
1929           break;
1930         case ISD::SETULT:
1931           BuildMI(BB, IA64::FCMPLTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1932           break;
1933         case ISD::SETUGT:
1934           BuildMI(BB, IA64::FCMPGTU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1935           break;
1936         case ISD::SETULE:
1937           BuildMI(BB, IA64::FCMPLEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1938           break;
1939         case ISD::SETUGE:
1940           BuildMI(BB, IA64::FCMPGEU, 2, Result).addReg(Tmp1).addReg(Tmp2);
1941           break;
1942         }
1943       }
1944     }
1945     else
1946       assert(0 && "this setcc not implemented yet");
1947
1948     return Result;
1949   }
1950
1951   case ISD::EXTLOAD:
1952   case ISD::ZEXTLOAD:
1953   case ISD::LOAD: {
1954     // Make sure we generate both values.
1955     if (Result != 1)
1956       ExprMap[N.getValue(1)] = 1;   // Generate the token
1957     else
1958       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1959
1960     bool isBool=false;
1961
1962     if(opcode == ISD::LOAD) { // this is a LOAD
1963       switch (Node->getValueType(0)) {
1964         default: assert(0 && "Cannot load this type!");
1965         case MVT::i1:  Opc = IA64::LD1; isBool=true; break;
1966               // FIXME: for now, we treat bool loads the same as i8 loads */
1967         case MVT::i8:  Opc = IA64::LD1; break;
1968         case MVT::i16: Opc = IA64::LD2; break;
1969         case MVT::i32: Opc = IA64::LD4; break;
1970         case MVT::i64: Opc = IA64::LD8; break;
1971                 
1972         case MVT::f32: Opc = IA64::LDF4; break;
1973         case MVT::f64: Opc = IA64::LDF8; break;
1974       }
1975     } else { // this is an EXTLOAD or ZEXTLOAD
1976       MVT::ValueType TypeBeingLoaded = cast<MVTSDNode>(Node)->getExtraValueType();
1977       switch (TypeBeingLoaded) {
1978         default: assert(0 && "Cannot extload/zextload this type!");
1979         // FIXME: bools?
1980         case MVT::i8: Opc = IA64::LD1; break;
1981         case MVT::i16: Opc = IA64::LD2; break;
1982         case MVT::i32: Opc = IA64::LD4; break;
1983         case MVT::f32: Opc = IA64::LDF4; break;
1984       }
1985     }
1986
1987     SDOperand Chain = N.getOperand(0);
1988     SDOperand Address = N.getOperand(1);
1989
1990     if(Address.getOpcode() == ISD::GlobalAddress) {
1991       Select(Chain);
1992       unsigned dummy = MakeReg(MVT::i64);
1993       unsigned dummy2 = MakeReg(MVT::i64);
1994       BuildMI(BB, IA64::ADD, 2, dummy)
1995         .addGlobalAddress(cast<GlobalAddressSDNode>(Address)->getGlobal())
1996         .addReg(IA64::r1);
1997       BuildMI(BB, IA64::LD8, 1, dummy2).addReg(dummy);
1998       if(!isBool)
1999         BuildMI(BB, Opc, 1, Result).addReg(dummy2);
2000       else { // emit a little pseudocode to load a bool (stored in one byte)
2001              // into a predicate register
2002         assert(Opc==IA64::LD1 && "problem loading a bool");
2003         unsigned dummy3 = MakeReg(MVT::i64);
2004         BuildMI(BB, Opc, 1, dummy3).addReg(dummy2);
2005         // we compare to 0. true? 0. false? 1.
2006         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
2007       }
2008     } else if(ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
2009       Select(Chain);
2010       IA64Lowering.restoreGP(BB);
2011       unsigned dummy = MakeReg(MVT::i64);
2012       BuildMI(BB, IA64::ADD, 2, dummy).addConstantPoolIndex(CP->getIndex())
2013         .addReg(IA64::r1); // CPI+GP
2014       if(!isBool)
2015         BuildMI(BB, Opc, 1, Result).addReg(dummy);
2016       else { // emit a little pseudocode to load a bool (stored in one byte)
2017              // into a predicate register
2018         assert(Opc==IA64::LD1 && "problem loading a bool");
2019         unsigned dummy3 = MakeReg(MVT::i64);
2020         BuildMI(BB, Opc, 1, dummy3).addReg(dummy);
2021         // we compare to 0. true? 0. false? 1.
2022         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
2023       }
2024     } else if(Address.getOpcode() == ISD::FrameIndex) {
2025       Select(Chain);  // FIXME ? what about bools?
2026       unsigned dummy = MakeReg(MVT::i64);
2027       BuildMI(BB, IA64::MOV, 1, dummy)
2028         .addFrameIndex(cast<FrameIndexSDNode>(Address)->getIndex());
2029       if(!isBool)
2030         BuildMI(BB, Opc, 1, Result).addReg(dummy);
2031       else { // emit a little pseudocode to load a bool (stored in one byte)
2032              // into a predicate register
2033         assert(Opc==IA64::LD1 && "problem loading a bool");
2034         unsigned dummy3 = MakeReg(MVT::i64);
2035         BuildMI(BB, Opc, 1, dummy3).addReg(dummy);
2036         // we compare to 0. true? 0. false? 1.
2037         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy3).addReg(IA64::r0);
2038       }
2039     } else { // none of the above...
2040       Select(Chain);
2041       Tmp2 = SelectExpr(Address);
2042       if(!isBool)
2043         BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
2044       else { // emit a little pseudocode to load a bool (stored in one byte)
2045              // into a predicate register
2046         assert(Opc==IA64::LD1 && "problem loading a bool");
2047         unsigned dummy = MakeReg(MVT::i64);
2048         BuildMI(BB, Opc, 1, dummy).addReg(Tmp2);
2049         // we compare to 0. true? 0. false? 1.
2050         BuildMI(BB, IA64::CMPNE, 2, Result).addReg(dummy).addReg(IA64::r0);
2051       }        
2052     }
2053
2054     return Result;
2055   }
2056
2057   case ISD::CopyFromReg: {
2058     if (Result == 1)
2059         Result = ExprMap[N.getValue(0)] =
2060           MakeReg(N.getValue(0).getValueType());
2061
2062       SDOperand Chain   = N.getOperand(0);
2063
2064       Select(Chain);
2065       unsigned r = dyn_cast<RegSDNode>(Node)->getReg();
2066
2067       if(N.getValueType() == MVT::i1) // if a bool, we use pseudocode
2068         BuildMI(BB, IA64::PCMPEQUNC, 3, Result)
2069           .addReg(IA64::r0).addReg(IA64::r0).addReg(r);
2070                             // (r) Result =cmp.eq.unc(r0,r0)
2071       else
2072         BuildMI(BB, IA64::MOV, 1, Result).addReg(r); // otherwise MOV
2073       return Result;
2074   }
2075
2076   case ISD::TAILCALL:
2077   case ISD::CALL: {
2078       Select(N.getOperand(0));
2079
2080       // The chain for this call is now lowered.
2081       ExprMap.insert(std::make_pair(N.getValue(Node->getNumValues()-1), 1));
2082
2083       //grab the arguments
2084       std::vector<unsigned> argvregs;
2085
2086       for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
2087         argvregs.push_back(SelectExpr(N.getOperand(i)));
2088
2089       // see section 8.5.8 of "Itanium Software Conventions and
2090       // Runtime Architecture Guide to see some examples of what's going
2091       // on here. (in short: int args get mapped 1:1 'slot-wise' to out0->out7,
2092       // while FP args get mapped to F8->F15 as needed)
2093
2094       unsigned used_FPArgs=0; // how many FP Args have been used so far?
2095
2096       // in reg args
2097       for(int i = 0, e = std::min(8, (int)argvregs.size()); i < e; ++i)
2098       {
2099         unsigned intArgs[] = {IA64::out0, IA64::out1, IA64::out2, IA64::out3,
2100                               IA64::out4, IA64::out5, IA64::out6, IA64::out7 };
2101         unsigned FPArgs[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
2102                              IA64::F12, IA64::F13, IA64::F14, IA64::F15 };
2103
2104         switch(N.getOperand(i+2).getValueType())
2105         {
2106           default:  // XXX do we need to support MVT::i1 here?
2107             Node->dump();
2108             N.getOperand(i).Val->dump();
2109             std::cerr << "Type for " << i << " is: " <<
2110               N.getOperand(i+2).getValueType() << std::endl;
2111             assert(0 && "Unknown value type for call");
2112           case MVT::i64:
2113             BuildMI(BB, IA64::MOV, 1, intArgs[i]).addReg(argvregs[i]);
2114             break;
2115           case MVT::f64:
2116             BuildMI(BB, IA64::FMOV, 1, FPArgs[used_FPArgs++])
2117               .addReg(argvregs[i]);
2118             // FIXME: we don't need to do this _all_ the time:
2119             BuildMI(BB, IA64::GETFD, 1, intArgs[i]).addReg(argvregs[i]);
2120             break;
2121           }
2122       }
2123
2124       //in mem args
2125       for (int i = 8, e = argvregs.size(); i < e; ++i)
2126       {
2127         unsigned tempAddr = MakeReg(MVT::i64);
2128         
2129         switch(N.getOperand(i+2).getValueType()) {
2130         default:
2131           Node->dump();
2132           N.getOperand(i).Val->dump();
2133           std::cerr << "Type for " << i << " is: " <<
2134             N.getOperand(i+2).getValueType() << "\n";
2135           assert(0 && "Unknown value type for call");
2136         case MVT::i1: // FIXME?
2137         case MVT::i8:
2138         case MVT::i16:
2139         case MVT::i32:
2140         case MVT::i64:
2141           BuildMI(BB, IA64::ADDIMM22, 2, tempAddr)
2142             .addReg(IA64::r12).addImm(16 + (i - 8) * 8); // r12 is SP
2143           BuildMI(BB, IA64::ST8, 2).addReg(tempAddr).addReg(argvregs[i]);
2144           break;
2145         case MVT::f32:
2146         case MVT::f64:
2147           BuildMI(BB, IA64::ADDIMM22, 2, tempAddr)
2148             .addReg(IA64::r12).addImm(16 + (i - 8) * 8); // r12 is SP
2149           BuildMI(BB, IA64::STF8, 2).addReg(tempAddr).addReg(argvregs[i]);
2150           break;
2151         }
2152       }
2153
2154     // build the right kind of call. if we can branch directly, do so:
2155     if (GlobalAddressSDNode *GASD =
2156                dyn_cast<GlobalAddressSDNode>(N.getOperand(1)))
2157       {
2158         BuildMI(BB, IA64::BRCALL, 1).addGlobalAddress(GASD->getGlobal(),true);
2159         IA64Lowering.restoreGP_SP_RP(BB);
2160       } else
2161     if (ExternalSymbolSDNode *ESSDN =
2162              dyn_cast<ExternalSymbolSDNode>(N.getOperand(1)))
2163       { // FIXME : currently need this case for correctness, to avoid
2164         // "non-pic code with imm relocation against dynamic symbol" errors
2165         BuildMI(BB, IA64::BRCALL, 1)
2166           .addExternalSymbol(ESSDN->getSymbol(), true);
2167         IA64Lowering.restoreGP_SP_RP(BB);
2168       }
2169     else { // otherwise we need to get the function descriptor
2170            // load the branch target (function)'s entry point and
2171            // GP, then branch
2172       Tmp1 = SelectExpr(N.getOperand(1));
2173
2174       unsigned targetEntryPoint=MakeReg(MVT::i64);
2175       unsigned targetGPAddr=MakeReg(MVT::i64);
2176       unsigned currentGP=MakeReg(MVT::i64);
2177
2178       // b6 is a scratch branch register, we load the target entry point
2179       // from the base of the function descriptor
2180       BuildMI(BB, IA64::LD8, 1, targetEntryPoint).addReg(Tmp1);
2181       BuildMI(BB, IA64::MOV, 1, IA64::B6).addReg(targetEntryPoint);
2182
2183       // save the current GP:
2184       BuildMI(BB, IA64::MOV, 1, currentGP).addReg(IA64::r1);
2185
2186       /* TODO: we need to make sure doing this never, ever loads a
2187        * bogus value into r1 (GP). */
2188       // load the target GP (which is at mem[functiondescriptor+8])
2189       BuildMI(BB, IA64::ADDIMM22, 2, targetGPAddr)
2190         .addReg(Tmp1).addImm(8); // FIXME: addimm22? why not postincrement ld
2191       BuildMI(BB, IA64::LD8, 1, IA64::r1).addReg(targetGPAddr);
2192
2193       // and then jump: (well, call)
2194       BuildMI(BB, IA64::BRCALL, 1).addReg(IA64::B6);
2195       // and finally restore the old GP
2196       BuildMI(BB, IA64::MOV, 1, IA64::r1).addReg(currentGP);
2197       IA64Lowering.restoreSP_RP(BB);
2198     }
2199
2200     switch (Node->getValueType(0)) {
2201     default: assert(0 && "Unknown value type for call result!");
2202     case MVT::Other: return 1;
2203     case MVT::i1:
2204       BuildMI(BB, IA64::CMPNE, 2, Result)
2205         .addReg(IA64::r8).addReg(IA64::r0);
2206       break;
2207     case MVT::i8:
2208     case MVT::i16:
2209     case MVT::i32:
2210     case MVT::i64:
2211       BuildMI(BB, IA64::MOV, 1, Result).addReg(IA64::r8);
2212       break;
2213     case MVT::f64:
2214       BuildMI(BB, IA64::FMOV, 1, Result).addReg(IA64::F8);
2215       break;
2216     }
2217     return Result+N.ResNo;
2218   }
2219
2220   } // <- uhhh XXX
2221   return 0;
2222 }
2223
2224 void ISel::Select(SDOperand N) {
2225   unsigned Tmp1, Tmp2, Opc;
2226   unsigned opcode = N.getOpcode();
2227
2228   if (!LoweredTokens.insert(N).second)
2229     return;  // Already selected.
2230
2231   SDNode *Node = N.Val;
2232
2233   switch (Node->getOpcode()) {
2234   default:
2235     Node->dump(); std::cerr << "\n";
2236     assert(0 && "Node not handled yet!");
2237
2238   case ISD::EntryToken: return;  // Noop
2239
2240   case ISD::TokenFactor: {
2241     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
2242       Select(Node->getOperand(i));
2243     return;
2244   }
2245
2246   case ISD::CopyToReg: {
2247     Select(N.getOperand(0));
2248     Tmp1 = SelectExpr(N.getOperand(1));
2249     Tmp2 = cast<RegSDNode>(N)->getReg();
2250
2251     if (Tmp1 != Tmp2) {
2252       if(N.getValueType() == MVT::i1) // if a bool, we use pseudocode
2253         BuildMI(BB, IA64::PCMPEQUNC, 3, Tmp2)
2254           .addReg(IA64::r0).addReg(IA64::r0).addReg(Tmp1);
2255                                    // (Tmp1) Tmp2 = cmp.eq.unc(r0,r0)
2256       else
2257         BuildMI(BB, IA64::MOV, 1, Tmp2).addReg(Tmp1);
2258                       // XXX is this the right way 'round? ;)
2259     }
2260     return;
2261   }
2262
2263   case ISD::RET: {
2264
2265   /* what the heck is going on here:
2266
2267 <_sabre_> ret with two operands is obvious: chain and value
2268 <camel_> yep
2269 <_sabre_> ret with 3 values happens when 'expansion' occurs
2270 <_sabre_> e.g. i64 gets split into 2x i32
2271 <camel_> oh right
2272 <_sabre_> you don't have this case on ia64
2273 <camel_> yep
2274 <_sabre_> so the two returned values go into EAX/EDX on ia32
2275 <camel_> ahhh *memories*
2276 <_sabre_> :)
2277 <camel_> ok, thanks :)
2278 <_sabre_> so yeah, everything that has a side effect takes a 'token chain'
2279 <_sabre_> this is the first operand always
2280 <_sabre_> these operand often define chains, they are the last operand
2281 <_sabre_> they are printed as 'ch' if you do DAG.dump()
2282   */
2283
2284     switch (N.getNumOperands()) {
2285     default:
2286       assert(0 && "Unknown return instruction!");
2287     case 2:
2288         Select(N.getOperand(0));
2289         Tmp1 = SelectExpr(N.getOperand(1));
2290       switch (N.getOperand(1).getValueType()) {
2291       default: assert(0 && "All other types should have been promoted!!");
2292                // FIXME: do I need to add support for bools here?
2293                // (return '0' or '1' r8, basically...)
2294                //
2295                // FIXME: need to round floats - 80 bits is bad, the tester
2296                // told me so
2297       case MVT::i64:
2298         // we mark r8 as live on exit up above in LowerArguments()
2299         BuildMI(BB, IA64::MOV, 1, IA64::r8).addReg(Tmp1);
2300         break;
2301       case MVT::f64:
2302         // we mark F8 as live on exit up above in LowerArguments()
2303         BuildMI(BB, IA64::FMOV, 1, IA64::F8).addReg(Tmp1);
2304       }
2305       break;
2306     case 1:
2307       Select(N.getOperand(0));
2308       break;
2309     }
2310     // before returning, restore the ar.pfs register (set by the 'alloc' up top)
2311     BuildMI(BB, IA64::MOV, 1).addReg(IA64::AR_PFS).addReg(IA64Lowering.VirtGPR);
2312     BuildMI(BB, IA64::RET, 0); // and then just emit a 'ret' instruction
2313     return;
2314   }
2315
2316   case ISD::BR: {
2317     Select(N.getOperand(0));
2318     MachineBasicBlock *Dest =
2319       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
2320     BuildMI(BB, IA64::BRLCOND_NOTCALL, 1).addReg(IA64::p0).addMBB(Dest);
2321     // XXX HACK! we do _not_ need long branches all the time
2322     return;
2323   }
2324
2325   case ISD::ImplicitDef: {
2326     Select(N.getOperand(0));
2327     BuildMI(BB, IA64::IDEF, 0, cast<RegSDNode>(N)->getReg());
2328     return;
2329   }
2330
2331   case ISD::BRCOND: {
2332     MachineBasicBlock *Dest =
2333       cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
2334
2335     Select(N.getOperand(0));
2336     Tmp1 = SelectExpr(N.getOperand(1));
2337     BuildMI(BB, IA64::BRLCOND_NOTCALL, 1).addReg(Tmp1).addMBB(Dest);
2338     // XXX HACK! we do _not_ need long branches all the time
2339     return;
2340   }
2341
2342   case ISD::EXTLOAD:
2343   case ISD::ZEXTLOAD:
2344   case ISD::SEXTLOAD:
2345   case ISD::LOAD:
2346   case ISD::TAILCALL:
2347   case ISD::CALL:
2348   case ISD::CopyFromReg:
2349   case ISD::DYNAMIC_STACKALLOC:
2350     SelectExpr(N);
2351     return;
2352
2353   case ISD::TRUNCSTORE:
2354   case ISD::STORE: {
2355       Select(N.getOperand(0));
2356       Tmp1 = SelectExpr(N.getOperand(1)); // value
2357
2358       bool isBool=false;
2359
2360       if(opcode == ISD::STORE) {
2361         switch (N.getOperand(1).getValueType()) {
2362           default: assert(0 && "Cannot store this type!");
2363           case MVT::i1:  Opc = IA64::ST1; isBool=true; break;
2364               // FIXME?: for now, we treat bool loads the same as i8 stores */
2365           case MVT::i8:  Opc = IA64::ST1; break;
2366           case MVT::i16: Opc = IA64::ST2; break;
2367           case MVT::i32: Opc = IA64::ST4; break;
2368           case MVT::i64: Opc = IA64::ST8; break;
2369                         
2370           case MVT::f32: Opc = IA64::STF4; break;
2371           case MVT::f64: Opc = IA64::STF8; break;
2372         }
2373       } else { // truncstore
2374         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
2375           default: assert(0 && "unknown type in truncstore");
2376           case MVT::i1: Opc = IA64::ST1; isBool=true; break;
2377                         //FIXME: DAG does not promote this load?
2378           case MVT::i8: Opc = IA64::ST1; break;
2379           case MVT::i16: Opc = IA64::ST2; break;
2380           case MVT::i32: Opc = IA64::ST4; break;
2381           case MVT::f32: Opc = IA64::STF4; break;
2382         }
2383       }
2384
2385       if(N.getOperand(2).getOpcode() == ISD::GlobalAddress) {
2386         unsigned dummy = MakeReg(MVT::i64);
2387         unsigned dummy2 = MakeReg(MVT::i64);
2388         BuildMI(BB, IA64::ADD, 2, dummy)
2389           .addGlobalAddress(cast<GlobalAddressSDNode>
2390               (N.getOperand(2))->getGlobal()).addReg(IA64::r1);
2391         BuildMI(BB, IA64::LD8, 1, dummy2).addReg(dummy);
2392
2393         if(!isBool)
2394           BuildMI(BB, Opc, 2).addReg(dummy2).addReg(Tmp1);
2395         else { // we are storing a bool, so emit a little pseudocode
2396                // to store a predicate register as one byte
2397           assert(Opc==IA64::ST1);
2398           unsigned dummy3 = MakeReg(MVT::i64);
2399           unsigned dummy4 = MakeReg(MVT::i64);
2400           BuildMI(BB, IA64::MOV, 1, dummy3).addReg(IA64::r0);
2401           BuildMI(BB, IA64::TPCADDIMM22, 2, dummy4)
2402             .addReg(dummy3).addImm(1).addReg(Tmp1); // if(Tmp1) dummy=0+1;
2403           BuildMI(BB, Opc, 2).addReg(dummy2).addReg(dummy4);
2404         }
2405       } else if(N.getOperand(2).getOpcode() == ISD::FrameIndex) {
2406
2407         // FIXME? (what about bools?)
2408         
2409         unsigned dummy = MakeReg(MVT::i64);
2410         BuildMI(BB, IA64::MOV, 1, dummy)
2411           .addFrameIndex(cast<FrameIndexSDNode>(N.getOperand(2))->getIndex());
2412         BuildMI(BB, Opc, 2).addReg(dummy).addReg(Tmp1);
2413       } else { // otherwise
2414         Tmp2 = SelectExpr(N.getOperand(2)); //address
2415         if(!isBool)
2416           BuildMI(BB, Opc, 2).addReg(Tmp2).addReg(Tmp1);
2417         else { // we are storing a bool, so emit a little pseudocode
2418                // to store a predicate register as one byte
2419           assert(Opc==IA64::ST1);
2420           unsigned dummy3 = MakeReg(MVT::i64);
2421           unsigned dummy4 = MakeReg(MVT::i64);
2422           BuildMI(BB, IA64::MOV, 1, dummy3).addReg(IA64::r0);
2423           BuildMI(BB, IA64::TPCADDIMM22, 2, dummy4)
2424             .addReg(dummy3).addImm(1).addReg(Tmp1); // if(Tmp1) dummy=0+1;
2425           BuildMI(BB, Opc, 2).addReg(Tmp2).addReg(dummy4);
2426         }
2427       }
2428     return;
2429   }
2430
2431   case ISD::CALLSEQ_START:
2432   case ISD::CALLSEQ_END: {
2433     Select(N.getOperand(0));
2434     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
2435
2436     Opc = N.getOpcode() == ISD::CALLSEQ_START ? IA64::ADJUSTCALLSTACKDOWN :
2437                                                 IA64::ADJUSTCALLSTACKUP;
2438     BuildMI(BB, Opc, 1).addImm(Tmp1);
2439     return;
2440   }
2441
2442     return;
2443   }
2444   assert(0 && "GAME OVER. INSERT COIN?");
2445 }
2446
2447
2448 /// createIA64PatternInstructionSelector - This pass converts an LLVM function
2449 /// into a machine code representation using pattern matching and a machine
2450 /// description file.
2451 ///
2452 FunctionPass *llvm::createIA64PatternInstructionSelector(TargetMachine &TM) {
2453   return new ISel(TM);
2454 }
2455
2456