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/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/SSARegMap.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Target/MRegisterInfo.h"
30 /// BMI - A special BuildMI variant that takes an iterator to insert the
31 /// instruction at as well as a basic block.
32 /// this is the version for when you have a destination register in mind.
33 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
34 MachineBasicBlock::iterator &I,
38 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
39 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
40 I = MBB->insert(I, MI)+1;
41 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
44 /// BMI - A special BuildMI variant that takes an iterator to insert the
45 /// instruction at as well as a basic block.
46 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
47 MachineBasicBlock::iterator &I,
49 unsigned NumOperands) {
50 assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
51 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
52 I = MBB->insert(I, MI)+1;
53 return MachineInstrBuilder(MI);
58 struct ISel : public FunctionPass, InstVisitor<ISel> {
60 MachineFunction *F; // The function we are compiling into
61 MachineBasicBlock *BB; // The current MBB we are compiling
63 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
65 // MBBMap - Mapping between LLVM BB -> Machine BB
66 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
68 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
70 /// runOnFunction - Top level implementation of instruction selection for
71 /// the entire function.
73 bool runOnFunction(Function &Fn) {
74 F = &MachineFunction::construct(&Fn, TM);
76 // Create all of the machine basic blocks for the function...
77 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
78 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81 LoadArgumentsToVirtualRegs(Fn);
83 // Instruction select everything except PHI nodes
86 // Select the PHI nodes
92 return false; // We never modify the LLVM itself.
95 virtual const char *getPassName() const {
96 return "X86 Simple Instruction Selection";
99 /// visitBasicBlock - This method is called when we are visiting a new basic
100 /// block. This simply creates a new MachineBasicBlock to emit code into
101 /// and adds it to the current MachineFunction. Subsequent visit* for
102 /// instructions will be invoked for all instructions in the basic block.
104 void visitBasicBlock(BasicBlock &LLVM_BB) {
105 BB = MBBMap[&LLVM_BB];
108 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
109 /// from the stack into virtual registers.
111 void LoadArgumentsToVirtualRegs(Function &F);
113 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
114 /// because we have to generate our sources into the source basic blocks,
115 /// not the current one.
117 void SelectPHINodes();
119 // Visitation methods for various instructions. These methods simply emit
120 // fixed X86 code for each instruction.
123 // Control flow operators
124 void visitReturnInst(ReturnInst &RI);
125 void visitBranchInst(BranchInst &BI);
130 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
132 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
133 const std::vector<ValueRecord> &Args);
134 void visitCallInst(CallInst &I);
136 // Arithmetic operators
137 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
138 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
139 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
140 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
141 unsigned DestReg, const Type *DestTy,
142 unsigned Op0Reg, unsigned Op1Reg);
143 void visitMul(BinaryOperator &B);
145 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
146 void visitRem(BinaryOperator &B) { visitDivRem(B); }
147 void visitDivRem(BinaryOperator &B);
150 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
151 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
152 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
154 // Comparison operators...
155 void visitSetCondInst(SetCondInst &I);
156 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
158 // Memory Instructions
159 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
160 MachineBasicBlock::iterator &MBBI,
161 const Type *Ty, unsigned DestReg);
162 void visitLoadInst(LoadInst &I);
163 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
164 void visitStoreInst(StoreInst &I);
165 void visitGetElementPtrInst(GetElementPtrInst &I);
166 void visitAllocaInst(AllocaInst &I);
167 void visitMallocInst(MallocInst &I);
168 void visitFreeInst(FreeInst &I);
171 void visitShiftInst(ShiftInst &I);
172 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
173 void visitCastInst(CastInst &I);
175 void visitInstruction(Instruction &I) {
176 std::cerr << "Cannot instruction select: " << I;
180 /// promote32 - Make a value 32-bits wide, and put it somewhere.
182 void promote32(unsigned targetReg, const ValueRecord &VR);
184 /// EmitByteSwap - Byteswap SrcReg into DestReg.
186 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
188 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
189 /// constant expression GEP support.
191 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
192 Value *Src, User::op_iterator IdxBegin,
193 User::op_iterator IdxEnd, unsigned TargetReg);
195 /// copyConstantToRegister - Output the instructions required to put the
196 /// specified constant into the specified register.
198 void copyConstantToRegister(MachineBasicBlock *MBB,
199 MachineBasicBlock::iterator &MBBI,
200 Constant *C, unsigned Reg);
202 /// makeAnotherReg - This method returns the next register number we haven't
205 /// Long values are handled somewhat specially. They are always allocated
206 /// as pairs of 32 bit integer values. The register number returned is the
207 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
208 /// of the long value.
210 unsigned makeAnotherReg(const Type *Ty) {
211 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
212 const TargetRegisterClass *RC =
213 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
214 // Create the lower part
215 F->getSSARegMap()->createVirtualRegister(RC);
216 // Create the upper part.
217 return F->getSSARegMap()->createVirtualRegister(RC)-1;
220 // Add the mapping of regnumber => reg class to MachineFunction
221 const TargetRegisterClass *RC =
222 TM.getRegisterInfo()->getRegClassForType(Ty);
223 return F->getSSARegMap()->createVirtualRegister(RC);
226 /// getReg - This method turns an LLVM value into a register number. This
227 /// is guaranteed to produce the same register number for a particular value
228 /// every time it is queried.
230 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
231 unsigned getReg(Value *V) {
232 // Just append to the end of the current bb.
233 MachineBasicBlock::iterator It = BB->end();
234 return getReg(V, BB, It);
236 unsigned getReg(Value *V, MachineBasicBlock *MBB,
237 MachineBasicBlock::iterator &IPt) {
238 unsigned &Reg = RegMap[V];
240 Reg = makeAnotherReg(V->getType());
244 // If this operand is a constant, emit the code to copy the constant into
245 // the register here...
247 if (Constant *C = dyn_cast<Constant>(V)) {
248 copyConstantToRegister(MBB, IPt, C, Reg);
249 RegMap.erase(V); // Assign a new name to this constant if ref'd again
250 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
251 // Move the address of the global into the register
252 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
253 RegMap.erase(V); // Assign a new name to this address if ref'd again
261 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
265 cByte, cShort, cInt, cFP, cLong
268 /// getClass - Turn a primitive type into a "class" number which is based on the
269 /// size of the type, and whether or not it is floating point.
271 static inline TypeClass getClass(const Type *Ty) {
272 switch (Ty->getPrimitiveID()) {
273 case Type::SByteTyID:
274 case Type::UByteTyID: return cByte; // Byte operands are class #0
275 case Type::ShortTyID:
276 case Type::UShortTyID: return cShort; // Short operands are class #1
279 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
281 case Type::FloatTyID:
282 case Type::DoubleTyID: return cFP; // Floating Point is #3
285 case Type::ULongTyID: return cLong; // Longs are class #4
287 assert(0 && "Invalid type to getClass!");
288 return cByte; // not reached
292 // getClassB - Just like getClass, but treat boolean values as bytes.
293 static inline TypeClass getClassB(const Type *Ty) {
294 if (Ty == Type::BoolTy) return cByte;
299 /// copyConstantToRegister - Output the instructions required to put the
300 /// specified constant into the specified register.
302 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
303 MachineBasicBlock::iterator &IP,
304 Constant *C, unsigned R) {
305 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
306 if (CE->getOpcode() == Instruction::GetElementPtr) {
307 emitGEPOperation(MBB, IP, CE->getOperand(0),
308 CE->op_begin()+1, CE->op_end(), R);
312 std::cerr << "Offending expr: " << C << "\n";
313 assert(0 && "Constant expressions not yet handled!\n");
316 if (C->getType()->isIntegral()) {
317 unsigned Class = getClassB(C->getType());
319 if (Class == cLong) {
320 // Copy the value into the register pair.
322 if (C->getType()->isSigned())
323 Val = cast<ConstantSInt>(C)->getValue();
325 Val = cast<ConstantUInt>(C)->getValue();
327 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
328 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
332 assert(Class <= cInt && "Type not handled yet!");
334 static const unsigned IntegralOpcodeTab[] = {
335 X86::MOVir8, X86::MOVir16, X86::MOVir32
338 if (C->getType() == Type::BoolTy) {
339 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
340 } else if (C->getType()->isSigned()) {
341 ConstantSInt *CSI = cast<ConstantSInt>(C);
342 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
344 ConstantUInt *CUI = cast<ConstantUInt>(C);
345 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
347 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
348 double Value = CFP->getValue();
350 BMI(MBB, IP, X86::FLD0, 0, R);
351 else if (Value == +1.0)
352 BMI(MBB, IP, X86::FLD1, 0, R);
354 // Otherwise we need to spill the constant to memory...
355 MachineConstantPool *CP = F->getConstantPool();
356 unsigned CPI = CP->getConstantPoolIndex(CFP);
357 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
360 } else if (isa<ConstantPointerNull>(C)) {
361 // Copy zero (null pointer) to the register.
362 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
363 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
364 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
365 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
367 std::cerr << "Offending constant: " << C << "\n";
368 assert(0 && "Type not handled yet!");
372 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
373 /// the stack into virtual registers.
375 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
376 // Emit instructions to load the arguments... On entry to a function on the
377 // X86, the stack frame looks like this:
379 // [ESP] -- return address
380 // [ESP + 4] -- first argument (leftmost lexically)
381 // [ESP + 8] -- second argument, if first argument is four bytes in size
384 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
385 MachineFrameInfo *MFI = F->getFrameInfo();
387 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
388 unsigned Reg = getReg(*I);
390 int FI; // Frame object index
391 switch (getClassB(I->getType())) {
393 FI = MFI->CreateFixedObject(1, ArgOffset);
394 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
397 FI = MFI->CreateFixedObject(2, ArgOffset);
398 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
401 FI = MFI->CreateFixedObject(4, ArgOffset);
402 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
405 FI = MFI->CreateFixedObject(8, ArgOffset);
406 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
407 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
408 ArgOffset += 4; // longs require 4 additional bytes
412 if (I->getType() == Type::FloatTy) {
413 Opcode = X86::FLDr32;
414 FI = MFI->CreateFixedObject(4, ArgOffset);
416 Opcode = X86::FLDr64;
417 FI = MFI->CreateFixedObject(8, ArgOffset);
418 ArgOffset += 4; // doubles require 4 additional bytes
420 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
423 assert(0 && "Unhandled argument type!");
425 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
430 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
431 /// because we have to generate our sources into the source basic blocks, not
434 void ISel::SelectPHINodes() {
435 const TargetInstrInfo &TII = TM.getInstrInfo();
436 const Function &LF = *F->getFunction(); // The LLVM function...
437 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
438 const BasicBlock *BB = I;
439 MachineBasicBlock *MBB = MBBMap[I];
441 // Loop over all of the PHI nodes in the LLVM basic block...
442 unsigned NumPHIs = 0;
443 for (BasicBlock::const_iterator I = BB->begin();
444 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
446 // Create a new machine instr PHI node, and insert it.
447 unsigned PHIReg = getReg(*PN);
448 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
449 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
451 MachineInstr *LongPhiMI = 0;
452 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
453 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
454 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
457 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
458 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
460 // Get the incoming value into a virtual register. If it is not already
461 // available in a virtual register, insert the computation code into
464 MachineBasicBlock::iterator PI = PredMBB->end();
465 while (PI != PredMBB->begin() &&
466 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
468 unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
469 PhiMI->addRegOperand(ValReg);
470 PhiMI->addMachineBasicBlockOperand(PredMBB);
472 LongPhiMI->addRegOperand(ValReg+1);
473 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
480 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
481 // the conditional branch instruction which is the only user of the cc
482 // instruction. This is the case if the conditional branch is the only user of
483 // the setcc, and if the setcc is in the same basic block as the conditional
484 // branch. We also don't handle long arguments below, so we reject them here as
487 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
488 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
489 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
490 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
491 const Type *Ty = SCI->getOperand(0)->getType();
492 if (Ty != Type::LongTy && Ty != Type::ULongTy)
498 // Return a fixed numbering for setcc instructions which does not depend on the
499 // order of the opcodes.
501 static unsigned getSetCCNumber(unsigned Opcode) {
503 default: assert(0 && "Unknown setcc instruction!");
504 case Instruction::SetEQ: return 0;
505 case Instruction::SetNE: return 1;
506 case Instruction::SetLT: return 2;
507 case Instruction::SetGT: return 3;
508 case Instruction::SetLE: return 4;
509 case Instruction::SetGE: return 5;
513 // LLVM -> X86 signed X86 unsigned
514 // ----- ---------- ------------
515 // seteq -> sete sete
516 // setne -> setne setne
517 // setlt -> setl setb
518 // setgt -> setg seta
519 // setle -> setle setbe
520 // setge -> setge setae
521 static const unsigned SetCCOpcodeTab[2][6] = {
522 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
523 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
526 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
528 // The arguments are already supposed to be of the same type.
529 const Type *CompTy = Op0->getType();
530 bool isSigned = CompTy->isSigned();
531 unsigned reg1 = getReg(Op0);
532 unsigned reg2 = getReg(Op1);
534 unsigned Class = getClassB(CompTy);
536 default: assert(0 && "Unknown type class!");
537 // Emit: cmp <var1>, <var2> (do the comparison). We can
538 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
541 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
544 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
547 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
550 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
551 BuildMI(BB, X86::FNSTSWr8, 0);
552 BuildMI(BB, X86::SAHF, 1);
553 isSigned = false; // Compare with unsigned operators
557 if (OpNum < 2) { // seteq, setne
558 unsigned LoTmp = makeAnotherReg(Type::IntTy);
559 unsigned HiTmp = makeAnotherReg(Type::IntTy);
560 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
561 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
562 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
563 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
564 break; // Allow the sete or setne to be generated from flags set by OR
566 // Emit a sequence of code which compares the high and low parts once
567 // each, then uses a conditional move to handle the overflow case. For
568 // example, a setlt for long would generate code like this:
570 // AL = lo(op1) < lo(op2) // Signedness depends on operands
571 // BL = hi(op1) < hi(op2) // Always unsigned comparison
572 // dest = hi(op1) == hi(op2) ? AL : BL;
575 // FIXME: This would be much better if we had hierarchical register
576 // classes! Until then, hardcode registers so that we can deal with their
577 // aliases (because we don't have conditional byte moves).
579 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
580 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
581 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
582 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
583 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
584 // NOTE: visitSetCondInst knows that the value is dumped into the BL
585 // register at this point for long values...
593 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
594 /// register, then move it to wherever the result should be.
596 void ISel::visitSetCondInst(SetCondInst &I) {
597 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
599 unsigned OpNum = getSetCCNumber(I.getOpcode());
600 unsigned DestReg = getReg(I);
601 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
604 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
605 // Handle normal comparisons with a setcc instruction...
606 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
608 // Handle long comparisons by copying the value which is already in BL into
609 // the register we want...
610 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
614 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
615 /// operand, in the specified target register.
616 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
617 bool isUnsigned = VR.Ty->isUnsigned();
618 switch (getClassB(VR.Ty)) {
620 // Extend value into target register (8->32)
622 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
624 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
627 // Extend value into target register (16->32)
629 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
631 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
634 // Move value into target register (32->32)
635 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
638 assert(0 && "Unpromotable operand class in promote32");
642 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
643 /// we have the following possibilities:
645 /// ret void: No return value, simply emit a 'ret' instruction
646 /// ret sbyte, ubyte : Extend value into EAX and return
647 /// ret short, ushort: Extend value into EAX and return
648 /// ret int, uint : Move value into EAX and return
649 /// ret pointer : Move value into EAX and return
650 /// ret long, ulong : Move value into EAX/EDX and return
651 /// ret float/double : Top of FP stack
653 void ISel::visitReturnInst(ReturnInst &I) {
654 if (I.getNumOperands() == 0) {
655 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
659 Value *RetVal = I.getOperand(0);
660 unsigned RetReg = getReg(RetVal);
661 switch (getClassB(RetVal->getType())) {
662 case cByte: // integral return values: extend or move into EAX and return
665 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
667 case cFP: // Floats & Doubles: Return in ST(0)
668 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
671 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
672 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
677 // Emit a 'ret' instruction
678 BuildMI(BB, X86::RET, 0);
681 /// visitBranchInst - Handle conditional and unconditional branches here. Note
682 /// that since code layout is frozen at this point, that if we are trying to
683 /// jump to a block that is the immediate successor of the current block, we can
684 /// just make a fall-through (but we don't currently).
686 void ISel::visitBranchInst(BranchInst &BI) {
687 if (!BI.isConditional()) {
688 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
692 // See if we can fold the setcc into the branch itself...
693 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
695 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
696 // computed some other way...
697 unsigned condReg = getReg(BI.getCondition());
698 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
699 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
700 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
704 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
705 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
708 // LLVM -> X86 signed X86 unsigned
709 // ----- ---------- ------------
716 static const unsigned OpcodeTab[2][6] = {
717 { X86::JE, X86::JNE, X86::JB, X86::JA, X86::JBE, X86::JAE },
718 { X86::JE, X86::JNE, X86::JL, X86::JG, X86::JLE, X86::JGE },
721 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
722 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
726 /// doCall - This emits an abstract call instruction, setting up the arguments
727 /// and the return value as appropriate. For the actual function call itself,
728 /// it inserts the specified CallMI instruction into the stream.
730 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
731 const std::vector<ValueRecord> &Args) {
733 // Count how many bytes are to be pushed on the stack...
734 unsigned NumBytes = 0;
737 for (unsigned i = 0, e = Args.size(); i != e; ++i)
738 switch (getClassB(Args[i].Ty)) {
739 case cByte: case cShort: case cInt:
740 NumBytes += 4; break;
742 NumBytes += 8; break;
744 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
746 default: assert(0 && "Unknown class!");
749 // Adjust the stack pointer for the new arguments...
750 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
752 // Arguments go on the stack in reverse order, as specified by the ABI.
753 unsigned ArgOffset = 0;
754 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
755 unsigned ArgReg = Args[i].Reg;
756 switch (getClassB(Args[i].Ty)) {
759 // Promote arg to 32 bits wide into a temporary register...
760 unsigned R = makeAnotherReg(Type::UIntTy);
761 promote32(R, Args[i]);
762 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
763 X86::ESP, ArgOffset).addReg(R);
767 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
768 X86::ESP, ArgOffset).addReg(ArgReg);
771 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
772 X86::ESP, ArgOffset).addReg(ArgReg);
773 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
774 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
775 ArgOffset += 4; // 8 byte entry, not 4.
779 if (Args[i].Ty == Type::FloatTy) {
780 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
781 X86::ESP, ArgOffset).addReg(ArgReg);
783 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
784 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
785 X86::ESP, ArgOffset).addReg(ArgReg);
786 ArgOffset += 4; // 8 byte entry, not 4.
790 default: assert(0 && "Unknown class!");
795 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
798 BB->push_back(CallMI);
800 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
802 // If there is a return value, scavenge the result from the location the call
805 if (Ret.Ty != Type::VoidTy) {
806 unsigned DestClass = getClassB(Ret.Ty);
811 // Integral results are in %eax, or the appropriate portion
813 static const unsigned regRegMove[] = {
814 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
816 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
817 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
820 case cFP: // Floating-point return values live in %ST(0)
821 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
823 case cLong: // Long values are left in EDX:EAX
824 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
825 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
827 default: assert(0 && "Unknown class!");
833 /// visitCallInst - Push args on stack and do a procedure call instruction.
834 void ISel::visitCallInst(CallInst &CI) {
835 MachineInstr *TheCall;
836 if (Function *F = CI.getCalledFunction()) {
837 // Emit a CALL instruction with PC-relative displacement.
838 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
839 } else { // Emit an indirect call...
840 unsigned Reg = getReg(CI.getCalledValue());
841 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
844 std::vector<ValueRecord> Args;
845 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
846 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
847 CI.getOperand(i)->getType()));
849 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
850 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
854 /// visitSimpleBinary - Implement simple binary operators for integral types...
855 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
858 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
859 unsigned Class = getClassB(B.getType());
861 static const unsigned OpcodeTab[][4] = {
862 // Arithmetic operators
863 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
864 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
867 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
868 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
869 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
873 if (Class == cLong) {
875 Class = cInt; // Bottom 32 bits are handled just like ints
878 unsigned Opcode = OpcodeTab[OperatorClass][Class];
879 assert(Opcode && "Floating point arguments to logical inst?");
880 unsigned Op0r = getReg(B.getOperand(0));
881 unsigned Op1r = getReg(B.getOperand(1));
882 unsigned DestReg = getReg(B);
883 BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
885 if (isLong) { // Handle the upper 32 bits of long values...
886 static const unsigned TopTab[] = {
887 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
889 BuildMI(BB, TopTab[OperatorClass], 2,
890 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
894 /// doMultiply - Emit appropriate instructions to multiply together the
895 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
896 /// result should be given as DestTy.
898 /// FIXME: doMultiply should use one of the two address IMUL instructions!
900 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
901 unsigned DestReg, const Type *DestTy,
902 unsigned op0Reg, unsigned op1Reg) {
903 unsigned Class = getClass(DestTy);
905 case cFP: // Floating point multiply
906 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
909 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
912 case cInt: // Small integerals, handled below...
916 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
917 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
918 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
919 unsigned Reg = Regs[Class];
921 // Emit a MOV to put the first operand into the appropriately-sized
923 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
925 // Emit the appropriate multiply instruction.
926 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
928 // Emit another MOV to put the result into the destination register.
929 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
932 /// visitMul - Multiplies are not simple binary operators because they must deal
933 /// with the EAX register explicitly.
935 void ISel::visitMul(BinaryOperator &I) {
936 unsigned Op0Reg = getReg(I.getOperand(0));
937 unsigned Op1Reg = getReg(I.getOperand(1));
938 unsigned DestReg = getReg(I);
940 // Simple scalar multiply?
941 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
942 MachineBasicBlock::iterator MBBI = BB->end();
943 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
945 // Long value. We have to do things the hard way...
946 // Multiply the two low parts... capturing carry into EDX
947 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
948 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
950 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
951 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
952 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
954 MachineBasicBlock::iterator MBBI = BB->end();
955 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
956 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
958 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
959 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
960 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
963 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
964 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
966 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
967 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
972 /// visitDivRem - Handle division and remainder instructions... these
973 /// instruction both require the same instructions to be generated, they just
974 /// select the result from a different register. Note that both of these
975 /// instructions work differently for signed and unsigned operands.
977 void ISel::visitDivRem(BinaryOperator &I) {
978 unsigned Class = getClass(I.getType());
979 unsigned Op0Reg = getReg(I.getOperand(0));
980 unsigned Op1Reg = getReg(I.getOperand(1));
981 unsigned ResultReg = getReg(I);
984 case cFP: // Floating point divide
985 if (I.getOpcode() == Instruction::Div)
986 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
987 else { // Floating point remainder...
988 MachineInstr *TheCall =
989 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
990 std::vector<ValueRecord> Args;
991 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
992 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
993 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
997 static const char *FnName[] =
998 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1000 unsigned NameIdx = I.getType()->isUnsigned()*2;
1001 NameIdx += I.getOpcode() == Instruction::Div;
1002 MachineInstr *TheCall =
1003 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1005 std::vector<ValueRecord> Args;
1006 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1007 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1008 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1011 case cByte: case cShort: case cInt:
1012 break; // Small integerals, handled below...
1013 default: assert(0 && "Unknown class!");
1016 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1017 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1018 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
1019 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1020 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1022 static const unsigned DivOpcode[][4] = {
1023 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1024 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1027 bool isSigned = I.getType()->isSigned();
1028 unsigned Reg = Regs[Class];
1029 unsigned ExtReg = ExtRegs[Class];
1031 // Put the first operand into one of the A registers...
1032 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1035 // Emit a sign extension instruction...
1036 BuildMI(BB, ExtOpcode[Class], 0);
1038 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1039 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1042 // Emit the appropriate divide or remainder instruction...
1043 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1045 // Figure out which register we want to pick the result out of...
1046 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1048 // Put the result into the destination register...
1049 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1053 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1054 /// for constant immediate shift values, and for constant immediate
1055 /// shift values equal to 1. Even the general case is sort of special,
1056 /// because the shift amount has to be in CL, not just any old register.
1058 void ISel::visitShiftInst(ShiftInst &I) {
1059 unsigned SrcReg = getReg(I.getOperand(0));
1060 unsigned DestReg = getReg(I);
1061 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1062 bool isSigned = I.getType()->isSigned();
1063 unsigned Class = getClass(I.getType());
1065 static const unsigned ConstantOperand[][4] = {
1066 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1067 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1068 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1069 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1072 static const unsigned NonConstantOperand[][4] = {
1073 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1074 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1075 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1076 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1079 // Longs, as usual, are handled specially...
1080 if (Class == cLong) {
1081 // If we have a constant shift, we can generate much more efficient code
1082 // than otherwise...
1084 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1085 unsigned Amount = CUI->getValue();
1087 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1089 BuildMI(BB, Opc[3], 3,
1090 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1091 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1093 BuildMI(BB, Opc[3], 3,
1094 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1095 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1097 } else { // Shifting more than 32 bits
1100 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1101 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1103 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1104 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1105 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1109 visitInstruction(I); // FIXME: Implement long shift by non-constant
1114 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1115 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1116 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1118 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1119 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1120 } else { // The shift amount is non-constant.
1121 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1123 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1124 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1129 /// doFPLoad - This method is used to load an FP value from memory using the
1130 /// current endianness. NOTE: This method returns a partially constructed load
1131 /// instruction which needs to have the memory source filled in still.
1133 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1134 MachineBasicBlock::iterator &MBBI,
1135 const Type *Ty, unsigned DestReg) {
1136 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1137 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1139 if (TM.getTargetData().isLittleEndian()) // fast path...
1140 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1142 // If we are big-endian, start by creating an LEA instruction to represent the
1143 // address of the memory location to load from...
1145 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1146 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1148 // Allocate a temporary stack slot to transform the value into...
1149 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1151 // Perform the bswaps 32 bits at a time...
1152 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1153 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1154 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1155 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1156 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1157 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1158 FrameIdx, Offset).addReg(TmpReg2);
1160 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1161 TmpReg1 = makeAnotherReg(Type::UIntTy);
1162 TmpReg2 = makeAnotherReg(Type::UIntTy);
1164 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1165 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1166 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1167 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1170 // Now we can reload the final byteswapped result into the final destination.
1171 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1175 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1177 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1178 // Emit the byte swap instruction...
1181 // No byteswap neccesary for 8 bit value...
1182 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1185 // Use the 32 bit bswap instruction to do a 32 bit swap...
1186 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1190 // For 16 bit we have to use an xchg instruction, because there is no
1191 // 16-bit bswap. XCHG is neccesarily not in SSA form, so we force things
1192 // into AX to do the xchg.
1194 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1195 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1196 .addReg(X86::AH, MOTy::UseAndDef);
1197 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1199 default: assert(0 && "Cannot byteswap this class!");
1204 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1205 /// instruction. The load and store instructions are the only place where we
1206 /// need to worry about the memory layout of the target machine.
1208 void ISel::visitLoadInst(LoadInst &I) {
1209 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1210 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1211 unsigned SrcAddrReg = getReg(I.getOperand(0));
1212 unsigned DestReg = getReg(I);
1214 unsigned Class = getClass(I.getType());
1217 MachineBasicBlock::iterator MBBI = BB->end();
1218 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1221 case cLong: case cInt: case cShort: case cByte:
1222 break; // Integers of various sizes handled below
1223 default: assert(0 && "Unknown memory class!");
1226 // We need to adjust the input pointer if we are emulating a big-endian
1227 // long-pointer target. On these systems, the pointer that we are interested
1228 // in is in the upper part of the eight byte memory image of the pointer. It
1229 // also happens to be byte-swapped, but this will be handled later.
1231 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1232 unsigned R = makeAnotherReg(Type::UIntTy);
1233 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1237 unsigned IReg = DestReg;
1238 if (!isLittleEndian) // If big endian we need an intermediate stage
1239 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1241 static const unsigned Opcode[] = {
1242 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1244 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1246 // Handle long values now...
1247 if (Class == cLong) {
1248 if (isLittleEndian) {
1249 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1251 EmitByteSwap(IReg+1, DestReg, cInt);
1252 unsigned TempReg = makeAnotherReg(Type::IntTy);
1253 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1254 EmitByteSwap(IReg, TempReg, cInt);
1259 if (!isLittleEndian)
1260 EmitByteSwap(IReg, DestReg, Class);
1264 /// doFPStore - This method is used to store an FP value to memory using the
1265 /// current endianness.
1267 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1268 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1269 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1271 if (TM.getTargetData().isLittleEndian()) { // fast path...
1272 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1276 // Allocate a temporary stack slot to transform the value into...
1277 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1278 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1279 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1281 // Store the value into a temporary stack slot...
1282 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1284 // Perform the bswaps 32 bits at a time...
1285 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1286 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1287 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1288 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1289 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1290 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1291 DestAddrReg, Offset).addReg(TmpReg2);
1293 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1294 TmpReg1 = makeAnotherReg(Type::UIntTy);
1295 TmpReg2 = makeAnotherReg(Type::UIntTy);
1297 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1298 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1299 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1300 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1305 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1308 void ISel::visitStoreInst(StoreInst &I) {
1309 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1310 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1311 unsigned ValReg = getReg(I.getOperand(0));
1312 unsigned AddressReg = getReg(I.getOperand(1));
1314 unsigned Class = getClass(I.getOperand(0)->getType());
1317 if (isLittleEndian) {
1318 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1319 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1320 AddressReg, 4).addReg(ValReg+1);
1322 unsigned T1 = makeAnotherReg(Type::IntTy);
1323 unsigned T2 = makeAnotherReg(Type::IntTy);
1324 EmitByteSwap(T1, ValReg , cInt);
1325 EmitByteSwap(T2, ValReg+1, cInt);
1326 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1327 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1331 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1333 case cInt: case cShort: case cByte:
1334 break; // Integers of various sizes handled below
1335 default: assert(0 && "Unknown memory class!");
1338 if (!isLittleEndian && hasLongPointers &&
1339 isa<PointerType>(I.getOperand(0)->getType())) {
1340 unsigned R = makeAnotherReg(Type::UIntTy);
1341 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1345 if (!isLittleEndian && Class != cByte) {
1346 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1347 EmitByteSwap(R, ValReg, Class);
1351 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1352 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1356 /// visitCastInst - Here we have various kinds of copying with or without
1357 /// sign extension going on.
1358 void ISel::visitCastInst(CastInst &CI) {
1359 const Type *DestTy = CI.getType();
1360 Value *Src = CI.getOperand(0);
1361 unsigned SrcReg = getReg(Src);
1362 const Type *SrcTy = Src->getType();
1363 unsigned SrcClass = getClassB(SrcTy);
1364 unsigned DestReg = getReg(CI);
1365 unsigned DestClass = getClassB(DestTy);
1367 // Implement casts to bool by using compare on the operand followed by set if
1368 // not zero on the result.
1369 if (DestTy == Type::BoolTy) {
1370 if (SrcClass == cFP || SrcClass == cLong)
1371 visitInstruction(CI);
1373 BuildMI(BB, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1374 BuildMI(BB, X86::SETNEr, 1, DestReg);
1378 static const unsigned RegRegMove[] = {
1379 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1382 // Implement casts between values of the same type class (as determined by
1383 // getClass) by using a register-to-register move.
1384 if (SrcClass == DestClass) {
1385 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1386 BuildMI(BB, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1387 } else if (SrcClass == cFP) {
1388 if (SrcTy == Type::FloatTy) { // double -> float
1389 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1390 BuildMI(BB, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1391 } else { // float -> double
1392 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1393 "Unknown cFP member!");
1394 // Truncate from double to float by storing to memory as short, then
1396 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1397 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1398 addFrameReference(BuildMI(BB, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1399 addFrameReference(BuildMI(BB, X86::FLDr32, 5, DestReg), FrameIdx);
1401 } else if (SrcClass == cLong) {
1402 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1403 BuildMI(BB, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1405 visitInstruction(CI);
1410 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1411 // or zero extension, depending on whether the source type was signed.
1412 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1413 SrcClass < DestClass) {
1414 bool isLong = DestClass == cLong;
1415 if (isLong) DestClass = cInt;
1417 static const unsigned Opc[][4] = {
1418 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1419 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1422 bool isUnsigned = SrcTy->isUnsigned();
1423 BuildMI(BB, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1424 DestReg).addReg(SrcReg);
1426 if (isLong) { // Handle upper 32 bits as appropriate...
1427 if (isUnsigned) // Zero out top bits...
1428 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1429 else // Sign extend bottom half...
1430 BuildMI(BB, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1435 // Special case long -> int ...
1436 if (SrcClass == cLong && DestClass == cInt) {
1437 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1441 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1442 // move out of AX or AL.
1443 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1444 && SrcClass > DestClass) {
1445 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1446 BuildMI(BB, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1447 BuildMI(BB, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1451 // Handle casts from integer to floating point now...
1452 if (DestClass == cFP) {
1453 // unsigned int -> load as 64 bit int.
1454 // unsigned long long -> more complex
1455 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
1456 visitInstruction(CI); // don't handle unsigned src yet!
1458 // We don't have the facilities for directly loading byte sized data from
1459 // memory. Promote it to 16 bits.
1460 if (SrcClass == cByte) {
1461 unsigned TmpReg = makeAnotherReg(Type::ShortTy);
1462 BuildMI(BB, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1463 1, TmpReg).addReg(SrcReg);
1464 SrcTy = Type::ShortTy; // Pretend the short is our input now!
1469 // Spill the integer to memory and reload it from there...
1471 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1473 if (SrcClass == cLong) {
1474 if (SrcTy == Type::ULongTy) visitInstruction(CI);
1475 addFrameReference(BuildMI(BB, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1476 addFrameReference(BuildMI(BB, X86::MOVrm32, 5),
1477 FrameIdx, 4).addReg(SrcReg+1);
1479 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1480 addFrameReference(BuildMI(BB, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1483 static const unsigned Op2[] =
1484 { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
1485 addFrameReference(BuildMI(BB, Op2[SrcClass], 5, DestReg), FrameIdx);
1489 // Handle casts from floating point to integer now...
1490 if (SrcClass == cFP) {
1491 // Change the floating point control register to use "round towards zero"
1492 // mode when truncating to an integer value.
1494 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1495 addFrameReference(BuildMI(BB, X86::FNSTCWm16, 4), CWFrameIdx);
1497 // Load the old value of the high byte of the control word...
1498 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1499 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1501 // Set the high part to be round to zero...
1502 addFrameReference(BuildMI(BB, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1504 // Reload the modified control word now...
1505 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1507 // Restore the memory image of control word to original value
1508 addFrameReference(BuildMI(BB, X86::MOVrm8, 5),
1509 CWFrameIdx, 1).addReg(HighPartOfCW);
1511 // We don't have the facilities for directly storing byte sized data to
1512 // memory. Promote it to 16 bits. We also must promote unsigned values to
1513 // larger classes because we only have signed FP stores.
1514 unsigned StoreClass = DestClass;
1515 const Type *StoreTy = DestTy;
1516 if (StoreClass == cByte || DestTy->isUnsigned())
1517 switch (StoreClass) {
1518 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1519 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1520 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1521 case cLong: visitInstruction(CI); // unsigned long long -> more complex
1522 default: assert(0 && "Unknown store class!");
1525 // Spill the integer to memory and reload it from there...
1527 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1529 static const unsigned Op1[] =
1530 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1531 addFrameReference(BuildMI(BB, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1533 if (DestClass == cLong) {
1534 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg), FrameIdx);
1535 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1537 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1538 addFrameReference(BuildMI(BB, Op2[DestClass], 4, DestReg), FrameIdx);
1541 // Reload the original control word now...
1542 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1546 // Anything we haven't handled already, we can't (yet) handle at all.
1547 visitInstruction (CI);
1550 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1551 // returns zero when the input is not exactly a power of two.
1552 static unsigned ExactLog2(unsigned Val) {
1553 if (Val == 0) return 0;
1556 if (Val & 1) return 0;
1563 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1564 unsigned outputReg = getReg(I);
1565 MachineBasicBlock::iterator MI = BB->end();
1566 emitGEPOperation(BB, MI, I.getOperand(0),
1567 I.op_begin()+1, I.op_end(), outputReg);
1570 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1571 MachineBasicBlock::iterator &IP,
1572 Value *Src, User::op_iterator IdxBegin,
1573 User::op_iterator IdxEnd, unsigned TargetReg) {
1574 const TargetData &TD = TM.getTargetData();
1575 const Type *Ty = Src->getType();
1576 unsigned BaseReg = getReg(Src, MBB, IP);
1578 // GEPs have zero or more indices; we must perform a struct access
1579 // or array access for each one.
1580 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1581 oe = IdxEnd; oi != oe; ++oi) {
1583 unsigned NextReg = BaseReg;
1584 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1585 // It's a struct access. idx is the index into the structure,
1586 // which names the field. This index must have ubyte type.
1587 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1588 assert(CUI->getType() == Type::UByteTy
1589 && "Funny-looking structure index in GEP");
1590 // Use the TargetData structure to pick out what the layout of
1591 // the structure is in memory. Since the structure index must
1592 // be constant, we can get its value and use it to find the
1593 // right byte offset from the StructLayout class's list of
1594 // structure member offsets.
1595 unsigned idxValue = CUI->getValue();
1596 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1598 NextReg = makeAnotherReg(Type::UIntTy);
1599 // Emit an ADD to add FieldOff to the basePtr.
1600 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1602 // The next type is the member of the structure selected by the
1604 Ty = StTy->getElementTypes()[idxValue];
1605 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1606 // It's an array or pointer access: [ArraySize x ElementType].
1608 // idx is the index into the array. Unlike with structure
1609 // indices, we may not know its actual value at code-generation
1611 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1613 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1614 // must find the size of the pointed-to type (Not coincidentally, the next
1615 // type is the type of the elements in the array).
1616 Ty = SqTy->getElementType();
1617 unsigned elementSize = TD.getTypeSize(Ty);
1619 // If idxReg is a constant, we don't need to perform the multiply!
1620 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1621 if (!CSI->isNullValue()) {
1622 unsigned Offset = elementSize*CSI->getValue();
1623 NextReg = makeAnotherReg(Type::UIntTy);
1624 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1626 } else if (elementSize == 1) {
1627 // If the element size is 1, we don't have to multiply, just add
1628 unsigned idxReg = getReg(idx, MBB, IP);
1629 NextReg = makeAnotherReg(Type::UIntTy);
1630 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1632 unsigned idxReg = getReg(idx, MBB, IP);
1633 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1634 if (unsigned Shift = ExactLog2(elementSize)) {
1635 // If the element size is exactly a power of 2, use a shift to get it.
1636 BMI(MBB, IP, X86::SHLir32, 2,
1637 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1639 // Most general case, emit a multiply...
1640 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1641 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1643 // Emit a MUL to multiply the register holding the index by
1644 // elementSize, putting the result in OffsetReg.
1645 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1647 // Emit an ADD to add OffsetReg to the basePtr.
1648 NextReg = makeAnotherReg(Type::UIntTy);
1649 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1652 // Now that we are here, further indices refer to subtypes of this
1653 // one, so we don't need to worry about BaseReg itself, anymore.
1656 // After we have processed all the indices, the result is left in
1657 // BaseReg. Move it to the register where we were expected to
1658 // put the answer. A 32-bit move should do it, because we are in
1660 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1664 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1665 /// frame manager, otherwise do it the hard way.
1667 void ISel::visitAllocaInst(AllocaInst &I) {
1668 // Find the data size of the alloca inst's getAllocatedType.
1669 const Type *Ty = I.getAllocatedType();
1670 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1672 // If this is a fixed size alloca in the entry block for the function,
1673 // statically stack allocate the space.
1675 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1676 if (I.getParent() == I.getParent()->getParent()->begin()) {
1677 TySize *= CUI->getValue(); // Get total allocated size...
1678 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1680 // Create a new stack object using the frame manager...
1681 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1682 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1687 // Create a register to hold the temporary result of multiplying the type size
1688 // constant by the variable amount.
1689 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1690 unsigned SrcReg1 = getReg(I.getArraySize());
1691 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1692 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1694 // TotalSizeReg = mul <numelements>, <TypeSize>
1695 MachineBasicBlock::iterator MBBI = BB->end();
1696 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1698 // AddedSize = add <TotalSizeReg>, 15
1699 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1700 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1702 // AlignedSize = and <AddedSize>, ~15
1703 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1704 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1706 // Subtract size from stack pointer, thereby allocating some space.
1707 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1709 // Put a pointer to the space into the result register, by copying
1710 // the stack pointer.
1711 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1713 // Inform the Frame Information that we have just allocated a variable sized
1715 F->getFrameInfo()->CreateVariableSizedObject();
1718 /// visitMallocInst - Malloc instructions are code generated into direct calls
1719 /// to the library malloc.
1721 void ISel::visitMallocInst(MallocInst &I) {
1722 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1725 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1726 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1728 Arg = makeAnotherReg(Type::UIntTy);
1729 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1730 unsigned Op1Reg = getReg(I.getOperand(0));
1731 MachineBasicBlock::iterator MBBI = BB->end();
1732 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1737 std::vector<ValueRecord> Args;
1738 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1739 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1740 1).addExternalSymbol("malloc", true);
1741 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1745 /// visitFreeInst - Free instructions are code gen'd to call the free libc
1748 void ISel::visitFreeInst(FreeInst &I) {
1749 std::vector<ValueRecord> Args;
1750 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1751 I.getOperand(0)->getType()));
1752 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1753 1).addExternalSymbol("free", true);
1754 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1758 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1759 /// into a machine code representation is a very simple peep-hole fashion. The
1760 /// generated code sucks but the implementation is nice and simple.
1762 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1763 return new ISel(TM);