Build add instructions of the correct form!
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 platform
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include <map>
26
27 using namespace MOTy;  // Get Use, Def, UseAndDef
28
29
30 /// BMI - A special BuildMI variant that takes an iterator to insert the
31 /// instruction at as well as a basic block.
32 /// this is the version for when you have a destination register in mind.
33 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
34                                       MachineBasicBlock::iterator &I,
35                                       MachineOpCode Opcode,
36                                       unsigned NumOperands,
37                                       unsigned DestReg) {
38   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
39   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
40   I = ++MBB->insert(I, MI);
41   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
42 }
43
44 /// BMI - A special BuildMI variant that takes an iterator to insert the
45 /// instruction at as well as a basic block.
46 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
47                                       MachineBasicBlock::iterator &I,
48                                       MachineOpCode Opcode,
49                                       unsigned NumOperands) {
50   assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
51   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
52   I = ++MBB->insert(I, MI);
53   return MachineInstrBuilder(MI);
54 }
55
56
57 namespace {
58   struct ISel : public FunctionPass, InstVisitor<ISel> {
59     TargetMachine &TM;
60     MachineFunction *F;                    // The function we are compiling into
61     MachineBasicBlock *BB;                 // The current MBB we are compiling
62
63     unsigned CurReg;
64     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
65
66     // MBBMap - Mapping between LLVM BB -> Machine BB
67     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
68
69     ISel(TargetMachine &tm)
70       : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
71
72     /// runOnFunction - Top level implementation of instruction selection for
73     /// the entire function.
74     ///
75     bool runOnFunction(Function &Fn) {
76       F = &MachineFunction::construct(&Fn, TM);
77
78       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
79         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
80
81       // Emit instructions to load the arguments...  The function's arguments
82       // look like this:
83       //
84       // [EBP]     -- copy of old EBP
85       // [EBP + 4] -- return address
86       // [EBP + 8] -- first argument (leftmost lexically)
87       //
88       // So we want to start with counter = 2.
89       //
90       BB = &F->front();
91       unsigned ArgOffset = 8;
92       for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E;
93            ++I, ArgOffset += 4) {
94         unsigned Reg = getReg(*I);
95
96         // Load it out of the stack frame at EBP + 4*argPos.
97
98         // FIXME: This should load the argument of the appropriate size!!
99         addRegOffset(BuildMI(BB, X86::MOVmr32, 4, Reg), X86::EBP, ArgOffset);
100       }
101
102       // Instruction select everything except PHI nodes
103       visit(Fn);
104
105       // Select the PHI nodes
106       SelectPHINodes();
107
108       RegMap.clear();
109       MBBMap.clear();
110       CurReg = MRegisterInfo::FirstVirtualRegister;
111       F = 0;
112       return false;  // We never modify the LLVM itself.
113     }
114
115     virtual const char *getPassName() const {
116       return "X86 Simple Instruction Selection";
117     }
118
119     /// visitBasicBlock - This method is called when we are visiting a new basic
120     /// block.  This simply creates a new MachineBasicBlock to emit code into
121     /// and adds it to the current MachineFunction.  Subsequent visit* for
122     /// instructions will be invoked for all instructions in the basic block.
123     ///
124     void visitBasicBlock(BasicBlock &LLVM_BB) {
125       BB = MBBMap[&LLVM_BB];
126     }
127
128
129     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
130     /// because we have to generate our sources into the source basic blocks,
131     /// not the current one.
132     ///
133     void SelectPHINodes();
134
135     // Visitation methods for various instructions.  These methods simply emit
136     // fixed X86 code for each instruction.
137     //
138
139     // Control flow operators
140     void visitReturnInst(ReturnInst &RI);
141     void visitBranchInst(BranchInst &BI);
142     void visitCallInst(CallInst &I);
143
144     // Arithmetic operators
145     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
146     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
147     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
148     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
149                     unsigned destReg, const Type *resultType,
150                     unsigned op0Reg, unsigned op1Reg);
151     void visitMul(BinaryOperator &B);
152
153     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
154     void visitRem(BinaryOperator &B) { visitDivRem(B); }
155     void visitDivRem(BinaryOperator &B);
156
157     // Bitwise operators
158     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
159     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
160     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
161
162     // Binary comparison operators
163     void visitSetCCInst(SetCondInst &I, unsigned OpNum);
164     void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
165     void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
166     void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
167     void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
168     void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
169     void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
170
171     // Memory Instructions
172     void visitLoadInst(LoadInst &I);
173     void visitStoreInst(StoreInst &I);
174     void visitGetElementPtrInst(GetElementPtrInst &I);
175     void visitMallocInst(MallocInst &I);
176     void visitFreeInst(FreeInst &I);
177     void visitAllocaInst(AllocaInst &I);
178     
179     // Other operators
180     void visitShiftInst(ShiftInst &I);
181     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
182     void visitCastInst(CastInst &I);
183
184     void visitInstruction(Instruction &I) {
185       std::cerr << "Cannot instruction select: " << I;
186       abort();
187     }
188
189     /// promote32 - Make a value 32-bits wide, and put it somewhere.
190     void promote32 (const unsigned targetReg, Value *v);
191     
192     // emitGEPOperation - Common code shared between visitGetElementPtrInst and
193     // constant expression GEP support.
194     //
195     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
196                           Value *Src, User::op_iterator IdxBegin,
197                           User::op_iterator IdxEnd, unsigned TargetReg);
198
199     /// copyConstantToRegister - Output the instructions required to put the
200     /// specified constant into the specified register.
201     ///
202     void copyConstantToRegister(MachineBasicBlock *MBB,
203                                 MachineBasicBlock::iterator &MBBI,
204                                 Constant *C, unsigned Reg);
205
206     /// makeAnotherReg - This method returns the next register number
207     /// we haven't yet used.
208     unsigned makeAnotherReg(const Type *Ty) {
209       // Add the mapping of regnumber => reg class to MachineFunction
210       F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
211       return CurReg++;
212     }
213
214     /// getReg - This method turns an LLVM value into a register number.  This
215     /// is guaranteed to produce the same register number for a particular value
216     /// every time it is queried.
217     ///
218     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
219     unsigned getReg(Value *V) {
220       // Just append to the end of the current bb.
221       MachineBasicBlock::iterator It = BB->end();
222       return getReg(V, BB, It);
223     }
224     unsigned getReg(Value *V, MachineBasicBlock *MBB,
225                     MachineBasicBlock::iterator &IPt) {
226       unsigned &Reg = RegMap[V];
227       if (Reg == 0) {
228         Reg = makeAnotherReg(V->getType());
229         RegMap[V] = Reg;
230       }
231
232       // If this operand is a constant, emit the code to copy the constant into
233       // the register here...
234       //
235       if (Constant *C = dyn_cast<Constant>(V)) {
236         copyConstantToRegister(MBB, IPt, C, Reg);
237         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
238       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
239         // Move the address of the global into the register
240         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
241         RegMap.erase(V);  // Assign a new name to this address if ref'd again
242       }
243
244       return Reg;
245     }
246   };
247 }
248
249 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
250 /// Representation.
251 ///
252 enum TypeClass {
253   cByte, cShort, cInt, cLong, cFloat, cDouble
254 };
255
256 /// getClass - Turn a primitive type into a "class" number which is based on the
257 /// size of the type, and whether or not it is floating point.
258 ///
259 static inline TypeClass getClass(const Type *Ty) {
260   switch (Ty->getPrimitiveID()) {
261   case Type::SByteTyID:
262   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
263   case Type::ShortTyID:
264   case Type::UShortTyID:  return cShort;     // Short operands are class #1
265   case Type::IntTyID:
266   case Type::UIntTyID:
267   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
268
269   case Type::LongTyID:
270   case Type::ULongTyID:   //return cLong;      // Longs are class #3
271     return cInt;          // FIXME: LONGS ARE TREATED AS INTS!
272
273   case Type::FloatTyID:   return cFloat;     // Float is class #4
274   case Type::DoubleTyID:  return cDouble;    // Doubles are class #5
275   default:
276     assert(0 && "Invalid type to getClass!");
277     return cByte;  // not reached
278   }
279 }
280
281 // getClassB - Just like getClass, but treat boolean values as bytes.
282 static inline TypeClass getClassB(const Type *Ty) {
283   if (Ty == Type::BoolTy) return cByte;
284   return getClass(Ty);
285 }
286
287
288 /// copyConstantToRegister - Output the instructions required to put the
289 /// specified constant into the specified register.
290 ///
291 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
292                                   MachineBasicBlock::iterator &IP,
293                                   Constant *C, unsigned R) {
294   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
295     if (CE->getOpcode() == Instruction::GetElementPtr) {
296       emitGEPOperation(MBB, IP, CE->getOperand(0),
297                        CE->op_begin()+1, CE->op_end(), R);
298       return;
299     }
300
301     std::cerr << "Offending expr: " << C << "\n";
302     assert (0 && "Constant expressions not yet handled!\n");
303   }
304
305   if (C->getType()->isIntegral()) {
306     unsigned Class = getClassB(C->getType());
307     assert(Class != 3 && "Type not handled yet!");
308
309     static const unsigned IntegralOpcodeTab[] = {
310       X86::MOVir8, X86::MOVir16, X86::MOVir32
311     };
312
313     if (C->getType() == Type::BoolTy) {
314       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
315     } else if (C->getType()->isSigned()) {
316       ConstantSInt *CSI = cast<ConstantSInt>(C);
317       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
318     } else {
319       ConstantUInt *CUI = cast<ConstantUInt>(C);
320       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
321     }
322   } else if (isa<ConstantPointerNull>(C)) {
323     // Copy zero (null pointer) to the register.
324     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
325   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
326     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
327     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
328   } else {
329     std::cerr << "Offending constant: " << C << "\n";
330     assert(0 && "Type not handled yet!");
331   }
332 }
333
334 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
335 /// because we have to generate our sources into the source basic blocks, not
336 /// the current one.
337 ///
338 void ISel::SelectPHINodes() {
339   const Function &LF = *F->getFunction();  // The LLVM function...
340   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
341     const BasicBlock *BB = I;
342     MachineBasicBlock *MBB = MBBMap[I];
343
344     // Loop over all of the PHI nodes in the LLVM basic block...
345     unsigned NumPHIs = 0;
346     for (BasicBlock::const_iterator I = BB->begin();
347          PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
348       // Create a new machine instr PHI node, and insert it.
349       MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
350       MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
351
352       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
353         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
354
355         // Get the incoming value into a virtual register.  If it is not already
356         // available in a virtual register, insert the computation code into
357         // PredMBB
358         //
359
360         MachineBasicBlock::iterator PI = PredMBB->begin();
361         while ((*PI)->getOpcode() == X86::PHI) ++PI;
362         
363         MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
364         MI->addMachineBasicBlockOperand(PredMBB);
365       }
366     }
367   }
368 }
369
370
371
372 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
373 /// register, then move it to wherever the result should be. 
374 /// We handle FP setcc instructions by pushing them, doing a
375 /// compare-and-pop-twice, and then copying the concodes to the main
376 /// processor's concodes (I didn't make this up, it's in the Intel manual)
377 ///
378 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
379   // The arguments are already supposed to be of the same type.
380   const Type *CompTy = I.getOperand(0)->getType();
381   unsigned reg1 = getReg(I.getOperand(0));
382   unsigned reg2 = getReg(I.getOperand(1));
383
384   unsigned Class = getClass(CompTy);
385   switch (Class) {
386     // Emit: cmp <var1>, <var2> (do the comparison).  We can
387     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
388     // 32-bit.
389   case cByte:
390     BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
391     break;
392   case cShort:
393     BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
394     break;
395   case cInt:
396     BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
397     break;
398
399     // Push the variables on the stack with fldl opcodes.
400     // FIXME: assuming var1, var2 are in memory, if not, spill to
401     // stack first
402   case cFloat:  // Floats
403     BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
404     BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
405     break;
406   case cDouble:  // Doubles
407     BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
408     BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
409     break;
410   case cLong:
411   default:
412     visitInstruction(I);
413   }
414
415   if (CompTy->isFloatingPoint()) {
416     // (Non-trapping) compare and pop twice.
417     BuildMI (BB, X86::FUCOMPP, 0);
418     // Move fp status word (concodes) to ax.
419     BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
420     // Load real concodes from ax.
421     BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
422   }
423
424   // Emit setOp instruction (extract concode; clobbers ax),
425   // using the following mapping:
426   // LLVM  -> X86 signed  X86 unsigned
427   // -----    -----       -----
428   // seteq -> sete        sete
429   // setne -> setne       setne
430   // setlt -> setl        setb
431   // setgt -> setg        seta
432   // setle -> setle       setbe
433   // setge -> setge       setae
434
435   static const unsigned OpcodeTab[2][6] = {
436     {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
437     {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
438   };
439
440   BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
441   
442   // Put it in the result using a move.
443   BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
444 }
445
446 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
447 /// operand, in the specified target register.
448 void
449 ISel::promote32 (unsigned targetReg, Value *v)
450 {
451   unsigned vReg = getReg (v);
452   unsigned Class = getClass (v->getType ());
453   bool isUnsigned = v->getType ()->isUnsigned ();
454   assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
455           && "Unpromotable operand class in promote32");
456   switch (Class)
457     {
458     case cByte:
459       // Extend value into target register (8->32)
460       if (isUnsigned)
461         BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
462       else
463         BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
464       break;
465     case cShort:
466       // Extend value into target register (16->32)
467       if (isUnsigned)
468         BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
469       else
470         BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
471       break;
472     case cInt:
473       // Move value into target register (32->32)
474       BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
475       break;
476     }
477 }
478
479 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
480 /// we have the following possibilities:
481 ///
482 ///   ret void: No return value, simply emit a 'ret' instruction
483 ///   ret sbyte, ubyte : Extend value into EAX and return
484 ///   ret short, ushort: Extend value into EAX and return
485 ///   ret int, uint    : Move value into EAX and return
486 ///   ret pointer      : Move value into EAX and return
487 ///   ret long, ulong  : Move value into EAX/EDX and return
488 ///   ret float/double : Top of FP stack
489 ///
490 void
491 ISel::visitReturnInst (ReturnInst &I)
492 {
493   if (I.getNumOperands () == 0)
494     {
495       // Emit a 'ret' instruction
496       BuildMI (BB, X86::RET, 0);
497       return;
498     }
499   Value *rv = I.getOperand (0);
500   unsigned Class = getClass (rv->getType ());
501   switch (Class)
502     {
503       // integral return values: extend or move into EAX and return. 
504     case cByte:
505     case cShort:
506     case cInt:
507       promote32 (X86::EAX, rv);
508       break;
509       // ret float/double: top of FP stack
510       // FLD <val>
511     case cFloat:                // Floats
512       BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
513       break;
514     case cDouble:               // Doubles
515       BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
516       break;
517     case cLong:
518       // ret long: use EAX(least significant 32 bits)/EDX (most
519       // significant 32)...uh, I think so Brain, but how do i call
520       // up the two parts of the value from inside this mouse
521       // cage? *zort*
522     default:
523       visitInstruction (I);
524     }
525   // Emit a 'ret' instruction
526   BuildMI (BB, X86::RET, 0);
527 }
528
529 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
530 /// that since code layout is frozen at this point, that if we are trying to
531 /// jump to a block that is the immediate successor of the current block, we can
532 /// just make a fall-through. (but we don't currently).
533 ///
534 void
535 ISel::visitBranchInst (BranchInst & BI)
536 {
537   if (BI.isConditional ())
538     {
539       BasicBlock *ifTrue = BI.getSuccessor (0);
540       BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious 
541
542       // simplest thing I can think of: compare condition with zero,
543       // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
544       // ifTrue
545       unsigned int condReg = getReg (BI.getCondition ());
546       BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
547       BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
548       BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
549     }
550   else // unconditional branch
551     {
552       BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
553     }
554 }
555
556 /// visitCallInst - Push args on stack and do a procedure call instruction.
557 void
558 ISel::visitCallInst (CallInst & CI)
559 {
560   // keep a counter of how many bytes we pushed on the stack
561   unsigned bytesPushed = 0;
562
563   // Push the arguments on the stack in reverse order, as specified by
564   // the ABI.
565   for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
566     {
567       Value *v = CI.getOperand (i);
568       switch (getClass (v->getType ()))
569         {
570         case cByte:
571         case cShort:
572           // Promote V to 32 bits wide, and move the result into EAX,
573           // then push EAX.
574           promote32 (X86::EAX, v);
575           BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
576           bytesPushed += 4;
577           break;
578         case cInt:
579         case cFloat: {
580           unsigned Reg = getReg(v);
581           BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
582           bytesPushed += 4;
583           break;
584         }
585         default:
586           // FIXME: long/ulong/double args not handled.
587           visitInstruction (CI);
588           break;
589         }
590     }
591
592   if (Function *F = CI.getCalledFunction()) {
593     // Emit a CALL instruction with PC-relative displacement.
594     BuildMI(BB, X86::CALLpcrel32, 1).addPCDisp(F);
595   } else {
596     unsigned Reg = getReg(CI.getCalledValue());
597     BuildMI(BB, X86::CALLr32, 1).addReg(Reg);
598   }
599
600   // Adjust the stack by `bytesPushed' amount if non-zero
601   if (bytesPushed > 0)
602     BuildMI (BB, X86::ADDri32,2,X86::ESP).addReg(X86::ESP).addZImm(bytesPushed);
603
604   // If there is a return value, scavenge the result from the location the call
605   // leaves it in...
606   //
607   if (CI.getType() != Type::VoidTy) {
608     unsigned resultTypeClass = getClass (CI.getType ());
609     switch (resultTypeClass) {
610     case cByte:
611     case cShort:
612     case cInt: {
613       // Integral results are in %eax, or the appropriate portion
614       // thereof.
615       static const unsigned regRegMove[] = {
616         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
617       };
618       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
619       BuildMI (BB, regRegMove[resultTypeClass], 1,
620                getReg (CI)).addReg (AReg[resultTypeClass]);
621       break;
622     }
623     case cFloat:
624       // Floating-point return values live in %st(0) (i.e., the top of
625       // the FP stack.) The general way to approach this is to do a
626       // FSTP to save the top of the FP stack on the real stack, then
627       // do a MOV to load the top of the real stack into the target
628       // register.
629       visitInstruction (CI); // FIXME: add the right args for the calls below
630       // BuildMI (BB, X86::FSTPm32, 0);
631       // BuildMI (BB, X86::MOVmr32, 0);
632       break;
633     default:
634       std::cerr << "Cannot get return value for call of type '"
635                 << *CI.getType() << "'\n";
636       visitInstruction(CI);
637     }
638   }
639 }
640
641 /// visitSimpleBinary - Implement simple binary operators for integral types...
642 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
643 /// 4 for Xor.
644 ///
645 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
646   if (B.getType() == Type::BoolTy)  // FIXME: Handle bools for logicals
647     visitInstruction(B);
648
649   unsigned Class = getClass(B.getType());
650   if (Class > 2)  // FIXME: Handle longs
651     visitInstruction(B);
652
653   static const unsigned OpcodeTab[][4] = {
654     // Arithmetic operators
655     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 },  // ADD
656     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 },  // SUB
657
658     // Bitwise operators
659     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
660     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
661     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
662   };
663   
664   unsigned Opcode = OpcodeTab[OperatorClass][Class];
665   unsigned Op0r = getReg(B.getOperand(0));
666   unsigned Op1r = getReg(B.getOperand(1));
667   BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
668 }
669
670 /// doMultiply - Emit appropriate instructions to multiply together
671 /// the registers op0Reg and op1Reg, and put the result in destReg.
672 /// The type of the result should be given as resultType.
673 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
674                       unsigned destReg, const Type *resultType,
675                       unsigned op0Reg, unsigned op1Reg) {
676   unsigned Class = getClass (resultType);
677
678   // FIXME:
679   assert (Class <= 2 && "Someday, we will learn how to multiply"
680           "longs and floating-point numbers. This is not that day.");
681  
682   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
683   static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
684   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
685   unsigned Reg     = Regs[Class];
686
687   // Emit a MOV to put the first operand into the appropriately-sized
688   // subreg of EAX.
689   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
690   
691   // Emit the appropriate multiply instruction.
692   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
693
694   // Emit another MOV to put the result into the destination register.
695   BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
696 }
697
698 /// visitMul - Multiplies are not simple binary operators because they must deal
699 /// with the EAX register explicitly.
700 ///
701 void ISel::visitMul(BinaryOperator &I) {
702   unsigned DestReg = getReg(I);
703   unsigned Op0Reg  = getReg(I.getOperand(0));
704   unsigned Op1Reg  = getReg(I.getOperand(1));
705   MachineBasicBlock::iterator MBBI = BB->end();
706   doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
707 }
708
709
710 /// visitDivRem - Handle division and remainder instructions... these
711 /// instruction both require the same instructions to be generated, they just
712 /// select the result from a different register.  Note that both of these
713 /// instructions work differently for signed and unsigned operands.
714 ///
715 void ISel::visitDivRem(BinaryOperator &I) {
716   unsigned Class = getClass(I.getType());
717   if (Class > 2)  // FIXME: Handle longs
718     visitInstruction(I);
719
720   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
721   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
722   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
723   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
724   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
725
726   static const unsigned DivOpcode[][4] = {
727     { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 },  // Unsigned division
728     { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 },  // Signed division
729   };
730
731   bool isSigned   = I.getType()->isSigned();
732   unsigned Reg    = Regs[Class];
733   unsigned ExtReg = ExtRegs[Class];
734   unsigned Op0Reg = getReg(I.getOperand(0));
735   unsigned Op1Reg = getReg(I.getOperand(1));
736
737   // Put the first operand into one of the A registers...
738   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
739
740   if (isSigned) {
741     // Emit a sign extension instruction...
742     BuildMI(BB, ExtOpcode[Class], 0);
743   } else {
744     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
745     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
746   }
747
748   // Emit the appropriate divide or remainder instruction...
749   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
750
751   // Figure out which register we want to pick the result out of...
752   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
753   
754   // Put the result into the destination register...
755   BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
756 }
757
758
759 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
760 /// for constant immediate shift values, and for constant immediate
761 /// shift values equal to 1. Even the general case is sort of special,
762 /// because the shift amount has to be in CL, not just any old register.
763 ///
764 void ISel::visitShiftInst (ShiftInst &I) {
765   unsigned Op0r = getReg (I.getOperand(0));
766   unsigned DestReg = getReg(I);
767   bool isLeftShift = I.getOpcode() == Instruction::Shl;
768   bool isOperandSigned = I.getType()->isUnsigned();
769   unsigned OperandClass = getClass(I.getType());
770
771   if (OperandClass > 2)
772     visitInstruction(I); // Can't handle longs yet!
773
774   if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
775     {
776       // The shift amount is constant, guaranteed to be a ubyte. Get its value.
777       assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
778       unsigned char shAmt = CUI->getValue();
779
780       static const unsigned ConstantOperand[][4] = {
781         { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 },  // SHR
782         { X86::SARir8, X86::SARir16, X86::SARir32, 0 },  // SAR
783         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SHL
784         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SAL = SHL
785       };
786
787       const unsigned *OpTab = // Figure out the operand table to use
788         ConstantOperand[isLeftShift*2+isOperandSigned];
789
790       // Emit: <insn> reg, shamt  (shift-by-immediate opcode "ir" form.)
791       BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
792     }
793   else
794     {
795       // The shift amount is non-constant.
796       //
797       // In fact, you can only shift with a variable shift amount if
798       // that amount is already in the CL register, so we have to put it
799       // there first.
800       //
801
802       // Emit: move cl, shiftAmount (put the shift amount in CL.)
803       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
804
805       // This is a shift right (SHR).
806       static const unsigned NonConstantOperand[][4] = {
807         { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 },  // SHR
808         { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 },  // SAR
809         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SHL
810         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SAL = SHL
811       };
812
813       const unsigned *OpTab = // Figure out the operand table to use
814         NonConstantOperand[isLeftShift*2+isOperandSigned];
815
816       BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
817     }
818 }
819
820
821 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
822 /// instruction.
823 ///
824 void ISel::visitLoadInst(LoadInst &I) {
825   unsigned Class = getClass(I.getType());
826   if (Class > 2)  // FIXME: Handle longs and others...
827     visitInstruction(I);
828
829   static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
830
831   unsigned AddressReg = getReg(I.getOperand(0));
832   addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
833 }
834
835
836 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
837 /// instruction.
838 ///
839 void ISel::visitStoreInst(StoreInst &I) {
840   unsigned Class = getClass(I.getOperand(0)->getType());
841   if (Class > 2)  // FIXME: Handle longs and others...
842     visitInstruction(I);
843
844   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
845
846   unsigned ValReg = getReg(I.getOperand(0));
847   unsigned AddressReg = getReg(I.getOperand(1));
848   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
849 }
850
851
852 /// visitCastInst - Here we have various kinds of copying with or without
853 /// sign extension going on.
854 void
855 ISel::visitCastInst (CastInst &CI)
856 {
857   const Type *targetType = CI.getType ();
858   Value *operand = CI.getOperand (0);
859   unsigned int operandReg = getReg (operand);
860   const Type *sourceType = operand->getType ();
861   unsigned int destReg = getReg (CI);
862   //
863   // Currently we handle:
864   //
865   // 1) cast * to bool
866   //
867   // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
868   //    cast {short, ushort} to {ushort, short}
869   //    cast {int, uint, ptr} to {int, uint, ptr}
870   //
871   // 3) cast {sbyte, ubyte} to {ushort, short}
872   //    cast {sbyte, ubyte} to {int, uint, ptr}
873   //    cast {short, ushort} to {int, uint, ptr}
874   //
875   // 4) cast {int, uint, ptr} to {short, ushort}
876   //    cast {int, uint, ptr} to {sbyte, ubyte}
877   //    cast {short, ushort} to {sbyte, ubyte}
878
879   // 1) Implement casts to bool by using compare on the operand followed
880   // by set if not zero on the result.
881   if (targetType == Type::BoolTy)
882     {
883       BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
884       BuildMI (BB, X86::SETNEr, 1, destReg);
885       return;
886     }
887
888   // 2) Implement casts between values of the same type class (as determined
889   // by getClass) by using a register-to-register move.
890   unsigned srcClass = getClassB (sourceType);
891   unsigned targClass = getClass (targetType);
892   static const unsigned regRegMove[] = {
893     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
894   };
895   if ((srcClass < cLong) && (targClass < cLong) && (srcClass == targClass))
896     {
897       BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
898       return;
899     }
900   // 3) Handle cast of SMALLER int to LARGER int using a move with sign
901   // extension or zero extension, depending on whether the source type
902   // was signed.
903   if ((srcClass < cLong) && (targClass < cLong) && (srcClass < targClass))
904     {
905       static const unsigned ops[] = {
906         X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
907         X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
908       };
909       unsigned srcSigned = sourceType->isSigned ();
910       BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
911                destReg).addReg (operandReg);
912       return;
913     }
914   // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
915   // followed by a move out of AX or AL.
916   if ((srcClass < cLong) && (targClass < cLong) && (srcClass > targClass))
917     {
918       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
919       BuildMI (BB, regRegMove[srcClass], 1,
920                AReg[srcClass]).addReg (operandReg);
921       BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
922       return;
923     }
924   // Anything we haven't handled already, we can't (yet) handle at all.
925   //
926   // FP to integral casts can be handled with FISTP to store onto the
927   // stack while converting to integer, followed by a MOV to load from
928   // the stack into the result register. Integral to FP casts can be
929   // handled with MOV to store onto the stack, followed by a FILD to
930   // load from the stack while converting to FP. For the moment, I
931   // can't quite get straight in my head how to borrow myself some
932   // stack space and write on it. Otherwise, this would be trivial.
933   visitInstruction (CI);
934 }
935
936 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
937 // returns zero when the input is not exactly a power of two.
938 static unsigned ExactLog2(unsigned Val) {
939   if (Val == 0) return 0;
940   unsigned Count = 0;
941   while (Val != 1) {
942     if (Val & 1) return 0;
943     Val >>= 1;
944     ++Count;
945   }
946   return Count+1;
947 }
948
949 /// visitGetElementPtrInst - I don't know, most programs don't have
950 /// getelementptr instructions, right? That means we can put off
951 /// implementing this, right? Right. This method emits machine
952 /// instructions to perform type-safe pointer arithmetic. I am
953 /// guessing this could be cleaned up somewhat to use fewer temporary
954 /// registers.
955 void
956 ISel::visitGetElementPtrInst (GetElementPtrInst &I)
957 {
958   unsigned outputReg = getReg (I);
959   MachineBasicBlock::iterator MI = BB->end();
960   emitGEPOperation(BB, MI, I.getOperand(0),
961                    I.op_begin()+1, I.op_end(), outputReg);
962 }
963
964 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
965                             MachineBasicBlock::iterator &IP,
966                             Value *Src, User::op_iterator IdxBegin,
967                             User::op_iterator IdxEnd, unsigned TargetReg) {
968   const TargetData &TD = TM.getTargetData();
969   const Type *Ty = Src->getType();
970   unsigned basePtrReg = getReg(Src, MBB, IP);
971
972   // GEPs have zero or more indices; we must perform a struct access
973   // or array access for each one.
974   for (GetElementPtrInst::op_iterator oi = IdxBegin,
975          oe = IdxEnd; oi != oe; ++oi) {
976     Value *idx = *oi;
977     unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
978     if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
979       // It's a struct access.  idx is the index into the structure,
980       // which names the field. This index must have ubyte type.
981       const ConstantUInt *CUI = cast <ConstantUInt> (idx);
982       assert (CUI->getType () == Type::UByteTy
983               && "Funny-looking structure index in GEP");
984       // Use the TargetData structure to pick out what the layout of
985       // the structure is in memory.  Since the structure index must
986       // be constant, we can get its value and use it to find the
987       // right byte offset from the StructLayout class's list of
988       // structure member offsets.
989       unsigned idxValue = CUI->getValue ();
990       unsigned memberOffset =
991         TD.getStructLayout (StTy)->MemberOffsets[idxValue];
992       // Emit an ADD to add memberOffset to the basePtr.
993       BMI(MBB, IP, X86::ADDri32, 2,
994           nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
995       // The next type is the member of the structure selected by the
996       // index.
997       Ty = StTy->getElementTypes ()[idxValue];
998     } else if (const SequentialType *SqTy = cast <SequentialType>(Ty)) {
999       // It's an array or pointer access: [ArraySize x ElementType].
1000
1001       // idx is the index into the array.  Unlike with structure
1002       // indices, we may not know its actual value at code-generation
1003       // time.
1004       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1005
1006       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1007       // must find the size of the pointed-to type (Not coincidentally, the next
1008       // type is the type of the elements in the array).
1009       Ty = SqTy->getElementType();
1010       unsigned elementSize = TD.getTypeSize(Ty);
1011
1012       // If idxReg is a constant, we don't need to perform the multiply!
1013       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1014         if (CSI->isNullValue()) {
1015           BMI(MBB, IP, X86::MOVrr32, 1, nextBasePtrReg).addReg(basePtrReg);
1016         } else {
1017           unsigned Offset = elementSize*CSI->getValue();
1018
1019           BMI(MBB, IP, X86::ADDri32, 2,
1020               nextBasePtrReg).addReg(basePtrReg).addZImm(Offset);
1021         }
1022       } else if (elementSize == 1) {
1023         // If the element size is 1, we don't have to multiply, just add
1024         unsigned idxReg = getReg(idx, MBB, IP);
1025         BMI(MBB, IP, X86::ADDrr32, 2,
1026             nextBasePtrReg).addReg(basePtrReg).addReg(idxReg);
1027       } else {
1028         unsigned idxReg = getReg(idx, MBB, IP);
1029         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1030         if (unsigned Shift = ExactLog2(elementSize)) {
1031           // If the element size is exactly a power of 2, use a shift to get it.
1032
1033           BMI(MBB, IP, X86::SHLir32, 2,
1034               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1035         } else {
1036           // Most general case, emit a multiply...
1037           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1038           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1039         
1040           // Emit a MUL to multiply the register holding the index by
1041           // elementSize, putting the result in OffsetReg.
1042           doMultiply(MBB, IP, OffsetReg, Type::LongTy, idxReg, elementSizeReg);
1043         }
1044         // Emit an ADD to add OffsetReg to the basePtr.
1045         BMI(MBB, IP, X86::ADDrr32, 2,
1046             nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1047       }
1048     }
1049     // Now that we are here, further indices refer to subtypes of this
1050     // one, so we don't need to worry about basePtrReg itself, anymore.
1051     basePtrReg = nextBasePtrReg;
1052   }
1053   // After we have processed all the indices, the result is left in
1054   // basePtrReg.  Move it to the register where we were expected to
1055   // put the answer.  A 32-bit move should do it, because we are in
1056   // ILP32 land.
1057   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
1058 }
1059
1060
1061 /// visitMallocInst - I know that personally, whenever I want to remember
1062 /// something, I have to clear off some space in my brain.
1063 void
1064 ISel::visitMallocInst (MallocInst &I)
1065 {
1066   // We assume that by this point, malloc instructions have been
1067   // lowered to calls, and dlsym will magically find malloc for us.
1068   // So we do not want to see malloc instructions here.
1069   visitInstruction (I);
1070 }
1071
1072
1073 /// visitFreeInst - same story as MallocInst
1074 void
1075 ISel::visitFreeInst (FreeInst &I)
1076 {
1077   // We assume that by this point, free instructions have been
1078   // lowered to calls, and dlsym will magically find free for us.
1079   // So we do not want to see free instructions here.
1080   visitInstruction (I);
1081 }
1082
1083
1084 /// visitAllocaInst - I want some stack space. Come on, man, I said I
1085 /// want some freakin' stack space.
1086 void
1087 ISel::visitAllocaInst (AllocaInst &I)
1088 {
1089   // Find the data size of the alloca inst's getAllocatedType.
1090   const Type *allocatedType = I.getAllocatedType ();
1091   const TargetData &TD = TM.DataLayout;
1092   unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1093   // Keep stack 32-bit aligned.
1094   unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1095   if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1096   // Subtract size from stack pointer, thereby allocating some space.
1097   BuildMI(BB, X86::SUBri32, 2,
1098           X86::ESP).addReg(X86::ESP).addZImm(allocatedTypeWords * 4);
1099   // Put a pointer to the space into the result register, by copying
1100   // the stack pointer.
1101   BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
1102 }
1103     
1104
1105 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1106 /// into a machine code representation is a very simple peep-hole fashion.  The
1107 /// generated code sucks but the implementation is nice and simple.
1108 ///
1109 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1110   return new ISel(TM);
1111 }