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/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/Intrinsics.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Target/MRegisterInfo.h"
31 /// BMI - A special BuildMI variant that takes an iterator to insert the
32 /// instruction at as well as a basic block. This is the version for when you
33 /// have a destination register in mind.
34 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
35 MachineBasicBlock::iterator &I,
39 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
40 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
41 I = MBB->insert(I, MI)+1;
42 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
45 /// BMI - A special BuildMI variant that takes an iterator to insert the
46 /// instruction at as well as a basic block.
47 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
48 MachineBasicBlock::iterator &I,
50 unsigned NumOperands) {
51 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
52 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
53 I = MBB->insert(I, MI)+1;
54 return MachineInstrBuilder(MI);
59 struct ISel : public FunctionPass, InstVisitor<ISel> {
61 MachineFunction *F; // The function we are compiling into
62 MachineBasicBlock *BB; // The current MBB we are compiling
63 int VarArgsFrameIndex; // FrameIndex for start of varargs area
65 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
67 // MBBMap - Mapping between LLVM BB -> Machine BB
68 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
70 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
72 /// runOnFunction - Top level implementation of instruction selection for
73 /// the entire function.
75 bool runOnFunction(Function &Fn) {
76 F = &MachineFunction::construct(&Fn, TM);
78 // Create all of the machine basic blocks for the function...
79 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
80 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
84 // Copy incoming arguments off of the stack...
85 LoadArgumentsToVirtualRegs(Fn);
87 // Instruction select everything except PHI nodes
90 // Select the PHI nodes
96 return false; // We never modify the LLVM itself.
99 virtual const char *getPassName() const {
100 return "X86 Simple Instruction Selection";
103 /// visitBasicBlock - This method is called when we are visiting a new basic
104 /// block. This simply creates a new MachineBasicBlock to emit code into
105 /// and adds it to the current MachineFunction. Subsequent visit* for
106 /// instructions will be invoked for all instructions in the basic block.
108 void visitBasicBlock(BasicBlock &LLVM_BB) {
109 BB = MBBMap[&LLVM_BB];
112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
115 void LoadArgumentsToVirtualRegs(Function &F);
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
121 void SelectPHINodes();
123 // Visitation methods for various instructions. These methods simply emit
124 // fixed X86 code for each instruction.
127 // Control flow operators
128 void visitReturnInst(ReturnInst &RI);
129 void visitBranchInst(BranchInst &BI);
134 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
136 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
137 const std::vector<ValueRecord> &Args);
138 void visitCallInst(CallInst &I);
139 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
141 // Arithmetic operators
142 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
143 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
144 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
145 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
146 unsigned DestReg, const Type *DestTy,
147 unsigned Op0Reg, unsigned Op1Reg);
148 void visitMul(BinaryOperator &B);
150 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
151 void visitRem(BinaryOperator &B) { visitDivRem(B); }
152 void visitDivRem(BinaryOperator &B);
155 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
156 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
157 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
159 // Comparison operators...
160 void visitSetCondInst(SetCondInst &I);
161 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
163 // Memory Instructions
164 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
165 MachineBasicBlock::iterator &MBBI,
166 const Type *Ty, unsigned DestReg);
167 void visitLoadInst(LoadInst &I);
168 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
169 void visitStoreInst(StoreInst &I);
170 void visitGetElementPtrInst(GetElementPtrInst &I);
171 void visitAllocaInst(AllocaInst &I);
172 void visitMallocInst(MallocInst &I);
173 void visitFreeInst(FreeInst &I);
176 void visitShiftInst(ShiftInst &I);
177 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
178 void visitCastInst(CastInst &I);
179 void visitVarArgInst(VarArgInst &I);
181 void visitInstruction(Instruction &I) {
182 std::cerr << "Cannot instruction select: " << I;
186 /// promote32 - Make a value 32-bits wide, and put it somewhere.
188 void promote32(unsigned targetReg, const ValueRecord &VR);
190 /// EmitByteSwap - Byteswap SrcReg into DestReg.
192 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
194 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
195 /// constant expression GEP support.
197 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
198 Value *Src, User::op_iterator IdxBegin,
199 User::op_iterator IdxEnd, unsigned TargetReg);
201 /// emitCastOperation - Common code shared between visitCastInst and
202 /// constant expression cast support.
203 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
204 Value *Src, const Type *DestTy, 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)) {
317 if (CE->getOpcode() == Instruction::GetElementPtr) {
318 emitGEPOperation(MBB, IP, CE->getOperand(0),
319 CE->op_begin()+1, CE->op_end(), R);
321 } else if (CE->getOpcode() == Instruction::Cast) {
322 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
326 std::cerr << "Offending expr: " << C << "\n";
327 assert(0 && "Constant expressions not yet handled!\n");
330 if (C->getType()->isIntegral()) {
331 unsigned Class = getClassB(C->getType());
333 if (Class == cLong) {
334 // Copy the value into the register pair.
336 if (C->getType()->isSigned())
337 Val = cast<ConstantSInt>(C)->getValue();
339 Val = cast<ConstantUInt>(C)->getValue();
341 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
342 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
346 assert(Class <= cInt && "Type not handled yet!");
348 static const unsigned IntegralOpcodeTab[] = {
349 X86::MOVir8, X86::MOVir16, X86::MOVir32
352 if (C->getType() == Type::BoolTy) {
353 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
354 } else if (C->getType()->isSigned()) {
355 ConstantSInt *CSI = cast<ConstantSInt>(C);
356 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
358 ConstantUInt *CUI = cast<ConstantUInt>(C);
359 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
361 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
362 double Value = CFP->getValue();
364 BMI(MBB, IP, X86::FLD0, 0, R);
365 else if (Value == +1.0)
366 BMI(MBB, IP, X86::FLD1, 0, R);
368 // Otherwise we need to spill the constant to memory...
369 MachineConstantPool *CP = F->getConstantPool();
370 unsigned CPI = CP->getConstantPoolIndex(CFP);
371 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
374 } else if (isa<ConstantPointerNull>(C)) {
375 // Copy zero (null pointer) to the register.
376 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
377 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
378 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
379 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
381 std::cerr << "Offending constant: " << C << "\n";
382 assert(0 && "Type not handled yet!");
386 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
387 /// the stack into virtual registers.
389 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
390 // Emit instructions to load the arguments... On entry to a function on the
391 // X86, the stack frame looks like this:
393 // [ESP] -- return address
394 // [ESP + 4] -- first argument (leftmost lexically)
395 // [ESP + 8] -- second argument, if first argument is four bytes in size
398 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
399 MachineFrameInfo *MFI = F->getFrameInfo();
401 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
402 unsigned Reg = getReg(*I);
404 int FI; // Frame object index
405 switch (getClassB(I->getType())) {
407 FI = MFI->CreateFixedObject(1, ArgOffset);
408 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
411 FI = MFI->CreateFixedObject(2, ArgOffset);
412 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
415 FI = MFI->CreateFixedObject(4, ArgOffset);
416 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
419 FI = MFI->CreateFixedObject(8, ArgOffset);
420 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
421 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
422 ArgOffset += 4; // longs require 4 additional bytes
426 if (I->getType() == Type::FloatTy) {
427 Opcode = X86::FLDr32;
428 FI = MFI->CreateFixedObject(4, ArgOffset);
430 Opcode = X86::FLDr64;
431 FI = MFI->CreateFixedObject(8, ArgOffset);
432 ArgOffset += 4; // doubles require 4 additional bytes
434 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
437 assert(0 && "Unhandled argument type!");
439 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
442 // If the function takes variable number of arguments, add a frame offset for
443 // the start of the first vararg value... this is used to expand
445 if (Fn.getFunctionType()->isVarArg())
446 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
450 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
451 /// because we have to generate our sources into the source basic blocks, not
454 void ISel::SelectPHINodes() {
455 const TargetInstrInfo &TII = TM.getInstrInfo();
456 const Function &LF = *F->getFunction(); // The LLVM function...
457 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
458 const BasicBlock *BB = I;
459 MachineBasicBlock *MBB = MBBMap[I];
461 // Loop over all of the PHI nodes in the LLVM basic block...
462 unsigned NumPHIs = 0;
463 for (BasicBlock::const_iterator I = BB->begin();
464 PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
466 // Create a new machine instr PHI node, and insert it.
467 unsigned PHIReg = getReg(*PN);
468 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
469 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
471 MachineInstr *LongPhiMI = 0;
472 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
473 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
474 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
477 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
478 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
480 // Get the incoming value into a virtual register. If it is not already
481 // available in a virtual register, insert the computation code into
484 MachineBasicBlock::iterator PI = PredMBB->end();
485 while (PI != PredMBB->begin() &&
486 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
488 unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
489 PhiMI->addRegOperand(ValReg);
490 PhiMI->addMachineBasicBlockOperand(PredMBB);
492 LongPhiMI->addRegOperand(ValReg+1);
493 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
500 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
501 // the conditional branch instruction which is the only user of the cc
502 // instruction. This is the case if the conditional branch is the only user of
503 // the setcc, and if the setcc is in the same basic block as the conditional
504 // branch. We also don't handle long arguments below, so we reject them here as
507 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
508 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
509 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
510 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
511 const Type *Ty = SCI->getOperand(0)->getType();
512 if (Ty != Type::LongTy && Ty != Type::ULongTy)
518 // Return a fixed numbering for setcc instructions which does not depend on the
519 // order of the opcodes.
521 static unsigned getSetCCNumber(unsigned Opcode) {
523 default: assert(0 && "Unknown setcc instruction!");
524 case Instruction::SetEQ: return 0;
525 case Instruction::SetNE: return 1;
526 case Instruction::SetLT: return 2;
527 case Instruction::SetGE: return 3;
528 case Instruction::SetGT: return 4;
529 case Instruction::SetLE: return 5;
533 // LLVM -> X86 signed X86 unsigned
534 // ----- ---------- ------------
535 // seteq -> sete sete
536 // setne -> setne setne
537 // setlt -> setl setb
538 // setge -> setge setae
539 // setgt -> setg seta
540 // setle -> setle setbe
541 static const unsigned SetCCOpcodeTab[2][6] = {
542 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
543 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
546 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
548 // The arguments are already supposed to be of the same type.
549 const Type *CompTy = Op0->getType();
550 bool isSigned = CompTy->isSigned();
551 unsigned reg1 = getReg(Op0);
552 unsigned reg2 = getReg(Op1);
554 unsigned Class = getClassB(CompTy);
556 default: assert(0 && "Unknown type class!");
557 // Emit: cmp <var1>, <var2> (do the comparison). We can
558 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
561 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
564 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
567 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
570 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
571 BuildMI(BB, X86::FNSTSWr8, 0);
572 BuildMI(BB, X86::SAHF, 1);
573 isSigned = false; // Compare with unsigned operators
577 if (OpNum < 2) { // seteq, setne
578 unsigned LoTmp = makeAnotherReg(Type::IntTy);
579 unsigned HiTmp = makeAnotherReg(Type::IntTy);
580 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
581 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
582 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
583 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
584 break; // Allow the sete or setne to be generated from flags set by OR
586 // Emit a sequence of code which compares the high and low parts once
587 // each, then uses a conditional move to handle the overflow case. For
588 // example, a setlt for long would generate code like this:
590 // AL = lo(op1) < lo(op2) // Signedness depends on operands
591 // BL = hi(op1) < hi(op2) // Always unsigned comparison
592 // dest = hi(op1) == hi(op2) ? AL : BL;
595 // FIXME: This would be much better if we had hierarchical register
596 // classes! Until then, hardcode registers so that we can deal with their
597 // aliases (because we don't have conditional byte moves).
599 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
600 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
601 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
602 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
603 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
604 // NOTE: visitSetCondInst knows that the value is dumped into the BL
605 // register at this point for long values...
613 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
614 /// register, then move it to wherever the result should be.
616 void ISel::visitSetCondInst(SetCondInst &I) {
617 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
619 unsigned OpNum = getSetCCNumber(I.getOpcode());
620 unsigned DestReg = getReg(I);
621 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
624 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
625 // Handle normal comparisons with a setcc instruction...
626 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
628 // Handle long comparisons by copying the value which is already in BL into
629 // the register we want...
630 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
634 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
635 /// operand, in the specified target register.
636 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
637 bool isUnsigned = VR.Ty->isUnsigned();
638 switch (getClassB(VR.Ty)) {
640 // Extend value into target register (8->32)
642 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
644 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
647 // Extend value into target register (16->32)
649 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
651 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
654 // Move value into target register (32->32)
655 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
658 assert(0 && "Unpromotable operand class in promote32");
662 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
663 /// we have the following possibilities:
665 /// ret void: No return value, simply emit a 'ret' instruction
666 /// ret sbyte, ubyte : Extend value into EAX and return
667 /// ret short, ushort: Extend value into EAX and return
668 /// ret int, uint : Move value into EAX and return
669 /// ret pointer : Move value into EAX and return
670 /// ret long, ulong : Move value into EAX/EDX and return
671 /// ret float/double : Top of FP stack
673 void ISel::visitReturnInst(ReturnInst &I) {
674 if (I.getNumOperands() == 0) {
675 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
679 Value *RetVal = I.getOperand(0);
680 unsigned RetReg = getReg(RetVal);
681 switch (getClassB(RetVal->getType())) {
682 case cByte: // integral return values: extend or move into EAX and return
685 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
686 // Declare that EAX is live on exit
687 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
689 case cFP: // Floats & Doubles: Return in ST(0)
690 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
691 // Declare that top-of-stack is live on exit
692 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
695 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
696 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
697 // Declare that EAX & EDX are live on exit
698 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
703 // Emit a 'ret' instruction
704 BuildMI(BB, X86::RET, 0);
707 // getBlockAfter - Return the basic block which occurs lexically after the
709 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
710 Function::iterator I = BB; ++I; // Get iterator to next block
711 return I != BB->getParent()->end() ? &*I : 0;
714 /// visitBranchInst - Handle conditional and unconditional branches here. Note
715 /// that since code layout is frozen at this point, that if we are trying to
716 /// jump to a block that is the immediate successor of the current block, we can
717 /// just make a fall-through (but we don't currently).
719 void ISel::visitBranchInst(BranchInst &BI) {
720 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
722 if (!BI.isConditional()) { // Unconditional branch?
723 if (BI.getSuccessor(0) != NextBB)
724 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
728 // See if we can fold the setcc into the branch itself...
729 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
731 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
732 // computed some other way...
733 unsigned condReg = getReg(BI.getCondition());
734 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
735 if (BI.getSuccessor(1) == NextBB) {
736 if (BI.getSuccessor(0) != NextBB)
737 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
739 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
741 if (BI.getSuccessor(0) != NextBB)
742 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
747 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
748 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
751 // LLVM -> X86 signed X86 unsigned
752 // ----- ---------- ------------
759 static const unsigned OpcodeTab[2][6] = {
760 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
761 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
764 if (BI.getSuccessor(0) != NextBB) {
765 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
766 if (BI.getSuccessor(1) != NextBB)
767 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
769 // Change to the inverse condition...
770 if (BI.getSuccessor(1) != NextBB) {
772 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
778 /// doCall - This emits an abstract call instruction, setting up the arguments
779 /// and the return value as appropriate. For the actual function call itself,
780 /// it inserts the specified CallMI instruction into the stream.
782 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
783 const std::vector<ValueRecord> &Args) {
785 // Count how many bytes are to be pushed on the stack...
786 unsigned NumBytes = 0;
789 for (unsigned i = 0, e = Args.size(); i != e; ++i)
790 switch (getClassB(Args[i].Ty)) {
791 case cByte: case cShort: case cInt:
792 NumBytes += 4; break;
794 NumBytes += 8; break;
796 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
798 default: assert(0 && "Unknown class!");
801 // Adjust the stack pointer for the new arguments...
802 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
804 // Arguments go on the stack in reverse order, as specified by the ABI.
805 unsigned ArgOffset = 0;
806 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
807 unsigned ArgReg = Args[i].Reg;
808 switch (getClassB(Args[i].Ty)) {
811 // Promote arg to 32 bits wide into a temporary register...
812 unsigned R = makeAnotherReg(Type::UIntTy);
813 promote32(R, Args[i]);
814 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
815 X86::ESP, ArgOffset).addReg(R);
819 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
820 X86::ESP, ArgOffset).addReg(ArgReg);
823 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
824 X86::ESP, ArgOffset).addReg(ArgReg);
825 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
826 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
827 ArgOffset += 4; // 8 byte entry, not 4.
831 if (Args[i].Ty == Type::FloatTy) {
832 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
833 X86::ESP, ArgOffset).addReg(ArgReg);
835 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
836 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
837 X86::ESP, ArgOffset).addReg(ArgReg);
838 ArgOffset += 4; // 8 byte entry, not 4.
842 default: assert(0 && "Unknown class!");
847 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
850 BB->push_back(CallMI);
852 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
854 // If there is a return value, scavenge the result from the location the call
857 if (Ret.Ty != Type::VoidTy) {
858 unsigned DestClass = getClassB(Ret.Ty);
863 // Integral results are in %eax, or the appropriate portion
865 static const unsigned regRegMove[] = {
866 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
868 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
869 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
872 case cFP: // Floating-point return values live in %ST(0)
873 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
875 case cLong: // Long values are left in EDX:EAX
876 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
877 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
879 default: assert(0 && "Unknown class!");
885 /// visitCallInst - Push args on stack and do a procedure call instruction.
886 void ISel::visitCallInst(CallInst &CI) {
887 MachineInstr *TheCall;
888 if (Function *F = CI.getCalledFunction()) {
889 // Is it an intrinsic function call?
890 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
891 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
895 // Emit a CALL instruction with PC-relative displacement.
896 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
897 } else { // Emit an indirect call...
898 unsigned Reg = getReg(CI.getCalledValue());
899 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
902 std::vector<ValueRecord> Args;
903 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
904 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
905 CI.getOperand(i)->getType()));
907 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
908 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
911 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
912 unsigned TmpReg1, TmpReg2;
914 case LLVMIntrinsic::va_start:
915 // Get the address of the first vararg value...
916 TmpReg1 = makeAnotherReg(Type::UIntTy);
917 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
918 TmpReg2 = getReg(CI.getOperand(1));
919 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
922 case LLVMIntrinsic::va_end: return; // Noop on X86
923 case LLVMIntrinsic::va_copy:
924 TmpReg1 = getReg(CI.getOperand(2)); // Get existing va_list
925 TmpReg2 = getReg(CI.getOperand(1)); // Get va_list* to store into
926 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
929 default: assert(0 && "Unknown intrinsic for X86!");
935 /// visitSimpleBinary - Implement simple binary operators for integral types...
936 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
939 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
940 unsigned Class = getClassB(B.getType());
942 static const unsigned OpcodeTab[][4] = {
943 // Arithmetic operators
944 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
945 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
948 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
949 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
950 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
954 if (Class == cLong) {
956 Class = cInt; // Bottom 32 bits are handled just like ints
959 unsigned Opcode = OpcodeTab[OperatorClass][Class];
960 assert(Opcode && "Floating point arguments to logical inst?");
961 unsigned Op0r = getReg(B.getOperand(0));
962 unsigned Op1r = getReg(B.getOperand(1));
963 unsigned DestReg = getReg(B);
964 BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
966 if (isLong) { // Handle the upper 32 bits of long values...
967 static const unsigned TopTab[] = {
968 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
970 BuildMI(BB, TopTab[OperatorClass], 2,
971 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
975 /// doMultiply - Emit appropriate instructions to multiply together the
976 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
977 /// result should be given as DestTy.
979 /// FIXME: doMultiply should use one of the two address IMUL instructions!
981 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
982 unsigned DestReg, const Type *DestTy,
983 unsigned op0Reg, unsigned op1Reg) {
984 unsigned Class = getClass(DestTy);
986 case cFP: // Floating point multiply
987 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
990 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
993 case cInt: // Small integerals, handled below...
997 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
998 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
999 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1000 unsigned Reg = Regs[Class];
1002 // Emit a MOV to put the first operand into the appropriately-sized
1004 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
1006 // Emit the appropriate multiply instruction.
1007 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
1009 // Emit another MOV to put the result into the destination register.
1010 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
1013 /// visitMul - Multiplies are not simple binary operators because they must deal
1014 /// with the EAX register explicitly.
1016 void ISel::visitMul(BinaryOperator &I) {
1017 unsigned Op0Reg = getReg(I.getOperand(0));
1018 unsigned Op1Reg = getReg(I.getOperand(1));
1019 unsigned DestReg = getReg(I);
1021 // Simple scalar multiply?
1022 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1023 MachineBasicBlock::iterator MBBI = BB->end();
1024 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1026 // Long value. We have to do things the hard way...
1027 // Multiply the two low parts... capturing carry into EDX
1028 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1029 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1031 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1032 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1033 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1035 MachineBasicBlock::iterator MBBI = BB->end();
1036 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1037 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1039 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1040 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1041 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1044 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1045 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1047 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1048 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1053 /// visitDivRem - Handle division and remainder instructions... these
1054 /// instruction both require the same instructions to be generated, they just
1055 /// select the result from a different register. Note that both of these
1056 /// instructions work differently for signed and unsigned operands.
1058 void ISel::visitDivRem(BinaryOperator &I) {
1059 unsigned Class = getClass(I.getType());
1060 unsigned Op0Reg = getReg(I.getOperand(0));
1061 unsigned Op1Reg = getReg(I.getOperand(1));
1062 unsigned ResultReg = getReg(I);
1065 case cFP: // Floating point divide
1066 if (I.getOpcode() == Instruction::Div)
1067 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1068 else { // Floating point remainder...
1069 MachineInstr *TheCall =
1070 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1071 std::vector<ValueRecord> Args;
1072 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1073 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1074 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1078 static const char *FnName[] =
1079 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1081 unsigned NameIdx = I.getType()->isUnsigned()*2;
1082 NameIdx += I.getOpcode() == Instruction::Div;
1083 MachineInstr *TheCall =
1084 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1086 std::vector<ValueRecord> Args;
1087 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1088 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1089 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1092 case cByte: case cShort: case cInt:
1093 break; // Small integerals, handled below...
1094 default: assert(0 && "Unknown class!");
1097 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1098 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1099 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
1100 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1101 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1103 static const unsigned DivOpcode[][4] = {
1104 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1105 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1108 bool isSigned = I.getType()->isSigned();
1109 unsigned Reg = Regs[Class];
1110 unsigned ExtReg = ExtRegs[Class];
1112 // Put the first operand into one of the A registers...
1113 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1116 // Emit a sign extension instruction...
1117 BuildMI(BB, ExtOpcode[Class], 0);
1119 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1120 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1123 // Emit the appropriate divide or remainder instruction...
1124 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1126 // Figure out which register we want to pick the result out of...
1127 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1129 // Put the result into the destination register...
1130 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1134 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1135 /// for constant immediate shift values, and for constant immediate
1136 /// shift values equal to 1. Even the general case is sort of special,
1137 /// because the shift amount has to be in CL, not just any old register.
1139 void ISel::visitShiftInst(ShiftInst &I) {
1140 unsigned SrcReg = getReg(I.getOperand(0));
1141 unsigned DestReg = getReg(I);
1142 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1143 bool isSigned = I.getType()->isSigned();
1144 unsigned Class = getClass(I.getType());
1146 static const unsigned ConstantOperand[][4] = {
1147 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1148 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1149 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1150 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1153 static const unsigned NonConstantOperand[][4] = {
1154 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1155 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1156 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1157 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1160 // Longs, as usual, are handled specially...
1161 if (Class == cLong) {
1162 // If we have a constant shift, we can generate much more efficient code
1163 // than otherwise...
1165 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1166 unsigned Amount = CUI->getValue();
1168 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1170 BuildMI(BB, Opc[3], 3,
1171 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1172 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1174 BuildMI(BB, Opc[3], 3,
1175 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1176 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1178 } else { // Shifting more than 32 bits
1181 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1182 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1184 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1185 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1186 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1190 visitInstruction(I); // FIXME: Implement long shift by non-constant
1195 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1196 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1197 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1199 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1200 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1201 } else { // The shift amount is non-constant.
1202 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1204 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1205 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1210 /// doFPLoad - This method is used to load an FP value from memory using the
1211 /// current endianness. NOTE: This method returns a partially constructed load
1212 /// instruction which needs to have the memory source filled in still.
1214 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1215 MachineBasicBlock::iterator &MBBI,
1216 const Type *Ty, unsigned DestReg) {
1217 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1218 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1220 if (TM.getTargetData().isLittleEndian()) // fast path...
1221 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1223 // If we are big-endian, start by creating an LEA instruction to represent the
1224 // address of the memory location to load from...
1226 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1227 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1229 // Allocate a temporary stack slot to transform the value into...
1230 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1232 // Perform the bswaps 32 bits at a time...
1233 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1234 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1235 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1236 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1237 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1238 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1239 FrameIdx, Offset).addReg(TmpReg2);
1241 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1242 TmpReg1 = makeAnotherReg(Type::UIntTy);
1243 TmpReg2 = makeAnotherReg(Type::UIntTy);
1245 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1246 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1247 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1248 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1251 // Now we can reload the final byteswapped result into the final destination.
1252 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1256 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1258 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1259 // Emit the byte swap instruction...
1262 // No byteswap necessary for 8 bit value...
1263 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1266 // Use the 32 bit bswap instruction to do a 32 bit swap...
1267 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1271 // For 16 bit we have to use an xchg instruction, because there is no
1272 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
1273 // into AX to do the xchg.
1275 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1276 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1277 .addReg(X86::AH, MOTy::UseAndDef);
1278 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1280 default: assert(0 && "Cannot byteswap this class!");
1285 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1286 /// instruction. The load and store instructions are the only place where we
1287 /// need to worry about the memory layout of the target machine.
1289 void ISel::visitLoadInst(LoadInst &I) {
1290 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1291 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1292 unsigned SrcAddrReg = getReg(I.getOperand(0));
1293 unsigned DestReg = getReg(I);
1295 unsigned Class = getClass(I.getType());
1298 MachineBasicBlock::iterator MBBI = BB->end();
1299 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1302 case cLong: case cInt: case cShort: case cByte:
1303 break; // Integers of various sizes handled below
1304 default: assert(0 && "Unknown memory class!");
1307 // We need to adjust the input pointer if we are emulating a big-endian
1308 // long-pointer target. On these systems, the pointer that we are interested
1309 // in is in the upper part of the eight byte memory image of the pointer. It
1310 // also happens to be byte-swapped, but this will be handled later.
1312 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1313 unsigned R = makeAnotherReg(Type::UIntTy);
1314 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1318 unsigned IReg = DestReg;
1319 if (!isLittleEndian) // If big endian we need an intermediate stage
1320 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1322 static const unsigned Opcode[] = {
1323 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1325 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1327 // Handle long values now...
1328 if (Class == cLong) {
1329 if (isLittleEndian) {
1330 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1332 EmitByteSwap(IReg+1, DestReg, cInt);
1333 unsigned TempReg = makeAnotherReg(Type::IntTy);
1334 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1335 EmitByteSwap(IReg, TempReg, cInt);
1340 if (!isLittleEndian)
1341 EmitByteSwap(IReg, DestReg, Class);
1345 /// doFPStore - This method is used to store an FP value to memory using the
1346 /// current endianness.
1348 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1349 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1350 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1352 if (TM.getTargetData().isLittleEndian()) { // fast path...
1353 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1357 // Allocate a temporary stack slot to transform the value into...
1358 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1359 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1360 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1362 // Store the value into a temporary stack slot...
1363 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1365 // Perform the bswaps 32 bits at a time...
1366 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1367 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1368 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1369 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1370 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1371 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1372 DestAddrReg, Offset).addReg(TmpReg2);
1374 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1375 TmpReg1 = makeAnotherReg(Type::UIntTy);
1376 TmpReg2 = makeAnotherReg(Type::UIntTy);
1378 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1379 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1380 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1381 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1386 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1389 void ISel::visitStoreInst(StoreInst &I) {
1390 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1391 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1392 unsigned ValReg = getReg(I.getOperand(0));
1393 unsigned AddressReg = getReg(I.getOperand(1));
1395 unsigned Class = getClass(I.getOperand(0)->getType());
1398 if (isLittleEndian) {
1399 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1400 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1401 AddressReg, 4).addReg(ValReg+1);
1403 unsigned T1 = makeAnotherReg(Type::IntTy);
1404 unsigned T2 = makeAnotherReg(Type::IntTy);
1405 EmitByteSwap(T1, ValReg , cInt);
1406 EmitByteSwap(T2, ValReg+1, cInt);
1407 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1408 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1412 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1414 case cInt: case cShort: case cByte:
1415 break; // Integers of various sizes handled below
1416 default: assert(0 && "Unknown memory class!");
1419 if (!isLittleEndian && hasLongPointers &&
1420 isa<PointerType>(I.getOperand(0)->getType())) {
1421 unsigned R = makeAnotherReg(Type::UIntTy);
1422 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1426 if (!isLittleEndian && Class != cByte) {
1427 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1428 EmitByteSwap(R, ValReg, Class);
1432 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1433 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1437 /// visitCastInst - Here we have various kinds of copying with or without
1438 /// sign extension going on.
1439 void ISel::visitCastInst(CastInst &CI) {
1440 unsigned DestReg = getReg(CI);
1441 MachineBasicBlock::iterator MI = BB->end();
1442 emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1445 /// emitCastOperation - Common code shared between visitCastInst and
1446 /// constant expression cast support.
1447 void ISel::emitCastOperation(MachineBasicBlock *BB,
1448 MachineBasicBlock::iterator &IP,
1449 Value *Src, const Type *DestTy,
1451 unsigned SrcReg = getReg(Src, BB, IP);
1452 const Type *SrcTy = Src->getType();
1453 unsigned SrcClass = getClassB(SrcTy);
1454 unsigned DestClass = getClassB(DestTy);
1456 // Implement casts to bool by using compare on the operand followed by set if
1457 // not zero on the result.
1458 if (DestTy == Type::BoolTy) {
1459 if (SrcClass == cFP || SrcClass == cLong)
1460 abort(); // FIXME: implement cast (long & FP) to bool
1462 BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1463 BMI(BB, IP, X86::SETNEr, 1, DestReg);
1467 static const unsigned RegRegMove[] = {
1468 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1471 // Implement casts between values of the same type class (as determined by
1472 // getClass) by using a register-to-register move.
1473 if (SrcClass == DestClass) {
1474 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1475 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1476 } else if (SrcClass == cFP) {
1477 if (SrcTy == Type::FloatTy) { // double -> float
1478 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1479 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1480 } else { // float -> double
1481 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1482 "Unknown cFP member!");
1483 // Truncate from double to float by storing to memory as short, then
1485 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1486 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1487 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1488 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1490 } else if (SrcClass == cLong) {
1491 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1492 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1499 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1500 // or zero extension, depending on whether the source type was signed.
1501 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1502 SrcClass < DestClass) {
1503 bool isLong = DestClass == cLong;
1504 if (isLong) DestClass = cInt;
1506 static const unsigned Opc[][4] = {
1507 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1508 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1511 bool isUnsigned = SrcTy->isUnsigned();
1512 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1513 DestReg).addReg(SrcReg);
1515 if (isLong) { // Handle upper 32 bits as appropriate...
1516 if (isUnsigned) // Zero out top bits...
1517 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1518 else // Sign extend bottom half...
1519 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1524 // Special case long -> int ...
1525 if (SrcClass == cLong && DestClass == cInt) {
1526 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1530 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1531 // move out of AX or AL.
1532 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1533 && SrcClass > DestClass) {
1534 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1535 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1536 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1540 // Handle casts from integer to floating point now...
1541 if (DestClass == cFP) {
1542 // unsigned int -> load as 64 bit int.
1543 // unsigned long long -> more complex
1544 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
1545 abort(); // don't handle unsigned src yet!
1547 // We don't have the facilities for directly loading byte sized data from
1548 // memory. Promote it to 16 bits.
1549 if (SrcClass == cByte) {
1550 unsigned TmpReg = makeAnotherReg(Type::ShortTy);
1551 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1552 1, TmpReg).addReg(SrcReg);
1553 SrcTy = Type::ShortTy; // Pretend the short is our input now!
1558 // Spill the integer to memory and reload it from there...
1560 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1562 if (SrcClass == cLong) {
1563 if (SrcTy == Type::ULongTy) abort(); // FIXME: Handle ulong -> FP
1564 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1565 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1566 FrameIdx, 4).addReg(SrcReg+1);
1568 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1569 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1572 static const unsigned Op2[] =
1573 { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
1574 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1578 // Handle casts from floating point to integer now...
1579 if (SrcClass == cFP) {
1580 // Change the floating point control register to use "round towards zero"
1581 // mode when truncating to an integer value.
1583 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1584 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1586 // Load the old value of the high byte of the control word...
1587 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1588 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1590 // Set the high part to be round to zero...
1591 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1593 // Reload the modified control word now...
1594 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1596 // Restore the memory image of control word to original value
1597 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1598 CWFrameIdx, 1).addReg(HighPartOfCW);
1600 // We don't have the facilities for directly storing byte sized data to
1601 // memory. Promote it to 16 bits. We also must promote unsigned values to
1602 // larger classes because we only have signed FP stores.
1603 unsigned StoreClass = DestClass;
1604 const Type *StoreTy = DestTy;
1605 if (StoreClass == cByte || DestTy->isUnsigned())
1606 switch (StoreClass) {
1607 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1608 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1609 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1610 case cLong: abort(); // FIXME: unsigned long long -> more complex
1611 default: assert(0 && "Unknown store class!");
1614 // Spill the integer to memory and reload it from there...
1616 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1618 static const unsigned Op1[] =
1619 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1620 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1622 if (DestClass == cLong) {
1623 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1624 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1626 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1627 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1630 // Reload the original control word now...
1631 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1635 // Anything we haven't handled already, we can't (yet) handle at all.
1639 /// visitVarArgInst - Implement the va_arg instruction...
1641 void ISel::visitVarArgInst(VarArgInst &I) {
1642 unsigned SrcReg = getReg(I.getOperand(0));
1643 unsigned DestReg = getReg(I);
1645 // Load the va_list into a register...
1646 unsigned VAList = makeAnotherReg(Type::UIntTy);
1647 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1650 switch (I.getType()->getPrimitiveID()) {
1653 assert(0 && "Error: bad type for va_arg instruction!");
1655 case Type::PointerTyID:
1656 case Type::UIntTyID:
1659 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1661 case Type::ULongTyID:
1662 case Type::LongTyID:
1664 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1665 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1667 case Type::DoubleTyID:
1669 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1673 // Increment the VAList pointer...
1674 unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1675 BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1677 // Update the VAList in memory...
1678 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1682 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1683 // returns zero when the input is not exactly a power of two.
1684 static unsigned ExactLog2(unsigned Val) {
1685 if (Val == 0) return 0;
1688 if (Val & 1) return 0;
1695 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1696 unsigned outputReg = getReg(I);
1697 MachineBasicBlock::iterator MI = BB->end();
1698 emitGEPOperation(BB, MI, I.getOperand(0),
1699 I.op_begin()+1, I.op_end(), outputReg);
1702 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1703 MachineBasicBlock::iterator &IP,
1704 Value *Src, User::op_iterator IdxBegin,
1705 User::op_iterator IdxEnd, unsigned TargetReg) {
1706 const TargetData &TD = TM.getTargetData();
1707 const Type *Ty = Src->getType();
1708 unsigned BaseReg = getReg(Src, MBB, IP);
1710 // GEPs have zero or more indices; we must perform a struct access
1711 // or array access for each one.
1712 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1713 oe = IdxEnd; oi != oe; ++oi) {
1715 unsigned NextReg = BaseReg;
1716 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1717 // It's a struct access. idx is the index into the structure,
1718 // which names the field. This index must have ubyte type.
1719 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1720 assert(CUI->getType() == Type::UByteTy
1721 && "Funny-looking structure index in GEP");
1722 // Use the TargetData structure to pick out what the layout of
1723 // the structure is in memory. Since the structure index must
1724 // be constant, we can get its value and use it to find the
1725 // right byte offset from the StructLayout class's list of
1726 // structure member offsets.
1727 unsigned idxValue = CUI->getValue();
1728 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1730 NextReg = makeAnotherReg(Type::UIntTy);
1731 // Emit an ADD to add FieldOff to the basePtr.
1732 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1734 // The next type is the member of the structure selected by the
1736 Ty = StTy->getElementTypes()[idxValue];
1737 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1738 // It's an array or pointer access: [ArraySize x ElementType].
1740 // idx is the index into the array. Unlike with structure
1741 // indices, we may not know its actual value at code-generation
1743 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1745 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1746 // must find the size of the pointed-to type (Not coincidentally, the next
1747 // type is the type of the elements in the array).
1748 Ty = SqTy->getElementType();
1749 unsigned elementSize = TD.getTypeSize(Ty);
1751 // If idxReg is a constant, we don't need to perform the multiply!
1752 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1753 if (!CSI->isNullValue()) {
1754 unsigned Offset = elementSize*CSI->getValue();
1755 NextReg = makeAnotherReg(Type::UIntTy);
1756 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1758 } else if (elementSize == 1) {
1759 // If the element size is 1, we don't have to multiply, just add
1760 unsigned idxReg = getReg(idx, MBB, IP);
1761 NextReg = makeAnotherReg(Type::UIntTy);
1762 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1764 unsigned idxReg = getReg(idx, MBB, IP);
1765 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1766 if (unsigned Shift = ExactLog2(elementSize)) {
1767 // If the element size is exactly a power of 2, use a shift to get it.
1768 BMI(MBB, IP, X86::SHLir32, 2,
1769 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1771 // Most general case, emit a multiply...
1772 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1773 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1775 // Emit a MUL to multiply the register holding the index by
1776 // elementSize, putting the result in OffsetReg.
1777 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1779 // Emit an ADD to add OffsetReg to the basePtr.
1780 NextReg = makeAnotherReg(Type::UIntTy);
1781 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1784 // Now that we are here, further indices refer to subtypes of this
1785 // one, so we don't need to worry about BaseReg itself, anymore.
1788 // After we have processed all the indices, the result is left in
1789 // BaseReg. Move it to the register where we were expected to
1790 // put the answer. A 32-bit move should do it, because we are in
1792 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1796 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1797 /// frame manager, otherwise do it the hard way.
1799 void ISel::visitAllocaInst(AllocaInst &I) {
1800 // Find the data size of the alloca inst's getAllocatedType.
1801 const Type *Ty = I.getAllocatedType();
1802 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1804 // If this is a fixed size alloca in the entry block for the function,
1805 // statically stack allocate the space.
1807 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1808 if (I.getParent() == I.getParent()->getParent()->begin()) {
1809 TySize *= CUI->getValue(); // Get total allocated size...
1810 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1812 // Create a new stack object using the frame manager...
1813 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1814 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1819 // Create a register to hold the temporary result of multiplying the type size
1820 // constant by the variable amount.
1821 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1822 unsigned SrcReg1 = getReg(I.getArraySize());
1823 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1824 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1826 // TotalSizeReg = mul <numelements>, <TypeSize>
1827 MachineBasicBlock::iterator MBBI = BB->end();
1828 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1830 // AddedSize = add <TotalSizeReg>, 15
1831 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1832 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1834 // AlignedSize = and <AddedSize>, ~15
1835 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1836 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1838 // Subtract size from stack pointer, thereby allocating some space.
1839 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1841 // Put a pointer to the space into the result register, by copying
1842 // the stack pointer.
1843 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1845 // Inform the Frame Information that we have just allocated a variable-sized
1847 F->getFrameInfo()->CreateVariableSizedObject();
1850 /// visitMallocInst - Malloc instructions are code generated into direct calls
1851 /// to the library malloc.
1853 void ISel::visitMallocInst(MallocInst &I) {
1854 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1857 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1858 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1860 Arg = makeAnotherReg(Type::UIntTy);
1861 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1862 unsigned Op1Reg = getReg(I.getOperand(0));
1863 MachineBasicBlock::iterator MBBI = BB->end();
1864 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1869 std::vector<ValueRecord> Args;
1870 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1871 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1872 1).addExternalSymbol("malloc", true);
1873 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1877 /// visitFreeInst - Free instructions are code gen'd to call the free libc
1880 void ISel::visitFreeInst(FreeInst &I) {
1881 std::vector<ValueRecord> Args;
1882 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1883 I.getOperand(0)->getType()));
1884 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1885 1).addExternalSymbol("free", true);
1886 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1890 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1891 /// into a machine code representation is a very simple peep-hole fashion. The
1892 /// generated code sucks but the implementation is nice and simple.
1894 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1895 return new ISel(TM);