1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // This file defines a simple peephole instruction selector for the x86 target
5 //===----------------------------------------------------------------------===//
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Constants.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/SSARegMap.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Support/InstVisitor.h"
25 /// BMI - A special BuildMI variant that takes an iterator to insert the
26 /// instruction at as well as a basic block. This is the version for when you
27 /// have a destination register in mind.
28 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
29 MachineBasicBlock::iterator &I,
30 int Opcode, unsigned NumOperands,
32 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
33 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
34 I = MBB->insert(I, MI)+1;
35 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
38 /// BMI - A special BuildMI variant that takes an iterator to insert the
39 /// instruction at as well as a basic block.
40 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
41 MachineBasicBlock::iterator &I,
42 int Opcode, unsigned NumOperands) {
43 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
44 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
45 I = MBB->insert(I, MI)+1;
46 return MachineInstrBuilder(MI);
51 struct ISel : public FunctionPass, InstVisitor<ISel> {
53 MachineFunction *F; // The function we are compiling into
54 MachineBasicBlock *BB; // The current MBB we are compiling
55 int VarArgsFrameIndex; // FrameIndex for start of varargs area
57 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
59 // MBBMap - Mapping between LLVM BB -> Machine BB
60 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
62 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
64 /// runOnFunction - Top level implementation of instruction selection for
65 /// the entire function.
67 bool runOnFunction(Function &Fn) {
68 F = &MachineFunction::construct(&Fn, TM);
70 // Create all of the machine basic blocks for the function...
71 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
72 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
76 // Copy incoming arguments off of the stack...
77 LoadArgumentsToVirtualRegs(Fn);
79 // Instruction select everything except PHI nodes
82 // Select the PHI nodes
88 // We always build a machine code representation for the function
92 virtual const char *getPassName() const {
93 return "X86 Simple Instruction Selection";
96 /// visitBasicBlock - This method is called when we are visiting a new basic
97 /// block. This simply creates a new MachineBasicBlock to emit code into
98 /// and adds it to the current MachineFunction. Subsequent visit* for
99 /// instructions will be invoked for all instructions in the basic block.
101 void visitBasicBlock(BasicBlock &LLVM_BB) {
102 BB = MBBMap[&LLVM_BB];
105 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
106 /// from the stack into virtual registers.
108 void LoadArgumentsToVirtualRegs(Function &F);
110 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
111 /// because we have to generate our sources into the source basic blocks,
112 /// not the current one.
114 void SelectPHINodes();
116 // Visitation methods for various instructions. These methods simply emit
117 // fixed X86 code for each instruction.
120 // Control flow operators
121 void visitReturnInst(ReturnInst &RI);
122 void visitBranchInst(BranchInst &BI);
127 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
129 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
130 const std::vector<ValueRecord> &Args);
131 void visitCallInst(CallInst &I);
132 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
134 // Arithmetic operators
135 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
136 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
137 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
138 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
139 unsigned DestReg, const Type *DestTy,
140 unsigned Op0Reg, unsigned Op1Reg);
141 void visitMul(BinaryOperator &B);
143 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
144 void visitRem(BinaryOperator &B) { visitDivRem(B); }
145 void visitDivRem(BinaryOperator &B);
148 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
149 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
150 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
152 // Comparison operators...
153 void visitSetCondInst(SetCondInst &I);
154 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
156 // Memory Instructions
157 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
158 MachineBasicBlock::iterator &MBBI,
159 const Type *Ty, unsigned DestReg);
160 void visitLoadInst(LoadInst &I);
161 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
162 void visitStoreInst(StoreInst &I);
163 void visitGetElementPtrInst(GetElementPtrInst &I);
164 void visitAllocaInst(AllocaInst &I);
165 void visitMallocInst(MallocInst &I);
166 void visitFreeInst(FreeInst &I);
169 void visitShiftInst(ShiftInst &I);
170 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
171 void visitCastInst(CastInst &I);
172 void visitVarArgInst(VarArgInst &I);
174 void visitInstruction(Instruction &I) {
175 std::cerr << "Cannot instruction select: " << I;
179 /// promote32 - Make a value 32-bits wide, and put it somewhere.
181 void promote32(unsigned targetReg, const ValueRecord &VR);
183 /// EmitByteSwap - Byteswap SrcReg into DestReg.
185 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
187 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
188 /// constant expression GEP support.
190 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
191 Value *Src, User::op_iterator IdxBegin,
192 User::op_iterator IdxEnd, unsigned TargetReg);
194 /// emitCastOperation - Common code shared between visitCastInst and
195 /// constant expression cast support.
196 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
197 Value *Src, const Type *DestTy, unsigned TargetReg);
199 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
200 /// and constant expression support.
201 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
202 MachineBasicBlock::iterator &IP,
203 Value *Op0, Value *Op1,
204 unsigned OperatorClass, unsigned TargetReg);
206 /// copyConstantToRegister - Output the instructions required to put the
207 /// specified constant into the specified register.
209 void copyConstantToRegister(MachineBasicBlock *MBB,
210 MachineBasicBlock::iterator &MBBI,
211 Constant *C, unsigned Reg);
213 /// makeAnotherReg - This method returns the next register number we haven't
216 /// Long values are handled somewhat specially. They are always allocated
217 /// as pairs of 32 bit integer values. The register number returned is the
218 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
219 /// of the long value.
221 unsigned makeAnotherReg(const Type *Ty) {
222 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
223 const TargetRegisterClass *RC =
224 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
225 // Create the lower part
226 F->getSSARegMap()->createVirtualRegister(RC);
227 // Create the upper part.
228 return F->getSSARegMap()->createVirtualRegister(RC)-1;
231 // Add the mapping of regnumber => reg class to MachineFunction
232 const TargetRegisterClass *RC =
233 TM.getRegisterInfo()->getRegClassForType(Ty);
234 return F->getSSARegMap()->createVirtualRegister(RC);
237 /// getReg - This method turns an LLVM value into a register number. This
238 /// is guaranteed to produce the same register number for a particular value
239 /// every time it is queried.
241 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
242 unsigned getReg(Value *V) {
243 // Just append to the end of the current bb.
244 MachineBasicBlock::iterator It = BB->end();
245 return getReg(V, BB, It);
247 unsigned getReg(Value *V, MachineBasicBlock *MBB,
248 MachineBasicBlock::iterator &IPt) {
249 unsigned &Reg = RegMap[V];
251 Reg = makeAnotherReg(V->getType());
255 // If this operand is a constant, emit the code to copy the constant into
256 // the register here...
258 if (Constant *C = dyn_cast<Constant>(V)) {
259 copyConstantToRegister(MBB, IPt, C, Reg);
260 RegMap.erase(V); // Assign a new name to this constant if ref'd again
261 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
262 // Move the address of the global into the register
263 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
264 RegMap.erase(V); // Assign a new name to this address if ref'd again
272 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
276 cByte, cShort, cInt, cFP, cLong
279 /// getClass - Turn a primitive type into a "class" number which is based on the
280 /// size of the type, and whether or not it is floating point.
282 static inline TypeClass getClass(const Type *Ty) {
283 switch (Ty->getPrimitiveID()) {
284 case Type::SByteTyID:
285 case Type::UByteTyID: return cByte; // Byte operands are class #0
286 case Type::ShortTyID:
287 case Type::UShortTyID: return cShort; // Short operands are class #1
290 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
292 case Type::FloatTyID:
293 case Type::DoubleTyID: return cFP; // Floating Point is #3
296 case Type::ULongTyID: return cLong; // Longs are class #4
298 assert(0 && "Invalid type to getClass!");
299 return cByte; // not reached
303 // getClassB - Just like getClass, but treat boolean values as bytes.
304 static inline TypeClass getClassB(const Type *Ty) {
305 if (Ty == Type::BoolTy) return cByte;
310 /// copyConstantToRegister - Output the instructions required to put the
311 /// specified constant into the specified register.
313 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
314 MachineBasicBlock::iterator &IP,
315 Constant *C, unsigned R) {
316 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
318 switch (CE->getOpcode()) {
319 case Instruction::GetElementPtr:
320 emitGEPOperation(MBB, IP, CE->getOperand(0),
321 CE->op_begin()+1, CE->op_end(), R);
323 case Instruction::Cast:
324 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
327 case Instruction::Xor: ++Class; // FALL THROUGH
328 case Instruction::Or: ++Class; // FALL THROUGH
329 case Instruction::And: ++Class; // FALL THROUGH
330 case Instruction::Sub: ++Class; // FALL THROUGH
331 case Instruction::Add:
332 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
337 std::cerr << "Offending expr: " << C << "\n";
338 assert(0 && "Constant expressions not yet handled!\n");
342 if (C->getType()->isIntegral()) {
343 unsigned Class = getClassB(C->getType());
345 if (Class == cLong) {
346 // Copy the value into the register pair.
347 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
348 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
349 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
353 assert(Class <= cInt && "Type not handled yet!");
355 static const unsigned IntegralOpcodeTab[] = {
356 X86::MOVir8, X86::MOVir16, X86::MOVir32
359 if (C->getType() == Type::BoolTy) {
360 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
362 ConstantInt *CI = cast<ConstantInt>(C);
363 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CI->getRawValue());
365 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
366 double Value = CFP->getValue();
368 BMI(MBB, IP, X86::FLD0, 0, R);
369 else if (Value == +1.0)
370 BMI(MBB, IP, X86::FLD1, 0, R);
372 // Otherwise we need to spill the constant to memory...
373 MachineConstantPool *CP = F->getConstantPool();
374 unsigned CPI = CP->getConstantPoolIndex(CFP);
375 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
378 } else if (isa<ConstantPointerNull>(C)) {
379 // Copy zero (null pointer) to the register.
380 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
381 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
382 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
383 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
385 std::cerr << "Offending constant: " << C << "\n";
386 assert(0 && "Type not handled yet!");
390 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
391 /// the stack into virtual registers.
393 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
394 // Emit instructions to load the arguments... On entry to a function on the
395 // X86, the stack frame looks like this:
397 // [ESP] -- return address
398 // [ESP + 4] -- first argument (leftmost lexically)
399 // [ESP + 8] -- second argument, if first argument is four bytes in size
402 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
403 MachineFrameInfo *MFI = F->getFrameInfo();
405 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
406 unsigned Reg = getReg(*I);
408 int FI; // Frame object index
409 switch (getClassB(I->getType())) {
411 FI = MFI->CreateFixedObject(1, ArgOffset);
412 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
415 FI = MFI->CreateFixedObject(2, ArgOffset);
416 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
419 FI = MFI->CreateFixedObject(4, ArgOffset);
420 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
423 FI = MFI->CreateFixedObject(8, ArgOffset);
424 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
425 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
426 ArgOffset += 4; // longs require 4 additional bytes
430 if (I->getType() == Type::FloatTy) {
431 Opcode = X86::FLDr32;
432 FI = MFI->CreateFixedObject(4, ArgOffset);
434 Opcode = X86::FLDr64;
435 FI = MFI->CreateFixedObject(8, ArgOffset);
436 ArgOffset += 4; // doubles require 4 additional bytes
438 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
441 assert(0 && "Unhandled argument type!");
443 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
446 // If the function takes variable number of arguments, add a frame offset for
447 // the start of the first vararg value... this is used to expand
449 if (Fn.getFunctionType()->isVarArg())
450 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
454 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
455 /// because we have to generate our sources into the source basic blocks, not
458 void ISel::SelectPHINodes() {
459 const TargetInstrInfo &TII = TM.getInstrInfo();
460 const Function &LF = *F->getFunction(); // The LLVM function...
461 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
462 const BasicBlock *BB = I;
463 MachineBasicBlock *MBB = MBBMap[I];
465 // Loop over all of the PHI nodes in the LLVM basic block...
466 unsigned NumPHIs = 0;
467 for (BasicBlock::const_iterator I = BB->begin();
468 PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
470 // Create a new machine instr PHI node, and insert it.
471 unsigned PHIReg = getReg(*PN);
472 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
473 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
475 MachineInstr *LongPhiMI = 0;
476 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
477 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
478 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
481 // PHIValues - Map of blocks to incoming virtual registers. We use this
482 // so that we only initialize one incoming value for a particular block,
483 // even if the block has multiple entries in the PHI node.
485 std::map<MachineBasicBlock*, unsigned> PHIValues;
487 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
488 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
490 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
491 PHIValues.lower_bound(PredMBB);
493 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
494 // We already inserted an initialization of the register for this
495 // predecessor. Recycle it.
496 ValReg = EntryIt->second;
499 // Get the incoming value into a virtual register. If it is not
500 // already available in a virtual register, insert the computation
503 MachineBasicBlock::iterator PI = PredMBB->end();
504 while (PI != PredMBB->begin() &&
505 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
507 ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
509 // Remember that we inserted a value for this PHI for this predecessor
510 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
513 PhiMI->addRegOperand(ValReg);
514 PhiMI->addMachineBasicBlockOperand(PredMBB);
516 LongPhiMI->addRegOperand(ValReg+1);
517 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
524 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
525 // the conditional branch instruction which is the only user of the cc
526 // instruction. This is the case if the conditional branch is the only user of
527 // the setcc, and if the setcc is in the same basic block as the conditional
528 // branch. We also don't handle long arguments below, so we reject them here as
531 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
532 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
533 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
534 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
535 const Type *Ty = SCI->getOperand(0)->getType();
536 if (Ty != Type::LongTy && Ty != Type::ULongTy)
542 // Return a fixed numbering for setcc instructions which does not depend on the
543 // order of the opcodes.
545 static unsigned getSetCCNumber(unsigned Opcode) {
547 default: assert(0 && "Unknown setcc instruction!");
548 case Instruction::SetEQ: return 0;
549 case Instruction::SetNE: return 1;
550 case Instruction::SetLT: return 2;
551 case Instruction::SetGE: return 3;
552 case Instruction::SetGT: return 4;
553 case Instruction::SetLE: return 5;
557 // LLVM -> X86 signed X86 unsigned
558 // ----- ---------- ------------
559 // seteq -> sete sete
560 // setne -> setne setne
561 // setlt -> setl setb
562 // setge -> setge setae
563 // setgt -> setg seta
564 // setle -> setle setbe
565 static const unsigned SetCCOpcodeTab[2][6] = {
566 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
567 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
570 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
572 // The arguments are already supposed to be of the same type.
573 const Type *CompTy = Op0->getType();
574 bool isSigned = CompTy->isSigned();
575 unsigned Class = getClassB(CompTy);
576 unsigned Op0r = getReg(Op0);
578 // Special case handling of: cmp R, i
579 if (Class == cByte || Class == cShort || Class == cInt)
580 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
581 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
583 // Mask off any upper bits of the constant, if there are any...
584 Op1v &= (1ULL << (8 << Class)) - 1;
587 case cByte: BuildMI(BB, X86::CMPri8, 2).addReg(Op0r).addZImm(Op1v);break;
588 case cShort: BuildMI(BB, X86::CMPri16,2).addReg(Op0r).addZImm(Op1v);break;
589 case cInt: BuildMI(BB, X86::CMPri32,2).addReg(Op0r).addZImm(Op1v);break;
591 assert(0 && "Invalid class!");
596 unsigned Op1r = getReg(Op1);
598 default: assert(0 && "Unknown type class!");
599 // Emit: cmp <var1>, <var2> (do the comparison). We can
600 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
603 BuildMI(BB, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
606 BuildMI(BB, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
609 BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
612 BuildMI(BB, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
613 BuildMI(BB, X86::FNSTSWr8, 0);
614 BuildMI(BB, X86::SAHF, 1);
615 isSigned = false; // Compare with unsigned operators
619 if (OpNum < 2) { // seteq, setne
620 unsigned LoTmp = makeAnotherReg(Type::IntTy);
621 unsigned HiTmp = makeAnotherReg(Type::IntTy);
622 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
623 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
624 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
625 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
626 break; // Allow the sete or setne to be generated from flags set by OR
628 // Emit a sequence of code which compares the high and low parts once
629 // each, then uses a conditional move to handle the overflow case. For
630 // example, a setlt for long would generate code like this:
632 // AL = lo(op1) < lo(op2) // Signedness depends on operands
633 // BL = hi(op1) < hi(op2) // Always unsigned comparison
634 // dest = hi(op1) == hi(op2) ? AL : BL;
637 // FIXME: This would be much better if we had hierarchical register
638 // classes! Until then, hardcode registers so that we can deal with their
639 // aliases (because we don't have conditional byte moves).
641 BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
642 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
643 BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
644 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
645 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
646 // NOTE: visitSetCondInst knows that the value is dumped into the BL
647 // register at this point for long values...
655 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
656 /// register, then move it to wherever the result should be.
658 void ISel::visitSetCondInst(SetCondInst &I) {
659 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
661 unsigned OpNum = getSetCCNumber(I.getOpcode());
662 unsigned DestReg = getReg(I);
663 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
666 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
667 // Handle normal comparisons with a setcc instruction...
668 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
670 // Handle long comparisons by copying the value which is already in BL into
671 // the register we want...
672 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
676 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
677 /// operand, in the specified target register.
678 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
679 bool isUnsigned = VR.Ty->isUnsigned();
680 switch (getClassB(VR.Ty)) {
682 // Extend value into target register (8->32)
684 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
686 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
689 // Extend value into target register (16->32)
691 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
693 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
696 // Move value into target register (32->32)
697 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
700 assert(0 && "Unpromotable operand class in promote32");
704 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
705 /// we have the following possibilities:
707 /// ret void: No return value, simply emit a 'ret' instruction
708 /// ret sbyte, ubyte : Extend value into EAX and return
709 /// ret short, ushort: Extend value into EAX and return
710 /// ret int, uint : Move value into EAX and return
711 /// ret pointer : Move value into EAX and return
712 /// ret long, ulong : Move value into EAX/EDX and return
713 /// ret float/double : Top of FP stack
715 void ISel::visitReturnInst(ReturnInst &I) {
716 if (I.getNumOperands() == 0) {
717 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
721 Value *RetVal = I.getOperand(0);
722 unsigned RetReg = getReg(RetVal);
723 switch (getClassB(RetVal->getType())) {
724 case cByte: // integral return values: extend or move into EAX and return
727 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
728 // Declare that EAX is live on exit
729 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
731 case cFP: // Floats & Doubles: Return in ST(0)
732 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
733 // Declare that top-of-stack is live on exit
734 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
737 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
738 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
739 // Declare that EAX & EDX are live on exit
740 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
745 // Emit a 'ret' instruction
746 BuildMI(BB, X86::RET, 0);
749 // getBlockAfter - Return the basic block which occurs lexically after the
751 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
752 Function::iterator I = BB; ++I; // Get iterator to next block
753 return I != BB->getParent()->end() ? &*I : 0;
756 /// visitBranchInst - Handle conditional and unconditional branches here. Note
757 /// that since code layout is frozen at this point, that if we are trying to
758 /// jump to a block that is the immediate successor of the current block, we can
759 /// just make a fall-through (but we don't currently).
761 void ISel::visitBranchInst(BranchInst &BI) {
762 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
764 if (!BI.isConditional()) { // Unconditional branch?
765 if (BI.getSuccessor(0) != NextBB)
766 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
770 // See if we can fold the setcc into the branch itself...
771 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
773 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
774 // computed some other way...
775 unsigned condReg = getReg(BI.getCondition());
776 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
777 if (BI.getSuccessor(1) == NextBB) {
778 if (BI.getSuccessor(0) != NextBB)
779 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
781 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
783 if (BI.getSuccessor(0) != NextBB)
784 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
789 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
790 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
793 // LLVM -> X86 signed X86 unsigned
794 // ----- ---------- ------------
801 static const unsigned OpcodeTab[2][6] = {
802 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
803 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
806 if (BI.getSuccessor(0) != NextBB) {
807 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
808 if (BI.getSuccessor(1) != NextBB)
809 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
811 // Change to the inverse condition...
812 if (BI.getSuccessor(1) != NextBB) {
814 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
820 /// doCall - This emits an abstract call instruction, setting up the arguments
821 /// and the return value as appropriate. For the actual function call itself,
822 /// it inserts the specified CallMI instruction into the stream.
824 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
825 const std::vector<ValueRecord> &Args) {
827 // Count how many bytes are to be pushed on the stack...
828 unsigned NumBytes = 0;
831 for (unsigned i = 0, e = Args.size(); i != e; ++i)
832 switch (getClassB(Args[i].Ty)) {
833 case cByte: case cShort: case cInt:
834 NumBytes += 4; break;
836 NumBytes += 8; break;
838 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
840 default: assert(0 && "Unknown class!");
843 // Adjust the stack pointer for the new arguments...
844 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
846 // Arguments go on the stack in reverse order, as specified by the ABI.
847 unsigned ArgOffset = 0;
848 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
849 unsigned ArgReg = Args[i].Reg;
850 switch (getClassB(Args[i].Ty)) {
853 // Promote arg to 32 bits wide into a temporary register...
854 unsigned R = makeAnotherReg(Type::UIntTy);
855 promote32(R, Args[i]);
856 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
857 X86::ESP, ArgOffset).addReg(R);
861 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
862 X86::ESP, ArgOffset).addReg(ArgReg);
865 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
866 X86::ESP, ArgOffset).addReg(ArgReg);
867 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
868 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
869 ArgOffset += 4; // 8 byte entry, not 4.
873 if (Args[i].Ty == Type::FloatTy) {
874 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
875 X86::ESP, ArgOffset).addReg(ArgReg);
877 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
878 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
879 X86::ESP, ArgOffset).addReg(ArgReg);
880 ArgOffset += 4; // 8 byte entry, not 4.
884 default: assert(0 && "Unknown class!");
889 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
892 BB->push_back(CallMI);
894 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
896 // If there is a return value, scavenge the result from the location the call
899 if (Ret.Ty != Type::VoidTy) {
900 unsigned DestClass = getClassB(Ret.Ty);
905 // Integral results are in %eax, or the appropriate portion
907 static const unsigned regRegMove[] = {
908 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
910 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
911 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
914 case cFP: // Floating-point return values live in %ST(0)
915 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
917 case cLong: // Long values are left in EDX:EAX
918 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
919 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
921 default: assert(0 && "Unknown class!");
927 /// visitCallInst - Push args on stack and do a procedure call instruction.
928 void ISel::visitCallInst(CallInst &CI) {
929 MachineInstr *TheCall;
930 if (Function *F = CI.getCalledFunction()) {
931 // Is it an intrinsic function call?
932 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
933 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
937 // Emit a CALL instruction with PC-relative displacement.
938 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
939 } else { // Emit an indirect call...
940 unsigned Reg = getReg(CI.getCalledValue());
941 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
944 std::vector<ValueRecord> Args;
945 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
946 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
947 CI.getOperand(i)->getType()));
949 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
950 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
953 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
954 unsigned TmpReg1, TmpReg2;
956 case LLVMIntrinsic::va_start:
957 // Get the address of the first vararg value...
958 TmpReg1 = makeAnotherReg(Type::UIntTy);
959 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
960 TmpReg2 = getReg(CI.getOperand(1));
961 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
964 case LLVMIntrinsic::va_end: return; // Noop on X86
965 case LLVMIntrinsic::va_copy:
966 TmpReg1 = getReg(CI.getOperand(2)); // Get existing va_list
967 TmpReg2 = getReg(CI.getOperand(1)); // Get va_list* to store into
968 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
971 case LLVMIntrinsic::longjmp:
972 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("abort", true);
975 case LLVMIntrinsic::setjmp:
976 // Setjmp always returns zero...
977 BuildMI(BB, X86::MOVir32, 1, getReg(CI)).addZImm(0);
979 default: assert(0 && "Unknown intrinsic for X86!");
984 /// visitSimpleBinary - Implement simple binary operators for integral types...
985 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
987 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
988 unsigned DestReg = getReg(B);
989 MachineBasicBlock::iterator MI = BB->end();
990 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
991 OperatorClass, DestReg);
994 /// visitSimpleBinary - Implement simple binary operators for integral types...
995 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
998 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
999 /// and constant expression support.
1000 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
1001 MachineBasicBlock::iterator &IP,
1002 Value *Op0, Value *Op1,
1003 unsigned OperatorClass,unsigned TargetReg){
1004 unsigned Class = getClassB(Op0->getType());
1005 if (!isa<ConstantInt>(Op1) || Class == cLong) {
1006 static const unsigned OpcodeTab[][4] = {
1007 // Arithmetic operators
1008 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
1009 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
1011 // Bitwise operators
1012 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
1013 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
1014 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
1017 bool isLong = false;
1018 if (Class == cLong) {
1020 Class = cInt; // Bottom 32 bits are handled just like ints
1023 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1024 assert(Opcode && "Floating point arguments to logical inst?");
1025 unsigned Op0r = getReg(Op0, BB, IP);
1026 unsigned Op1r = getReg(Op1, BB, IP);
1027 BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
1029 if (isLong) { // Handle the upper 32 bits of long values...
1030 static const unsigned TopTab[] = {
1031 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1033 BMI(BB, IP, TopTab[OperatorClass], 2,
1034 TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
1037 // Special case: op Reg, <const>
1038 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1040 static const unsigned OpcodeTab[][3] = {
1041 // Arithmetic operators
1042 { X86::ADDri8, X86::ADDri16, X86::ADDri32 }, // ADD
1043 { X86::SUBri8, X86::SUBri16, X86::SUBri32 }, // SUB
1045 // Bitwise operators
1046 { X86::ANDri8, X86::ANDri16, X86::ANDri32 }, // AND
1047 { X86:: ORri8, X86:: ORri16, X86:: ORri32 }, // OR
1048 { X86::XORri8, X86::XORri16, X86::XORri32 }, // XOR
1051 assert(Class < 3 && "General code handles 64-bit integer types!");
1052 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1053 unsigned Op0r = getReg(Op0, BB, IP);
1054 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1056 // Mask off any upper bits of the constant, if there are any...
1057 Op1v &= (1ULL << (8 << Class)) - 1;
1058 BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addZImm(Op1v);
1062 /// doMultiply - Emit appropriate instructions to multiply together the
1063 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1064 /// result should be given as DestTy.
1066 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1067 unsigned DestReg, const Type *DestTy,
1068 unsigned op0Reg, unsigned op1Reg) {
1069 unsigned Class = getClass(DestTy);
1071 case cFP: // Floating point multiply
1072 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1076 BMI(BB, MBBI, Class == cInt ? X86::IMULr32 : X86::IMULr16, 2, DestReg)
1077 .addReg(op0Reg).addReg(op1Reg);
1080 // Must use the MUL instruction, which forces use of AL...
1081 BMI(MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1082 BMI(MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1083 BMI(MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1086 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1090 /// visitMul - Multiplies are not simple binary operators because they must deal
1091 /// with the EAX register explicitly.
1093 void ISel::visitMul(BinaryOperator &I) {
1094 unsigned Op0Reg = getReg(I.getOperand(0));
1095 unsigned Op1Reg = getReg(I.getOperand(1));
1096 unsigned DestReg = getReg(I);
1098 // Simple scalar multiply?
1099 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1100 MachineBasicBlock::iterator MBBI = BB->end();
1101 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1103 // Long value. We have to do things the hard way...
1104 // Multiply the two low parts... capturing carry into EDX
1105 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1106 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1108 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1109 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1110 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1112 MachineBasicBlock::iterator MBBI = BB->end();
1113 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1114 BMI(BB, MBBI, X86::IMULr32, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1116 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1117 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1118 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1121 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1122 BMI(BB, MBBI, X86::IMULr32, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1124 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1125 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1130 /// visitDivRem - Handle division and remainder instructions... these
1131 /// instruction both require the same instructions to be generated, they just
1132 /// select the result from a different register. Note that both of these
1133 /// instructions work differently for signed and unsigned operands.
1135 void ISel::visitDivRem(BinaryOperator &I) {
1136 unsigned Class = getClass(I.getType());
1137 unsigned Op0Reg = getReg(I.getOperand(0));
1138 unsigned Op1Reg = getReg(I.getOperand(1));
1139 unsigned ResultReg = getReg(I);
1142 case cFP: // Floating point divide
1143 if (I.getOpcode() == Instruction::Div)
1144 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1145 else { // Floating point remainder...
1146 MachineInstr *TheCall =
1147 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1148 std::vector<ValueRecord> Args;
1149 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1150 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1151 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1155 static const char *FnName[] =
1156 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1158 unsigned NameIdx = I.getType()->isUnsigned()*2;
1159 NameIdx += I.getOpcode() == Instruction::Div;
1160 MachineInstr *TheCall =
1161 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1163 std::vector<ValueRecord> Args;
1164 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1165 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1166 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1169 case cByte: case cShort: case cInt:
1170 break; // Small integerals, handled below...
1171 default: assert(0 && "Unknown class!");
1174 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1175 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1176 static const unsigned SarOpcode[]={ X86::SARir8, X86::SARir16, X86::SARir32 };
1177 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1178 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1180 static const unsigned DivOpcode[][4] = {
1181 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1182 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1185 bool isSigned = I.getType()->isSigned();
1186 unsigned Reg = Regs[Class];
1187 unsigned ExtReg = ExtRegs[Class];
1189 // Put the first operand into one of the A registers...
1190 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1193 // Emit a sign extension instruction...
1194 unsigned ShiftResult = makeAnotherReg(I.getType());
1195 BuildMI(BB, SarOpcode[Class], 2, ShiftResult).addReg(Op0Reg).addZImm(31);
1196 BuildMI(BB, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1198 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1199 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1202 // Emit the appropriate divide or remainder instruction...
1203 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1205 // Figure out which register we want to pick the result out of...
1206 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1208 // Put the result into the destination register...
1209 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1213 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1214 /// for constant immediate shift values, and for constant immediate
1215 /// shift values equal to 1. Even the general case is sort of special,
1216 /// because the shift amount has to be in CL, not just any old register.
1218 void ISel::visitShiftInst(ShiftInst &I) {
1219 unsigned SrcReg = getReg(I.getOperand(0));
1220 unsigned DestReg = getReg(I);
1221 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1222 bool isSigned = I.getType()->isSigned();
1223 unsigned Class = getClass(I.getType());
1225 static const unsigned ConstantOperand[][4] = {
1226 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1227 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1228 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1229 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1232 static const unsigned NonConstantOperand[][4] = {
1233 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1234 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1235 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1236 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1239 // Longs, as usual, are handled specially...
1240 if (Class == cLong) {
1241 // If we have a constant shift, we can generate much more efficient code
1242 // than otherwise...
1244 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1245 unsigned Amount = CUI->getValue();
1247 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1249 BuildMI(BB, Opc[3], 3,
1250 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1251 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1253 BuildMI(BB, Opc[3], 3,
1254 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1255 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1257 } else { // Shifting more than 32 bits
1260 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1261 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1263 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1264 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1265 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1269 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1271 if (!isLeftShift && isSigned) {
1272 // If this is a SHR of a Long, then we need to do funny sign extension
1273 // stuff. TmpReg gets the value to use as the high-part if we are
1274 // shifting more than 32 bits.
1275 BuildMI(BB, X86::SARir32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1277 // Other shifts use a fixed zero value if the shift is more than 32
1279 BuildMI(BB, X86::MOVir32, 1, TmpReg).addZImm(0);
1282 // Initialize CL with the shift amount...
1283 unsigned ShiftAmount = getReg(I.getOperand(1));
1284 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmount);
1286 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1287 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1289 // TmpReg2 = shld inHi, inLo
1290 BuildMI(BB, X86::SHLDrr32, 2, TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1291 // TmpReg3 = shl inLo, CL
1292 BuildMI(BB, X86::SHLrr32, 1, TmpReg3).addReg(SrcReg);
1294 // Set the flags to indicate whether the shift was by more than 32 bits.
1295 BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1297 // DestHi = (>32) ? TmpReg3 : TmpReg2;
1298 BuildMI(BB, X86::CMOVNErr32, 2,
1299 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1300 // DestLo = (>32) ? TmpReg : TmpReg3;
1301 BuildMI(BB, X86::CMOVNErr32, 2, DestReg).addReg(TmpReg3).addReg(TmpReg);
1303 // TmpReg2 = shrd inLo, inHi
1304 BuildMI(BB, X86::SHRDrr32, 2, TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1305 // TmpReg3 = s[ah]r inHi, CL
1306 BuildMI(BB, isSigned ? X86::SARrr32 : X86::SHRrr32, 1, TmpReg3)
1309 // Set the flags to indicate whether the shift was by more than 32 bits.
1310 BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1312 // DestLo = (>32) ? TmpReg3 : TmpReg2;
1313 BuildMI(BB, X86::CMOVNErr32, 2,
1314 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1316 // DestHi = (>32) ? TmpReg : TmpReg3;
1317 BuildMI(BB, X86::CMOVNErr32, 2,
1318 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1324 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1325 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1326 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1328 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1329 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1330 } else { // The shift amount is non-constant.
1331 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1333 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1334 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1339 /// doFPLoad - This method is used to load an FP value from memory using the
1340 /// current endianness. NOTE: This method returns a partially constructed load
1341 /// instruction which needs to have the memory source filled in still.
1343 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1344 MachineBasicBlock::iterator &MBBI,
1345 const Type *Ty, unsigned DestReg) {
1346 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1347 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1349 if (TM.getTargetData().isLittleEndian()) // fast path...
1350 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1352 // If we are big-endian, start by creating an LEA instruction to represent the
1353 // address of the memory location to load from...
1355 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1356 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1358 // Allocate a temporary stack slot to transform the value into...
1359 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1361 // Perform the bswaps 32 bits at a time...
1362 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1363 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1364 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1365 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1366 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1367 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1368 FrameIdx, Offset).addReg(TmpReg2);
1370 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1371 TmpReg1 = makeAnotherReg(Type::UIntTy);
1372 TmpReg2 = makeAnotherReg(Type::UIntTy);
1374 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1375 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1376 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1377 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1380 // Now we can reload the final byteswapped result into the final destination.
1381 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1385 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1387 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1388 // Emit the byte swap instruction...
1391 // No byteswap necessary for 8 bit value...
1392 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1395 // Use the 32 bit bswap instruction to do a 32 bit swap...
1396 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1400 // For 16 bit we have to use an xchg instruction, because there is no
1401 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
1402 // into AX to do the xchg.
1404 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1405 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1406 .addReg(X86::AH, MOTy::UseAndDef);
1407 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1409 default: assert(0 && "Cannot byteswap this class!");
1414 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1415 /// instruction. The load and store instructions are the only place where we
1416 /// need to worry about the memory layout of the target machine.
1418 void ISel::visitLoadInst(LoadInst &I) {
1419 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1420 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1421 unsigned SrcAddrReg = getReg(I.getOperand(0));
1422 unsigned DestReg = getReg(I);
1424 unsigned Class = getClassB(I.getType());
1427 MachineBasicBlock::iterator MBBI = BB->end();
1428 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1431 case cLong: case cInt: case cShort: case cByte:
1432 break; // Integers of various sizes handled below
1433 default: assert(0 && "Unknown memory class!");
1436 // We need to adjust the input pointer if we are emulating a big-endian
1437 // long-pointer target. On these systems, the pointer that we are interested
1438 // in is in the upper part of the eight byte memory image of the pointer. It
1439 // also happens to be byte-swapped, but this will be handled later.
1441 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1442 unsigned R = makeAnotherReg(Type::UIntTy);
1443 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1447 unsigned IReg = DestReg;
1448 if (!isLittleEndian) // If big endian we need an intermediate stage
1449 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1451 static const unsigned Opcode[] = {
1452 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1454 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1456 // Handle long values now...
1457 if (Class == cLong) {
1458 if (isLittleEndian) {
1459 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1461 EmitByteSwap(IReg+1, DestReg, cInt);
1462 unsigned TempReg = makeAnotherReg(Type::IntTy);
1463 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1464 EmitByteSwap(IReg, TempReg, cInt);
1469 if (!isLittleEndian)
1470 EmitByteSwap(IReg, DestReg, Class);
1474 /// doFPStore - This method is used to store an FP value to memory using the
1475 /// current endianness.
1477 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1478 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1479 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1481 if (TM.getTargetData().isLittleEndian()) { // fast path...
1482 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1486 // Allocate a temporary stack slot to transform the value into...
1487 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1488 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1489 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1491 // Store the value into a temporary stack slot...
1492 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1494 // Perform the bswaps 32 bits at a time...
1495 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1496 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1497 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1498 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1499 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1500 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1501 DestAddrReg, Offset).addReg(TmpReg2);
1503 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1504 TmpReg1 = makeAnotherReg(Type::UIntTy);
1505 TmpReg2 = makeAnotherReg(Type::UIntTy);
1507 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1508 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1509 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1510 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1515 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1518 void ISel::visitStoreInst(StoreInst &I) {
1519 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1520 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1521 unsigned ValReg = getReg(I.getOperand(0));
1522 unsigned AddressReg = getReg(I.getOperand(1));
1524 unsigned Class = getClassB(I.getOperand(0)->getType());
1527 if (isLittleEndian) {
1528 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1529 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1530 AddressReg, 4).addReg(ValReg+1);
1532 unsigned T1 = makeAnotherReg(Type::IntTy);
1533 unsigned T2 = makeAnotherReg(Type::IntTy);
1534 EmitByteSwap(T1, ValReg , cInt);
1535 EmitByteSwap(T2, ValReg+1, cInt);
1536 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1537 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1541 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1543 case cInt: case cShort: case cByte:
1544 break; // Integers of various sizes handled below
1545 default: assert(0 && "Unknown memory class!");
1548 if (!isLittleEndian && hasLongPointers &&
1549 isa<PointerType>(I.getOperand(0)->getType())) {
1550 unsigned R = makeAnotherReg(Type::UIntTy);
1551 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1555 if (!isLittleEndian && Class != cByte) {
1556 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1557 EmitByteSwap(R, ValReg, Class);
1561 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1562 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1566 /// visitCastInst - Here we have various kinds of copying with or without
1567 /// sign extension going on.
1568 void ISel::visitCastInst(CastInst &CI) {
1569 Value *Op = CI.getOperand(0);
1570 // If this is a cast from a 32-bit integer to a Long type, and the only uses
1571 // of the case are GEP instructions, then the cast does not need to be
1572 // generated explicitly, it will be folded into the GEP.
1573 if (CI.getType() == Type::LongTy &&
1574 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
1575 bool AllUsesAreGEPs = true;
1576 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
1577 if (!isa<GetElementPtrInst>(*I)) {
1578 AllUsesAreGEPs = false;
1582 // No need to codegen this cast if all users are getelementptr instrs...
1583 if (AllUsesAreGEPs) return;
1586 unsigned DestReg = getReg(CI);
1587 MachineBasicBlock::iterator MI = BB->end();
1588 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
1591 /// emitCastOperation - Common code shared between visitCastInst and
1592 /// constant expression cast support.
1593 void ISel::emitCastOperation(MachineBasicBlock *BB,
1594 MachineBasicBlock::iterator &IP,
1595 Value *Src, const Type *DestTy,
1597 unsigned SrcReg = getReg(Src, BB, IP);
1598 const Type *SrcTy = Src->getType();
1599 unsigned SrcClass = getClassB(SrcTy);
1600 unsigned DestClass = getClassB(DestTy);
1602 // Implement casts to bool by using compare on the operand followed by set if
1603 // not zero on the result.
1604 if (DestTy == Type::BoolTy) {
1607 BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
1610 BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
1613 BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
1616 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1617 BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
1621 assert(0 && "FIXME: implement cast FP to bool");
1625 // If the zero flag is not set, then the value is true, set the byte to
1627 BMI(BB, IP, X86::SETNEr, 1, DestReg);
1631 static const unsigned RegRegMove[] = {
1632 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1635 // Implement casts between values of the same type class (as determined by
1636 // getClass) by using a register-to-register move.
1637 if (SrcClass == DestClass) {
1638 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1639 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1640 } else if (SrcClass == cFP) {
1641 if (SrcTy == Type::FloatTy) { // double -> float
1642 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1643 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1644 } else { // float -> double
1645 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1646 "Unknown cFP member!");
1647 // Truncate from double to float by storing to memory as short, then
1649 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1650 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1651 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1652 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1654 } else if (SrcClass == cLong) {
1655 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1656 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1658 assert(0 && "Cannot handle this type of cast instruction!");
1664 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1665 // or zero extension, depending on whether the source type was signed.
1666 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1667 SrcClass < DestClass) {
1668 bool isLong = DestClass == cLong;
1669 if (isLong) DestClass = cInt;
1671 static const unsigned Opc[][4] = {
1672 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1673 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1676 bool isUnsigned = SrcTy->isUnsigned();
1677 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1678 DestReg).addReg(SrcReg);
1680 if (isLong) { // Handle upper 32 bits as appropriate...
1681 if (isUnsigned) // Zero out top bits...
1682 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1683 else // Sign extend bottom half...
1684 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1689 // Special case long -> int ...
1690 if (SrcClass == cLong && DestClass == cInt) {
1691 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1695 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1696 // move out of AX or AL.
1697 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1698 && SrcClass > DestClass) {
1699 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1700 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1701 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1705 // Handle casts from integer to floating point now...
1706 if (DestClass == cFP) {
1707 // Promote the integer to a type supported by FLD. We do this because there
1708 // are no unsigned FLD instructions, so we must promote an unsigned value to
1709 // a larger signed value, then use FLD on the larger value.
1711 const Type *PromoteType = 0;
1712 unsigned PromoteOpcode;
1713 switch (SrcTy->getPrimitiveID()) {
1714 case Type::BoolTyID:
1715 case Type::SByteTyID:
1716 // We don't have the facilities for directly loading byte sized data from
1717 // memory (even signed). Promote it to 16 bits.
1718 PromoteType = Type::ShortTy;
1719 PromoteOpcode = X86::MOVSXr16r8;
1721 case Type::UByteTyID:
1722 PromoteType = Type::ShortTy;
1723 PromoteOpcode = X86::MOVZXr16r8;
1725 case Type::UShortTyID:
1726 PromoteType = Type::IntTy;
1727 PromoteOpcode = X86::MOVZXr32r16;
1729 case Type::UIntTyID: {
1730 // Make a 64 bit temporary... and zero out the top of it...
1731 unsigned TmpReg = makeAnotherReg(Type::LongTy);
1732 BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1733 BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1734 SrcTy = Type::LongTy;
1739 case Type::ULongTyID:
1740 assert("FIXME: not implemented: cast ulong X to fp type!");
1741 default: // No promotion needed...
1746 unsigned TmpReg = makeAnotherReg(PromoteType);
1747 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1748 1, TmpReg).addReg(SrcReg);
1749 SrcTy = PromoteType;
1750 SrcClass = getClass(PromoteType);
1754 // Spill the integer to memory and reload it from there...
1756 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1758 if (SrcClass == cLong) {
1759 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1760 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1761 FrameIdx, 4).addReg(SrcReg+1);
1763 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1764 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1767 static const unsigned Op2[] =
1768 { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
1769 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1773 // Handle casts from floating point to integer now...
1774 if (SrcClass == cFP) {
1775 // Change the floating point control register to use "round towards zero"
1776 // mode when truncating to an integer value.
1778 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1779 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1781 // Load the old value of the high byte of the control word...
1782 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1783 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1785 // Set the high part to be round to zero...
1786 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1788 // Reload the modified control word now...
1789 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1791 // Restore the memory image of control word to original value
1792 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1793 CWFrameIdx, 1).addReg(HighPartOfCW);
1795 // We don't have the facilities for directly storing byte sized data to
1796 // memory. Promote it to 16 bits. We also must promote unsigned values to
1797 // larger classes because we only have signed FP stores.
1798 unsigned StoreClass = DestClass;
1799 const Type *StoreTy = DestTy;
1800 if (StoreClass == cByte || DestTy->isUnsigned())
1801 switch (StoreClass) {
1802 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1803 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1804 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1805 // The following treatment of cLong may not be perfectly right,
1806 // but it survives chains of casts of the form
1807 // double->ulong->double.
1808 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
1809 default: assert(0 && "Unknown store class!");
1812 // Spill the integer to memory and reload it from there...
1814 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1816 static const unsigned Op1[] =
1817 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1818 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1820 if (DestClass == cLong) {
1821 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1822 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1824 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1825 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1828 // Reload the original control word now...
1829 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1833 // Anything we haven't handled already, we can't (yet) handle at all.
1834 assert(0 && "Unhandled cast instruction!");
1838 /// visitVarArgInst - Implement the va_arg instruction...
1840 void ISel::visitVarArgInst(VarArgInst &I) {
1841 unsigned SrcReg = getReg(I.getOperand(0));
1842 unsigned DestReg = getReg(I);
1844 // Load the va_list into a register...
1845 unsigned VAList = makeAnotherReg(Type::UIntTy);
1846 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1849 switch (I.getType()->getPrimitiveID()) {
1852 assert(0 && "Error: bad type for va_arg instruction!");
1854 case Type::PointerTyID:
1855 case Type::UIntTyID:
1858 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1860 case Type::ULongTyID:
1861 case Type::LongTyID:
1863 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1864 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1866 case Type::DoubleTyID:
1868 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1872 // Increment the VAList pointer...
1873 unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1874 BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1876 // Update the VAList in memory...
1877 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1881 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1882 // returns zero when the input is not exactly a power of two.
1883 static unsigned ExactLog2(unsigned Val) {
1884 if (Val == 0) return 0;
1887 if (Val & 1) return 0;
1894 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1895 unsigned outputReg = getReg(I);
1896 MachineBasicBlock::iterator MI = BB->end();
1897 emitGEPOperation(BB, MI, I.getOperand(0),
1898 I.op_begin()+1, I.op_end(), outputReg);
1901 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1902 MachineBasicBlock::iterator &IP,
1903 Value *Src, User::op_iterator IdxBegin,
1904 User::op_iterator IdxEnd, unsigned TargetReg) {
1905 const TargetData &TD = TM.getTargetData();
1906 const Type *Ty = Src->getType();
1907 unsigned BaseReg = getReg(Src, MBB, IP);
1909 // GEPs have zero or more indices; we must perform a struct access
1910 // or array access for each one.
1911 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1912 oe = IdxEnd; oi != oe; ++oi) {
1914 unsigned NextReg = BaseReg;
1915 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1916 // It's a struct access. idx is the index into the structure,
1917 // which names the field. This index must have ubyte type.
1918 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1919 assert(CUI->getType() == Type::UByteTy
1920 && "Funny-looking structure index in GEP");
1921 // Use the TargetData structure to pick out what the layout of
1922 // the structure is in memory. Since the structure index must
1923 // be constant, we can get its value and use it to find the
1924 // right byte offset from the StructLayout class's list of
1925 // structure member offsets.
1926 unsigned idxValue = CUI->getValue();
1927 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1929 NextReg = makeAnotherReg(Type::UIntTy);
1930 // Emit an ADD to add FieldOff to the basePtr.
1931 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1933 // The next type is the member of the structure selected by the
1935 Ty = StTy->getElementTypes()[idxValue];
1936 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1937 // It's an array or pointer access: [ArraySize x ElementType].
1939 // idx is the index into the array. Unlike with structure
1940 // indices, we may not know its actual value at code-generation
1942 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1944 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
1945 // operand on X86. Handle this case directly now...
1946 if (CastInst *CI = dyn_cast<CastInst>(idx))
1947 if (CI->getOperand(0)->getType() == Type::IntTy ||
1948 CI->getOperand(0)->getType() == Type::UIntTy)
1949 idx = CI->getOperand(0);
1951 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1952 // must find the size of the pointed-to type (Not coincidentally, the next
1953 // type is the type of the elements in the array).
1954 Ty = SqTy->getElementType();
1955 unsigned elementSize = TD.getTypeSize(Ty);
1957 // If idxReg is a constant, we don't need to perform the multiply!
1958 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1959 if (!CSI->isNullValue()) {
1960 unsigned Offset = elementSize*CSI->getValue();
1961 NextReg = makeAnotherReg(Type::UIntTy);
1962 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1964 } else if (elementSize == 1) {
1965 // If the element size is 1, we don't have to multiply, just add
1966 unsigned idxReg = getReg(idx, MBB, IP);
1967 NextReg = makeAnotherReg(Type::UIntTy);
1968 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1970 unsigned idxReg = getReg(idx, MBB, IP);
1971 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1972 if (unsigned Shift = ExactLog2(elementSize)) {
1973 // If the element size is exactly a power of 2, use a shift to get it.
1974 BMI(MBB, IP, X86::SHLir32, 2,
1975 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1977 // Most general case, emit a multiply...
1978 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1979 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1981 // Emit a MUL to multiply the register holding the index by
1982 // elementSize, putting the result in OffsetReg.
1983 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1985 // Emit an ADD to add OffsetReg to the basePtr.
1986 NextReg = makeAnotherReg(Type::UIntTy);
1987 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1990 // Now that we are here, further indices refer to subtypes of this
1991 // one, so we don't need to worry about BaseReg itself, anymore.
1994 // After we have processed all the indices, the result is left in
1995 // BaseReg. Move it to the register where we were expected to
1996 // put the answer. A 32-bit move should do it, because we are in
1998 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2002 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2003 /// frame manager, otherwise do it the hard way.
2005 void ISel::visitAllocaInst(AllocaInst &I) {
2006 // Find the data size of the alloca inst's getAllocatedType.
2007 const Type *Ty = I.getAllocatedType();
2008 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2010 // If this is a fixed size alloca in the entry block for the function,
2011 // statically stack allocate the space.
2013 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2014 if (I.getParent() == I.getParent()->getParent()->begin()) {
2015 TySize *= CUI->getValue(); // Get total allocated size...
2016 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2018 // Create a new stack object using the frame manager...
2019 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2020 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2025 // Create a register to hold the temporary result of multiplying the type size
2026 // constant by the variable amount.
2027 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2028 unsigned SrcReg1 = getReg(I.getArraySize());
2029 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
2030 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
2032 // TotalSizeReg = mul <numelements>, <TypeSize>
2033 MachineBasicBlock::iterator MBBI = BB->end();
2034 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
2036 // AddedSize = add <TotalSizeReg>, 15
2037 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2038 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
2040 // AlignedSize = and <AddedSize>, ~15
2041 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2042 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
2044 // Subtract size from stack pointer, thereby allocating some space.
2045 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2047 // Put a pointer to the space into the result register, by copying
2048 // the stack pointer.
2049 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2051 // Inform the Frame Information that we have just allocated a variable-sized
2053 F->getFrameInfo()->CreateVariableSizedObject();
2056 /// visitMallocInst - Malloc instructions are code generated into direct calls
2057 /// to the library malloc.
2059 void ISel::visitMallocInst(MallocInst &I) {
2060 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2063 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2064 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2066 Arg = makeAnotherReg(Type::UIntTy);
2067 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
2068 unsigned Op1Reg = getReg(I.getOperand(0));
2069 MachineBasicBlock::iterator MBBI = BB->end();
2070 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
2073 std::vector<ValueRecord> Args;
2074 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2075 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2076 1).addExternalSymbol("malloc", true);
2077 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2081 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2084 void ISel::visitFreeInst(FreeInst &I) {
2085 std::vector<ValueRecord> Args;
2086 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
2087 I.getOperand(0)->getType()));
2088 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2089 1).addExternalSymbol("free", true);
2090 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2094 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2095 /// into a machine code representation is a very simple peep-hole fashion. The
2096 /// generated code sucks but the implementation is nice and simple.
2098 Pass *createX86SimpleInstructionSelector(TargetMachine &TM) {
2099 return new ISel(TM);