1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a simple peephole instruction selector for the x86 target
12 //===----------------------------------------------------------------------===//
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicLowering.h"
22 #include "llvm/Pass.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
41 struct ISel : public FunctionPass, InstVisitor<ISel> {
43 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
46 int ReturnAddressIndex; // FrameIndex for the return address
48 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
50 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
53 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
58 bool runOnFunction(Function &Fn) {
59 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
63 F = &MachineFunction::construct(&Fn, TM);
65 // Create all of the machine basic blocks for the function...
66 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
71 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
75 // Copy incoming arguments off of the stack...
76 LoadArgumentsToVirtualRegs(Fn);
78 // Instruction select everything except PHI nodes
81 // Select the PHI nodes
84 // Insert the FP_REG_KILL instructions into blocks that need them.
90 // We always build a machine code representation for the function
94 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
98 /// visitBasicBlock - This method is called when we are visiting a new basic
99 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
104 BB = MBBMap[&LLVM_BB];
107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
111 void LowerUnknownIntrinsicFunctionCalls(Function &F);
113 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
114 /// from the stack into virtual registers.
116 void LoadArgumentsToVirtualRegs(Function &F);
118 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
119 /// because we have to generate our sources into the source basic blocks,
120 /// not the current one.
122 void SelectPHINodes();
124 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
125 /// that need them. This only occurs due to the floating point stackifier
126 /// not being aggressive enough to handle arbitrary global stackification.
128 void InsertFPRegKills();
130 // Visitation methods for various instructions. These methods simply emit
131 // fixed X86 code for each instruction.
134 // Control flow operators
135 void visitReturnInst(ReturnInst &RI);
136 void visitBranchInst(BranchInst &BI);
142 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
143 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
145 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
146 const std::vector<ValueRecord> &Args);
147 void visitCallInst(CallInst &I);
148 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
150 // Arithmetic operators
151 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
152 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
153 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
154 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
155 unsigned DestReg, const Type *DestTy,
156 unsigned Op0Reg, unsigned Op1Reg);
157 void doMultiplyConst(MachineBasicBlock *MBB,
158 MachineBasicBlock::iterator MBBI,
159 unsigned DestReg, const Type *DestTy,
160 unsigned Op0Reg, unsigned Op1Val);
161 void visitMul(BinaryOperator &B);
163 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
164 void visitRem(BinaryOperator &B) { visitDivRem(B); }
165 void visitDivRem(BinaryOperator &B);
168 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
169 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
170 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
172 // Comparison operators...
173 void visitSetCondInst(SetCondInst &I);
174 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
175 MachineBasicBlock *MBB,
176 MachineBasicBlock::iterator MBBI);
177 void visitSelectInst(SelectInst &SI);
180 // Memory Instructions
181 void visitLoadInst(LoadInst &I);
182 void visitStoreInst(StoreInst &I);
183 void visitGetElementPtrInst(GetElementPtrInst &I);
184 void visitAllocaInst(AllocaInst &I);
185 void visitMallocInst(MallocInst &I);
186 void visitFreeInst(FreeInst &I);
189 void visitShiftInst(ShiftInst &I);
190 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
191 void visitCastInst(CastInst &I);
192 void visitVANextInst(VANextInst &I);
193 void visitVAArgInst(VAArgInst &I);
195 void visitInstruction(Instruction &I) {
196 std::cerr << "Cannot instruction select: " << I;
200 /// promote32 - Make a value 32-bits wide, and put it somewhere.
202 void promote32(unsigned targetReg, const ValueRecord &VR);
204 /// getAddressingMode - Get the addressing mode to use to address the
205 /// specified value. The returned value should be used with addFullAddress.
206 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
207 unsigned &IndexReg, unsigned &Disp);
210 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
212 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
213 std::vector<Value*> &GEPOps,
214 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
215 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
217 /// isGEPFoldable - Return true if the specified GEP can be completely
218 /// folded into the addressing mode of a load/store or lea instruction.
219 bool isGEPFoldable(MachineBasicBlock *MBB,
220 Value *Src, User::op_iterator IdxBegin,
221 User::op_iterator IdxEnd, unsigned &BaseReg,
222 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
224 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
225 /// constant expression GEP support.
227 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
228 Value *Src, User::op_iterator IdxBegin,
229 User::op_iterator IdxEnd, unsigned TargetReg);
231 /// emitCastOperation - Common code shared between visitCastInst and
232 /// constant expression cast support.
234 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
235 Value *Src, const Type *DestTy, unsigned TargetReg);
237 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
238 /// and constant expression support.
240 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
241 MachineBasicBlock::iterator IP,
242 Value *Op0, Value *Op1,
243 unsigned OperatorClass, unsigned TargetReg);
245 void emitDivRemOperation(MachineBasicBlock *BB,
246 MachineBasicBlock::iterator IP,
247 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
248 const Type *Ty, unsigned TargetReg);
250 /// emitSetCCOperation - Common code shared between visitSetCondInst and
251 /// constant expression support.
253 void emitSetCCOperation(MachineBasicBlock *BB,
254 MachineBasicBlock::iterator IP,
255 Value *Op0, Value *Op1, unsigned Opcode,
258 /// emitShiftOperation - Common code shared between visitShiftInst and
259 /// constant expression support.
261 void emitShiftOperation(MachineBasicBlock *MBB,
262 MachineBasicBlock::iterator IP,
263 Value *Op, Value *ShiftAmount, bool isLeftShift,
264 const Type *ResultTy, unsigned DestReg);
266 /// emitSelectOperation - Common code shared between visitSelectInst and the
267 /// constant expression support.
268 void emitSelectOperation(MachineBasicBlock *MBB,
269 MachineBasicBlock::iterator IP,
270 Value *Cond, Value *TrueVal, Value *FalseVal,
273 /// copyConstantToRegister - Output the instructions required to put the
274 /// specified constant into the specified register.
276 void copyConstantToRegister(MachineBasicBlock *MBB,
277 MachineBasicBlock::iterator MBBI,
278 Constant *C, unsigned Reg);
280 /// makeAnotherReg - This method returns the next register number we haven't
283 /// Long values are handled somewhat specially. They are always allocated
284 /// as pairs of 32 bit integer values. The register number returned is the
285 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
286 /// of the long value.
288 unsigned makeAnotherReg(const Type *Ty) {
289 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
290 "Current target doesn't have X86 reg info??");
291 const X86RegisterInfo *MRI =
292 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
293 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
294 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
295 // Create the lower part
296 F->getSSARegMap()->createVirtualRegister(RC);
297 // Create the upper part.
298 return F->getSSARegMap()->createVirtualRegister(RC)-1;
301 // Add the mapping of regnumber => reg class to MachineFunction
302 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
303 return F->getSSARegMap()->createVirtualRegister(RC);
306 /// getReg - This method turns an LLVM value into a register number. This
307 /// is guaranteed to produce the same register number for a particular value
308 /// every time it is queried.
310 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
311 unsigned getReg(Value *V) {
312 // Just append to the end of the current bb.
313 MachineBasicBlock::iterator It = BB->end();
314 return getReg(V, BB, It);
316 unsigned getReg(Value *V, MachineBasicBlock *MBB,
317 MachineBasicBlock::iterator IPt) {
318 unsigned &Reg = RegMap[V];
320 Reg = makeAnotherReg(V->getType());
324 // If this operand is a constant, emit the code to copy the constant into
325 // the register here...
327 if (Constant *C = dyn_cast<Constant>(V)) {
328 copyConstantToRegister(MBB, IPt, C, Reg);
329 RegMap.erase(V); // Assign a new name to this constant if ref'd again
330 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
331 // Move the address of the global into the register
332 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
333 RegMap.erase(V); // Assign a new name to this address if ref'd again
341 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
345 cByte, cShort, cInt, cFP, cLong
348 /// getClass - Turn a primitive type into a "class" number which is based on the
349 /// size of the type, and whether or not it is floating point.
351 static inline TypeClass getClass(const Type *Ty) {
352 switch (Ty->getPrimitiveID()) {
353 case Type::SByteTyID:
354 case Type::UByteTyID: return cByte; // Byte operands are class #0
355 case Type::ShortTyID:
356 case Type::UShortTyID: return cShort; // Short operands are class #1
359 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
361 case Type::FloatTyID:
362 case Type::DoubleTyID: return cFP; // Floating Point is #3
365 case Type::ULongTyID: return cLong; // Longs are class #4
367 assert(0 && "Invalid type to getClass!");
368 return cByte; // not reached
372 // getClassB - Just like getClass, but treat boolean values as bytes.
373 static inline TypeClass getClassB(const Type *Ty) {
374 if (Ty == Type::BoolTy) return cByte;
379 /// copyConstantToRegister - Output the instructions required to put the
380 /// specified constant into the specified register.
382 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
383 MachineBasicBlock::iterator IP,
384 Constant *C, unsigned R) {
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
387 switch (CE->getOpcode()) {
388 case Instruction::GetElementPtr:
389 emitGEPOperation(MBB, IP, CE->getOperand(0),
390 CE->op_begin()+1, CE->op_end(), R);
392 case Instruction::Cast:
393 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
396 case Instruction::Xor: ++Class; // FALL THROUGH
397 case Instruction::Or: ++Class; // FALL THROUGH
398 case Instruction::And: ++Class; // FALL THROUGH
399 case Instruction::Sub: ++Class; // FALL THROUGH
400 case Instruction::Add:
401 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
405 case Instruction::Mul: {
406 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
407 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
408 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
411 case Instruction::Div:
412 case Instruction::Rem: {
413 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
414 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
415 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
416 CE->getOpcode() == Instruction::Div,
421 case Instruction::SetNE:
422 case Instruction::SetEQ:
423 case Instruction::SetLT:
424 case Instruction::SetGT:
425 case Instruction::SetLE:
426 case Instruction::SetGE:
427 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
431 case Instruction::Shl:
432 case Instruction::Shr:
433 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
434 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
437 case Instruction::Select:
438 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
439 CE->getOperand(2), R);
443 std::cerr << "Offending expr: " << C << "\n";
444 assert(0 && "Constant expression not yet handled!\n");
448 if (C->getType()->isIntegral()) {
449 unsigned Class = getClassB(C->getType());
451 if (Class == cLong) {
452 // Copy the value into the register pair.
453 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
454 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
455 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
459 assert(Class <= cInt && "Type not handled yet!");
461 static const unsigned IntegralOpcodeTab[] = {
462 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
465 if (C->getType() == Type::BoolTy) {
466 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
468 ConstantInt *CI = cast<ConstantInt>(C);
469 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
471 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
472 if (CFP->isExactlyValue(+0.0))
473 BuildMI(*MBB, IP, X86::FLD0, 0, R);
474 else if (CFP->isExactlyValue(+1.0))
475 BuildMI(*MBB, IP, X86::FLD1, 0, R);
477 // Otherwise we need to spill the constant to memory...
478 MachineConstantPool *CP = F->getConstantPool();
479 unsigned CPI = CP->getConstantPoolIndex(CFP);
480 const Type *Ty = CFP->getType();
482 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
483 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
484 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
487 } else if (isa<ConstantPointerNull>(C)) {
488 // Copy zero (null pointer) to the register.
489 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
490 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
491 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
493 std::cerr << "Offending constant: " << C << "\n";
494 assert(0 && "Type not handled yet!");
498 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
499 /// the stack into virtual registers.
501 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
502 // Emit instructions to load the arguments... On entry to a function on the
503 // X86, the stack frame looks like this:
505 // [ESP] -- return address
506 // [ESP + 4] -- first argument (leftmost lexically)
507 // [ESP + 8] -- second argument, if first argument is four bytes in size
510 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
511 MachineFrameInfo *MFI = F->getFrameInfo();
513 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
514 unsigned Reg = getReg(*I);
516 int FI; // Frame object index
517 switch (getClassB(I->getType())) {
519 FI = MFI->CreateFixedObject(1, ArgOffset);
520 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
523 FI = MFI->CreateFixedObject(2, ArgOffset);
524 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
527 FI = MFI->CreateFixedObject(4, ArgOffset);
528 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
531 FI = MFI->CreateFixedObject(8, ArgOffset);
532 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
533 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
534 ArgOffset += 4; // longs require 4 additional bytes
538 if (I->getType() == Type::FloatTy) {
539 Opcode = X86::FLD32m;
540 FI = MFI->CreateFixedObject(4, ArgOffset);
542 Opcode = X86::FLD64m;
543 FI = MFI->CreateFixedObject(8, ArgOffset);
544 ArgOffset += 4; // doubles require 4 additional bytes
546 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
549 assert(0 && "Unhandled argument type!");
551 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
554 // If the function takes variable number of arguments, add a frame offset for
555 // the start of the first vararg value... this is used to expand
557 if (Fn.getFunctionType()->isVarArg())
558 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
562 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
563 /// because we have to generate our sources into the source basic blocks, not
566 void ISel::SelectPHINodes() {
567 const TargetInstrInfo &TII = TM.getInstrInfo();
568 const Function &LF = *F->getFunction(); // The LLVM function...
569 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
570 const BasicBlock *BB = I;
571 MachineBasicBlock &MBB = *MBBMap[I];
573 // Loop over all of the PHI nodes in the LLVM basic block...
574 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
575 for (BasicBlock::const_iterator I = BB->begin();
576 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
578 // Create a new machine instr PHI node, and insert it.
579 unsigned PHIReg = getReg(*PN);
580 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
581 X86::PHI, PN->getNumOperands(), PHIReg);
583 MachineInstr *LongPhiMI = 0;
584 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
585 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
586 X86::PHI, PN->getNumOperands(), PHIReg+1);
588 // PHIValues - Map of blocks to incoming virtual registers. We use this
589 // so that we only initialize one incoming value for a particular block,
590 // even if the block has multiple entries in the PHI node.
592 std::map<MachineBasicBlock*, unsigned> PHIValues;
594 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
595 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
597 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
598 PHIValues.lower_bound(PredMBB);
600 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
601 // We already inserted an initialization of the register for this
602 // predecessor. Recycle it.
603 ValReg = EntryIt->second;
606 // Get the incoming value into a virtual register.
608 Value *Val = PN->getIncomingValue(i);
610 // If this is a constant or GlobalValue, we may have to insert code
611 // into the basic block to compute it into a virtual register.
612 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
613 if (isa<ConstantExpr>(Val)) {
614 // Because we don't want to clobber any values which might be in
615 // physical registers with the computation of this constant (which
616 // might be arbitrarily complex if it is a constant expression),
617 // just insert the computation at the top of the basic block.
618 MachineBasicBlock::iterator PI = PredMBB->begin();
620 // Skip over any PHI nodes though!
621 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
624 ValReg = getReg(Val, PredMBB, PI);
626 // Simple constants get emitted at the end of the basic block,
627 // before any terminator instructions. We "know" that the code to
628 // move a constant into a register will never clobber any flags.
629 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
632 ValReg = getReg(Val);
635 // Remember that we inserted a value for this PHI for this predecessor
636 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
639 PhiMI->addRegOperand(ValReg);
640 PhiMI->addMachineBasicBlockOperand(PredMBB);
642 LongPhiMI->addRegOperand(ValReg+1);
643 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
647 // Now that we emitted all of the incoming values for the PHI node, make
648 // sure to reposition the InsertPoint after the PHI that we just added.
649 // This is needed because we might have inserted a constant into this
650 // block, right after the PHI's which is before the old insert point!
651 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
657 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
658 /// compensation code on critical edges. As such, it requires that we kill all
659 /// FP registers on the exit from any blocks that either ARE critical edges, or
660 /// branch to a block that has incoming critical edges.
662 /// Note that this kill instruction will eventually be eliminated when
663 /// restrictions in the stackifier are relaxed.
665 static bool RequiresFPRegKill(const BasicBlock *BB) {
667 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
668 const BasicBlock *Succ = *SI;
669 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
670 ++PI; // Block have at least one predecessory
671 if (PI != PE) { // If it has exactly one, this isn't crit edge
672 // If this block has more than one predecessor, check all of the
673 // predecessors to see if they have multiple successors. If so, then the
674 // block we are analyzing needs an FPRegKill.
675 for (PI = pred_begin(Succ); PI != PE; ++PI) {
676 const BasicBlock *Pred = *PI;
677 succ_const_iterator SI2 = succ_begin(Pred);
678 ++SI2; // There must be at least one successor of this block.
679 if (SI2 != succ_end(Pred))
680 return true; // Yes, we must insert the kill on this edge.
684 // If we got this far, there is no need to insert the kill instruction.
691 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
692 // need them. This only occurs due to the floating point stackifier not being
693 // aggressive enough to handle arbitrary global stackification.
695 // Currently we insert an FP_REG_KILL instruction into each block that uses or
696 // defines a floating point virtual register.
698 // When the global register allocators (like linear scan) finally update live
699 // variable analysis, we can keep floating point values in registers across
700 // portions of the CFG that do not involve critical edges. This will be a big
701 // win, but we are waiting on the global allocators before we can do this.
703 // With a bit of work, the floating point stackifier pass can be enhanced to
704 // break critical edges as needed (to make a place to put compensation code),
705 // but this will require some infrastructure improvements as well.
707 void ISel::InsertFPRegKills() {
708 SSARegMap &RegMap = *F->getSSARegMap();
710 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
711 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
712 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
713 MachineOperand& MO = I->getOperand(i);
714 if (MO.isRegister() && MO.getReg()) {
715 unsigned Reg = MO.getReg();
716 if (MRegisterInfo::isVirtualRegister(Reg))
717 if (RegMap.getRegClass(Reg)->getSize() == 10)
721 // If we haven't found an FP register use or def in this basic block, check
722 // to see if any of our successors has an FP PHI node, which will cause a
723 // copy to be inserted into this block.
724 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
725 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
726 MachineBasicBlock *SBB = MBBMap[*SI];
727 for (MachineBasicBlock::iterator I = SBB->begin();
728 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
729 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
735 // Okay, this block uses an FP register. If the block has successors (ie,
736 // it's not an unwind/return), insert the FP_REG_KILL instruction.
737 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
738 RequiresFPRegKill(BB->getBasicBlock())) {
739 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
746 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
747 // it into the conditional branch or select instruction which is the only user
748 // of the cc instruction. This is the case if the conditional branch is the
749 // only user of the setcc, and if the setcc is in the same basic block as the
750 // conditional branch. We also don't handle long arguments below, so we reject
751 // them here as well.
753 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
754 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
755 if (SCI->hasOneUse()) {
756 Instruction *User = cast<Instruction>(SCI->use_back());
757 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
758 SCI->getParent() == User->getParent() &&
759 getClassB(SCI->getOperand(0)->getType()) != cLong)
765 // Return a fixed numbering for setcc instructions which does not depend on the
766 // order of the opcodes.
768 static unsigned getSetCCNumber(unsigned Opcode) {
770 default: assert(0 && "Unknown setcc instruction!");
771 case Instruction::SetEQ: return 0;
772 case Instruction::SetNE: return 1;
773 case Instruction::SetLT: return 2;
774 case Instruction::SetGE: return 3;
775 case Instruction::SetGT: return 4;
776 case Instruction::SetLE: return 5;
780 // LLVM -> X86 signed X86 unsigned
781 // ----- ---------- ------------
782 // seteq -> sete sete
783 // setne -> setne setne
784 // setlt -> setl setb
785 // setge -> setge setae
786 // setgt -> setg seta
787 // setle -> setle setbe
789 // sets // Used by comparison with 0 optimization
791 static const unsigned SetCCOpcodeTab[2][8] = {
792 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
794 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
795 X86::SETSr, X86::SETNSr },
798 // EmitComparison - This function emits a comparison of the two operands,
799 // returning the extended setcc code to use.
800 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
801 MachineBasicBlock *MBB,
802 MachineBasicBlock::iterator IP) {
803 // The arguments are already supposed to be of the same type.
804 const Type *CompTy = Op0->getType();
805 unsigned Class = getClassB(CompTy);
806 unsigned Op0r = getReg(Op0, MBB, IP);
808 // Special case handling of: cmp R, i
809 if (Class == cByte || Class == cShort || Class == cInt)
810 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
811 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
813 // Mask off any upper bits of the constant, if there are any...
814 Op1v &= (1ULL << (8 << Class)) - 1;
816 // If this is a comparison against zero, emit more efficient code. We
817 // can't handle unsigned comparisons against zero unless they are == or
818 // !=. These should have been strength reduced already anyway.
819 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
820 static const unsigned TESTTab[] = {
821 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
823 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
825 if (OpNum == 2) return 6; // Map jl -> js
826 if (OpNum == 3) return 7; // Map jg -> jns
830 static const unsigned CMPTab[] = {
831 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
834 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
838 // Special case handling of comparison against +/- 0.0
839 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
840 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
841 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
842 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
843 BuildMI(*MBB, IP, X86::SAHF, 1);
847 unsigned Op1r = getReg(Op1, MBB, IP);
849 default: assert(0 && "Unknown type class!");
850 // Emit: cmp <var1>, <var2> (do the comparison). We can
851 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
854 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
857 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
860 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
863 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
864 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
865 BuildMI(*MBB, IP, X86::SAHF, 1);
869 if (OpNum < 2) { // seteq, setne
870 unsigned LoTmp = makeAnotherReg(Type::IntTy);
871 unsigned HiTmp = makeAnotherReg(Type::IntTy);
872 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
873 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
874 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
875 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
876 break; // Allow the sete or setne to be generated from flags set by OR
878 // Emit a sequence of code which compares the high and low parts once
879 // each, then uses a conditional move to handle the overflow case. For
880 // example, a setlt for long would generate code like this:
882 // AL = lo(op1) < lo(op2) // Signedness depends on operands
883 // BL = hi(op1) < hi(op2) // Always unsigned comparison
884 // dest = hi(op1) == hi(op2) ? AL : BL;
887 // FIXME: This would be much better if we had hierarchical register
888 // classes! Until then, hardcode registers so that we can deal with their
889 // aliases (because we don't have conditional byte moves).
891 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
892 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
893 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
894 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
895 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
896 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
897 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
899 // NOTE: visitSetCondInst knows that the value is dumped into the BL
900 // register at this point for long values...
907 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
908 /// register, then move it to wherever the result should be.
910 void ISel::visitSetCondInst(SetCondInst &I) {
911 if (canFoldSetCCIntoBranchOrSelect(&I))
912 return; // Fold this into a branch or select.
914 unsigned DestReg = getReg(I);
915 MachineBasicBlock::iterator MII = BB->end();
916 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
920 /// emitSetCCOperation - Common code shared between visitSetCondInst and
921 /// constant expression support.
923 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
924 MachineBasicBlock::iterator IP,
925 Value *Op0, Value *Op1, unsigned Opcode,
926 unsigned TargetReg) {
927 unsigned OpNum = getSetCCNumber(Opcode);
928 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
930 const Type *CompTy = Op0->getType();
931 unsigned CompClass = getClassB(CompTy);
932 bool isSigned = CompTy->isSigned() && CompClass != cFP;
934 if (CompClass != cLong || OpNum < 2) {
935 // Handle normal comparisons with a setcc instruction...
936 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
938 // Handle long comparisons by copying the value which is already in BL into
939 // the register we want...
940 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
944 void ISel::visitSelectInst(SelectInst &SI) {
945 unsigned DestReg = getReg(SI);
946 MachineBasicBlock::iterator MII = BB->end();
947 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
948 SI.getFalseValue(), DestReg);
951 /// emitSelect - Common code shared between visitSelectInst and the constant
952 /// expression support.
953 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
954 MachineBasicBlock::iterator IP,
955 Value *Cond, Value *TrueVal, Value *FalseVal,
957 unsigned SelectClass = getClassB(TrueVal->getType());
959 // We don't support 8-bit conditional moves. If we have incoming constants,
960 // transform them into 16-bit constants to avoid having a run-time conversion.
961 if (SelectClass == cByte) {
962 if (Constant *T = dyn_cast<Constant>(TrueVal))
963 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
964 if (Constant *F = dyn_cast<Constant>(FalseVal))
965 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
970 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
971 // We successfully folded the setcc into the select instruction.
973 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
974 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
977 const Type *CompTy = SCI->getOperand(0)->getType();
978 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
980 // LLVM -> X86 signed X86 unsigned
981 // ----- ---------- ------------
982 // seteq -> cmovNE cmovNE
983 // setne -> cmovE cmovE
984 // setlt -> cmovGE cmovAE
985 // setge -> cmovL cmovB
986 // setgt -> cmovLE cmovBE
987 // setle -> cmovG cmovA
989 // cmovNS // Used by comparison with 0 optimization
992 switch (SelectClass) {
993 default: assert(0 && "Unknown value class!");
995 // Annoyingly, we don't have a full set of floating point conditional
997 static const unsigned OpcodeTab[2][8] = {
998 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
999 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1000 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1002 Opcode = OpcodeTab[isSigned][OpNum];
1004 // If opcode == 0, we hit a case that we don't support. Output a setcc
1005 // and compare the result against zero.
1007 unsigned CompClass = getClassB(CompTy);
1009 if (CompClass != cLong || OpNum < 2) {
1010 CondReg = makeAnotherReg(Type::BoolTy);
1011 // Handle normal comparisons with a setcc instruction...
1012 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1014 // Long comparisons end up in the BL register.
1018 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1019 Opcode = X86::FCMOVE;
1025 static const unsigned OpcodeTab[2][8] = {
1026 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1027 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1028 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1029 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1031 Opcode = OpcodeTab[isSigned][OpNum];
1036 static const unsigned OpcodeTab[2][8] = {
1037 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1038 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1039 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1040 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1042 Opcode = OpcodeTab[isSigned][OpNum];
1047 // Get the value being branched on, and use it to set the condition codes.
1048 unsigned CondReg = getReg(Cond, MBB, IP);
1049 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1050 switch (SelectClass) {
1051 default: assert(0 && "Unknown value class!");
1052 case cFP: Opcode = X86::FCMOVE; break;
1054 case cShort: Opcode = X86::CMOVE16rr; break;
1056 case cLong: Opcode = X86::CMOVE32rr; break;
1060 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1061 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1062 unsigned RealDestReg = DestReg;
1065 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1066 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1067 // cmove, then truncate the result.
1068 if (SelectClass == cByte) {
1069 DestReg = makeAnotherReg(Type::ShortTy);
1070 if (getClassB(TrueVal->getType()) == cByte) {
1071 // Promote the true value, by storing it into AL, and reading from AX.
1072 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1073 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1074 TrueReg = makeAnotherReg(Type::ShortTy);
1075 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1077 if (getClassB(FalseVal->getType()) == cByte) {
1078 // Promote the true value, by storing it into CL, and reading from CX.
1079 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1080 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1081 FalseReg = makeAnotherReg(Type::ShortTy);
1082 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1086 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1088 switch (SelectClass) {
1090 // We did the computation with 16-bit registers. Truncate back to our
1091 // result by copying into AX then copying out AL.
1092 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1093 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1096 // Move the upper half of the value as well.
1097 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1104 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1105 /// operand, in the specified target register.
1107 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1108 bool isUnsigned = VR.Ty->isUnsigned();
1110 // Make sure we have the register number for this value...
1111 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
1113 switch (getClassB(VR.Ty)) {
1115 // Extend value into target register (8->32)
1117 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1119 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1122 // Extend value into target register (16->32)
1124 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1126 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1129 // Move value into target register (32->32)
1130 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1133 assert(0 && "Unpromotable operand class in promote32");
1137 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1138 /// we have the following possibilities:
1140 /// ret void: No return value, simply emit a 'ret' instruction
1141 /// ret sbyte, ubyte : Extend value into EAX and return
1142 /// ret short, ushort: Extend value into EAX and return
1143 /// ret int, uint : Move value into EAX and return
1144 /// ret pointer : Move value into EAX and return
1145 /// ret long, ulong : Move value into EAX/EDX and return
1146 /// ret float/double : Top of FP stack
1148 void ISel::visitReturnInst(ReturnInst &I) {
1149 if (I.getNumOperands() == 0) {
1150 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1154 Value *RetVal = I.getOperand(0);
1155 unsigned RetReg = getReg(RetVal);
1156 switch (getClassB(RetVal->getType())) {
1157 case cByte: // integral return values: extend or move into EAX and return
1160 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
1161 // Declare that EAX is live on exit
1162 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1164 case cFP: // Floats & Doubles: Return in ST(0)
1165 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1166 // Declare that top-of-stack is live on exit
1167 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1170 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1171 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1172 // Declare that EAX & EDX are live on exit
1173 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1177 visitInstruction(I);
1179 // Emit a 'ret' instruction
1180 BuildMI(BB, X86::RET, 0);
1183 // getBlockAfter - Return the basic block which occurs lexically after the
1185 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1186 Function::iterator I = BB; ++I; // Get iterator to next block
1187 return I != BB->getParent()->end() ? &*I : 0;
1190 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1191 /// that since code layout is frozen at this point, that if we are trying to
1192 /// jump to a block that is the immediate successor of the current block, we can
1193 /// just make a fall-through (but we don't currently).
1195 void ISel::visitBranchInst(BranchInst &BI) {
1196 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1198 if (!BI.isConditional()) { // Unconditional branch?
1199 if (BI.getSuccessor(0) != NextBB)
1200 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1204 // See if we can fold the setcc into the branch itself...
1205 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1207 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1208 // computed some other way...
1209 unsigned condReg = getReg(BI.getCondition());
1210 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1211 if (BI.getSuccessor(1) == NextBB) {
1212 if (BI.getSuccessor(0) != NextBB)
1213 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1215 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1217 if (BI.getSuccessor(0) != NextBB)
1218 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1223 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1224 MachineBasicBlock::iterator MII = BB->end();
1225 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1227 const Type *CompTy = SCI->getOperand(0)->getType();
1228 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1231 // LLVM -> X86 signed X86 unsigned
1232 // ----- ---------- ------------
1240 // js // Used by comparison with 0 optimization
1243 static const unsigned OpcodeTab[2][8] = {
1244 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1245 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1246 X86::JS, X86::JNS },
1249 if (BI.getSuccessor(0) != NextBB) {
1250 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1251 if (BI.getSuccessor(1) != NextBB)
1252 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1254 // Change to the inverse condition...
1255 if (BI.getSuccessor(1) != NextBB) {
1257 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1263 /// doCall - This emits an abstract call instruction, setting up the arguments
1264 /// and the return value as appropriate. For the actual function call itself,
1265 /// it inserts the specified CallMI instruction into the stream.
1267 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1268 const std::vector<ValueRecord> &Args) {
1270 // Count how many bytes are to be pushed on the stack...
1271 unsigned NumBytes = 0;
1273 if (!Args.empty()) {
1274 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1275 switch (getClassB(Args[i].Ty)) {
1276 case cByte: case cShort: case cInt:
1277 NumBytes += 4; break;
1279 NumBytes += 8; break;
1281 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1283 default: assert(0 && "Unknown class!");
1286 // Adjust the stack pointer for the new arguments...
1287 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1289 // Arguments go on the stack in reverse order, as specified by the ABI.
1290 unsigned ArgOffset = 0;
1291 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1293 switch (getClassB(Args[i].Ty)) {
1296 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1297 // Zero/Sign extend constant, then stuff into memory.
1298 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1299 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1300 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1301 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1303 // Promote arg to 32 bits wide into a temporary register...
1304 ArgReg = makeAnotherReg(Type::UIntTy);
1305 promote32(ArgReg, Args[i]);
1306 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1307 X86::ESP, ArgOffset).addReg(ArgReg);
1311 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1312 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1313 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1314 X86::ESP, ArgOffset).addImm(Val);
1316 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1317 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1318 X86::ESP, ArgOffset).addReg(ArgReg);
1322 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1323 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1324 X86::ESP, ArgOffset).addReg(ArgReg);
1325 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1326 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1327 ArgOffset += 4; // 8 byte entry, not 4.
1331 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1332 if (Args[i].Ty == Type::FloatTy) {
1333 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1334 X86::ESP, ArgOffset).addReg(ArgReg);
1336 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1337 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1338 X86::ESP, ArgOffset).addReg(ArgReg);
1339 ArgOffset += 4; // 8 byte entry, not 4.
1343 default: assert(0 && "Unknown class!");
1348 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1351 BB->push_back(CallMI);
1353 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1355 // If there is a return value, scavenge the result from the location the call
1358 if (Ret.Ty != Type::VoidTy) {
1359 unsigned DestClass = getClassB(Ret.Ty);
1360 switch (DestClass) {
1364 // Integral results are in %eax, or the appropriate portion
1366 static const unsigned regRegMove[] = {
1367 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1369 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1370 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1373 case cFP: // Floating-point return values live in %ST(0)
1374 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1376 case cLong: // Long values are left in EDX:EAX
1377 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1378 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1380 default: assert(0 && "Unknown class!");
1386 /// visitCallInst - Push args on stack and do a procedure call instruction.
1387 void ISel::visitCallInst(CallInst &CI) {
1388 MachineInstr *TheCall;
1389 if (Function *F = CI.getCalledFunction()) {
1390 // Is it an intrinsic function call?
1391 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1392 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1396 // Emit a CALL instruction with PC-relative displacement.
1397 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1398 } else { // Emit an indirect call...
1399 unsigned Reg = getReg(CI.getCalledValue());
1400 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1403 std::vector<ValueRecord> Args;
1404 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1405 Args.push_back(ValueRecord(CI.getOperand(i)));
1407 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1408 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1412 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1413 /// function, lowering any calls to unknown intrinsic functions into the
1414 /// equivalent LLVM code.
1416 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1417 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1418 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1419 if (CallInst *CI = dyn_cast<CallInst>(I++))
1420 if (Function *F = CI->getCalledFunction())
1421 switch (F->getIntrinsicID()) {
1422 case Intrinsic::not_intrinsic:
1423 case Intrinsic::vastart:
1424 case Intrinsic::vacopy:
1425 case Intrinsic::vaend:
1426 case Intrinsic::returnaddress:
1427 case Intrinsic::frameaddress:
1428 case Intrinsic::memcpy:
1429 case Intrinsic::memset:
1430 // We directly implement these intrinsics
1433 // All other intrinsic calls we must lower.
1434 Instruction *Before = CI->getPrev();
1435 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1436 if (Before) { // Move iterator to instruction after call
1445 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1446 unsigned TmpReg1, TmpReg2;
1448 case Intrinsic::vastart:
1449 // Get the address of the first vararg value...
1450 TmpReg1 = getReg(CI);
1451 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1454 case Intrinsic::vacopy:
1455 TmpReg1 = getReg(CI);
1456 TmpReg2 = getReg(CI.getOperand(1));
1457 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1459 case Intrinsic::vaend: return; // Noop on X86
1461 case Intrinsic::returnaddress:
1462 case Intrinsic::frameaddress:
1463 TmpReg1 = getReg(CI);
1464 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1465 if (ID == Intrinsic::returnaddress) {
1466 // Just load the return address
1467 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1468 ReturnAddressIndex);
1470 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1471 ReturnAddressIndex, -4);
1474 // Values other than zero are not implemented yet.
1475 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1479 case Intrinsic::memcpy: {
1480 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1482 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1483 Align = AlignC->getRawValue();
1484 if (Align == 0) Align = 1;
1487 // Turn the byte code into # iterations
1490 switch (Align & 3) {
1491 case 2: // WORD aligned
1492 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1493 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1495 CountReg = makeAnotherReg(Type::IntTy);
1496 unsigned ByteReg = getReg(CI.getOperand(3));
1497 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1499 Opcode = X86::REP_MOVSW;
1501 case 0: // DWORD aligned
1502 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1503 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1505 CountReg = makeAnotherReg(Type::IntTy);
1506 unsigned ByteReg = getReg(CI.getOperand(3));
1507 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1509 Opcode = X86::REP_MOVSD;
1511 default: // BYTE aligned
1512 CountReg = getReg(CI.getOperand(3));
1513 Opcode = X86::REP_MOVSB;
1517 // No matter what the alignment is, we put the source in ESI, the
1518 // destination in EDI, and the count in ECX.
1519 TmpReg1 = getReg(CI.getOperand(1));
1520 TmpReg2 = getReg(CI.getOperand(2));
1521 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1522 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1523 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1524 BuildMI(BB, Opcode, 0);
1527 case Intrinsic::memset: {
1528 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1530 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1531 Align = AlignC->getRawValue();
1532 if (Align == 0) Align = 1;
1535 // Turn the byte code into # iterations
1538 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1539 unsigned Val = ValC->getRawValue() & 255;
1541 // If the value is a constant, then we can potentially use larger copies.
1542 switch (Align & 3) {
1543 case 2: // WORD aligned
1544 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1545 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1547 CountReg = makeAnotherReg(Type::IntTy);
1548 unsigned ByteReg = getReg(CI.getOperand(3));
1549 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1551 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1552 Opcode = X86::REP_STOSW;
1554 case 0: // DWORD aligned
1555 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1556 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1558 CountReg = makeAnotherReg(Type::IntTy);
1559 unsigned ByteReg = getReg(CI.getOperand(3));
1560 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1562 Val = (Val << 8) | Val;
1563 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1564 Opcode = X86::REP_STOSD;
1566 default: // BYTE aligned
1567 CountReg = getReg(CI.getOperand(3));
1568 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1569 Opcode = X86::REP_STOSB;
1573 // If it's not a constant value we are storing, just fall back. We could
1574 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1575 unsigned ValReg = getReg(CI.getOperand(2));
1576 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1577 CountReg = getReg(CI.getOperand(3));
1578 Opcode = X86::REP_STOSB;
1581 // No matter what the alignment is, we put the source in ESI, the
1582 // destination in EDI, and the count in ECX.
1583 TmpReg1 = getReg(CI.getOperand(1));
1584 //TmpReg2 = getReg(CI.getOperand(2));
1585 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1586 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1587 BuildMI(BB, Opcode, 0);
1591 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1595 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1596 if (LI.getParent() != User.getParent())
1598 BasicBlock::iterator It = &LI;
1599 // Check all of the instructions between the load and the user. We should
1600 // really use alias analysis here, but for now we just do something simple.
1601 for (++It; It != BasicBlock::iterator(&User); ++It) {
1602 switch (It->getOpcode()) {
1603 case Instruction::Free:
1604 case Instruction::Store:
1605 case Instruction::Call:
1606 case Instruction::Invoke:
1614 /// visitSimpleBinary - Implement simple binary operators for integral types...
1615 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1618 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1619 unsigned DestReg = getReg(B);
1620 MachineBasicBlock::iterator MI = BB->end();
1621 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1623 // Special case: op Reg, load [mem]
1624 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1625 if (!B.swapOperands())
1626 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1628 unsigned Class = getClassB(B.getType());
1629 if (isa<LoadInst>(Op1) && Class < cFP &&
1630 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1632 static const unsigned OpcodeTab[][3] = {
1633 // Arithmetic operators
1634 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1635 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1637 // Bitwise operators
1638 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1639 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1640 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1643 assert(Class < cFP && "General code handles 64-bit integer types!");
1644 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1646 unsigned BaseReg, Scale, IndexReg, Disp;
1647 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1648 Scale, IndexReg, Disp);
1650 unsigned Op0r = getReg(Op0);
1651 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1652 BaseReg, Scale, IndexReg, Disp);
1656 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1659 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1660 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1663 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1664 /// and constant expression support.
1666 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1667 MachineBasicBlock::iterator IP,
1668 Value *Op0, Value *Op1,
1669 unsigned OperatorClass, unsigned DestReg) {
1670 unsigned Class = getClassB(Op0->getType());
1672 // sub 0, X -> neg X
1673 if (OperatorClass == 1 && Class != cLong)
1674 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1675 if (CI->isNullValue()) {
1676 unsigned op1Reg = getReg(Op1, MBB, IP);
1678 default: assert(0 && "Unknown class for this function!");
1680 BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
1683 BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
1686 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
1690 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1691 if (CFP->isExactlyValue(-0.0)) {
1693 unsigned op1Reg = getReg(Op1, MBB, IP);
1694 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1698 // Special case: op Reg, <const>
1699 if (Class != cLong && isa<ConstantInt>(Op1)) {
1700 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1701 unsigned Op0r = getReg(Op0, MBB, IP);
1703 // xor X, -1 -> not X
1704 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1705 static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1706 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1710 // add X, -1 -> dec X
1711 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1712 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1713 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1717 // add X, 1 -> inc X
1718 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1719 static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1720 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1724 static const unsigned OpcodeTab[][3] = {
1725 // Arithmetic operators
1726 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri }, // ADD
1727 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri }, // SUB
1729 // Bitwise operators
1730 { X86::AND8ri, X86::AND16ri, X86::AND32ri }, // AND
1731 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri }, // OR
1732 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri }, // XOR
1735 assert(Class < cFP && "General code handles 64-bit integer types!");
1736 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1739 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1740 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1v);
1744 // Finally, handle the general case now.
1745 static const unsigned OpcodeTab[][4] = {
1746 // Arithmetic operators
1747 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD }, // ADD
1748 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB }, // SUB
1750 // Bitwise operators
1751 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 }, // AND
1752 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 }, // OR
1753 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 }, // XOR
1756 bool isLong = false;
1757 if (Class == cLong) {
1759 Class = cInt; // Bottom 32 bits are handled just like ints
1762 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1763 assert(Opcode && "Floating point arguments to logical inst?");
1764 unsigned Op0r = getReg(Op0, MBB, IP);
1765 unsigned Op1r = getReg(Op1, MBB, IP);
1766 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1768 if (isLong) { // Handle the upper 32 bits of long values...
1769 static const unsigned TopTab[] = {
1770 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1772 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1773 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1777 /// doMultiply - Emit appropriate instructions to multiply together the
1778 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1779 /// result should be given as DestTy.
1781 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1782 unsigned DestReg, const Type *DestTy,
1783 unsigned op0Reg, unsigned op1Reg) {
1784 unsigned Class = getClass(DestTy);
1786 case cFP: // Floating point multiply
1787 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1791 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
1792 .addReg(op0Reg).addReg(op1Reg);
1795 // Must use the MUL instruction, which forces use of AL...
1796 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1797 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1798 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1801 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1805 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1806 // returns zero when the input is not exactly a power of two.
1807 static unsigned ExactLog2(unsigned Val) {
1808 if (Val == 0) return 0;
1811 if (Val & 1) return 0;
1818 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1819 MachineBasicBlock::iterator IP,
1820 unsigned DestReg, const Type *DestTy,
1821 unsigned op0Reg, unsigned ConstRHS) {
1822 unsigned Class = getClass(DestTy);
1824 // If the element size is exactly a power of 2, use a shift to get it.
1825 if (unsigned Shift = ExactLog2(ConstRHS)) {
1827 default: assert(0 && "Unknown class for this function!");
1829 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1832 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1835 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1840 if (Class == cShort) {
1841 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1843 } else if (Class == cInt) {
1844 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1848 // Most general case, emit a normal multiply...
1849 static const unsigned MOVriTab[] = {
1850 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
1853 unsigned TmpReg = makeAnotherReg(DestTy);
1854 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1856 // Emit a MUL to multiply the register holding the index by
1857 // elementSize, putting the result in OffsetReg.
1858 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1861 /// visitMul - Multiplies are not simple binary operators because they must deal
1862 /// with the EAX register explicitly.
1864 void ISel::visitMul(BinaryOperator &I) {
1865 unsigned Op0Reg = getReg(I.getOperand(0));
1866 unsigned DestReg = getReg(I);
1868 // Simple scalar multiply?
1869 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1870 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1871 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1872 MachineBasicBlock::iterator MBBI = BB->end();
1873 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1875 unsigned Op1Reg = getReg(I.getOperand(1));
1876 MachineBasicBlock::iterator MBBI = BB->end();
1877 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1880 unsigned Op1Reg = getReg(I.getOperand(1));
1882 // Long value. We have to do things the hard way...
1883 // Multiply the two low parts... capturing carry into EDX
1884 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1885 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
1887 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1888 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
1889 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1891 MachineBasicBlock::iterator MBBI = BB->end();
1892 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1893 BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1895 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1896 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
1897 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1900 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1901 BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1903 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1904 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1909 /// visitDivRem - Handle division and remainder instructions... these
1910 /// instruction both require the same instructions to be generated, they just
1911 /// select the result from a different register. Note that both of these
1912 /// instructions work differently for signed and unsigned operands.
1914 void ISel::visitDivRem(BinaryOperator &I) {
1915 unsigned Op0Reg = getReg(I.getOperand(0));
1916 unsigned Op1Reg = getReg(I.getOperand(1));
1917 unsigned ResultReg = getReg(I);
1919 MachineBasicBlock::iterator IP = BB->end();
1920 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1921 I.getType(), ResultReg);
1924 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1925 MachineBasicBlock::iterator IP,
1926 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1927 const Type *Ty, unsigned ResultReg) {
1928 unsigned Class = getClass(Ty);
1930 case cFP: // Floating point divide
1932 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1933 } else { // Floating point remainder...
1934 MachineInstr *TheCall =
1935 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1936 std::vector<ValueRecord> Args;
1937 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1938 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1939 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1943 static const char *FnName[] =
1944 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1946 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1947 MachineInstr *TheCall =
1948 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1950 std::vector<ValueRecord> Args;
1951 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1952 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1953 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1956 case cByte: case cShort: case cInt:
1957 break; // Small integrals, handled below...
1958 default: assert(0 && "Unknown class!");
1961 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1962 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1963 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1964 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
1965 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1967 static const unsigned DivOpcode[][4] = {
1968 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
1969 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
1972 bool isSigned = Ty->isSigned();
1973 unsigned Reg = Regs[Class];
1974 unsigned ExtReg = ExtRegs[Class];
1976 // Put the first operand into one of the A registers...
1977 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1980 // Emit a sign extension instruction...
1981 unsigned ShiftResult = makeAnotherReg(Ty);
1982 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1983 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1985 // If unsigned, emit a zeroing instruction... (reg = 0)
1986 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
1989 // Emit the appropriate divide or remainder instruction...
1990 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1992 // Figure out which register we want to pick the result out of...
1993 unsigned DestReg = isDiv ? Reg : ExtReg;
1995 // Put the result into the destination register...
1996 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2000 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2001 /// for constant immediate shift values, and for constant immediate
2002 /// shift values equal to 1. Even the general case is sort of special,
2003 /// because the shift amount has to be in CL, not just any old register.
2005 void ISel::visitShiftInst(ShiftInst &I) {
2006 MachineBasicBlock::iterator IP = BB->end ();
2007 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2008 I.getOpcode () == Instruction::Shl, I.getType (),
2012 /// emitShiftOperation - Common code shared between visitShiftInst and
2013 /// constant expression support.
2014 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2015 MachineBasicBlock::iterator IP,
2016 Value *Op, Value *ShiftAmount, bool isLeftShift,
2017 const Type *ResultTy, unsigned DestReg) {
2018 unsigned SrcReg = getReg (Op, MBB, IP);
2019 bool isSigned = ResultTy->isSigned ();
2020 unsigned Class = getClass (ResultTy);
2022 static const unsigned ConstantOperand[][4] = {
2023 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2024 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2025 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2026 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
2029 static const unsigned NonConstantOperand[][4] = {
2030 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2031 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2032 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2033 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
2036 // Longs, as usual, are handled specially...
2037 if (Class == cLong) {
2038 // If we have a constant shift, we can generate much more efficient code
2039 // than otherwise...
2041 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2042 unsigned Amount = CUI->getValue();
2044 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2046 BuildMI(*MBB, IP, Opc[3], 3,
2047 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2048 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2050 BuildMI(*MBB, IP, Opc[3], 3,
2051 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2052 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2054 } else { // Shifting more than 32 bits
2057 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2058 DestReg + 1).addReg(SrcReg).addImm(Amount);
2059 BuildMI(*MBB, IP, X86::MOV32ri, 1,
2062 unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
2063 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
2064 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2068 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2070 if (!isLeftShift && isSigned) {
2071 // If this is a SHR of a Long, then we need to do funny sign extension
2072 // stuff. TmpReg gets the value to use as the high-part if we are
2073 // shifting more than 32 bits.
2074 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
2076 // Other shifts use a fixed zero value if the shift is more than 32
2078 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2081 // Initialize CL with the shift amount...
2082 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2083 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2085 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2086 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2088 // TmpReg2 = shld inHi, inLo
2089 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2091 // TmpReg3 = shl inLo, CL
2092 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2094 // Set the flags to indicate whether the shift was by more than 32 bits.
2095 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2097 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2098 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2099 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2100 // DestLo = (>32) ? TmpReg : TmpReg3;
2101 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2102 DestReg).addReg(TmpReg3).addReg(TmpReg);
2104 // TmpReg2 = shrd inLo, inHi
2105 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2107 // TmpReg3 = s[ah]r inHi, CL
2108 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2111 // Set the flags to indicate whether the shift was by more than 32 bits.
2112 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2114 // DestLo = (>32) ? TmpReg3 : TmpReg2;
2115 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2116 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2118 // DestHi = (>32) ? TmpReg : TmpReg3;
2119 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2120 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2126 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2127 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2128 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2130 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2131 BuildMI(*MBB, IP, Opc[Class], 2,
2132 DestReg).addReg(SrcReg).addImm(CUI->getValue());
2133 } else { // The shift amount is non-constant.
2134 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2135 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2137 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2138 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2143 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2144 unsigned &IndexReg, unsigned &Disp) {
2145 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2146 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2147 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2148 BaseReg, Scale, IndexReg, Disp))
2150 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2151 if (CE->getOpcode() == Instruction::GetElementPtr)
2152 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2153 BaseReg, Scale, IndexReg, Disp))
2157 // If it's not foldable, reset addr mode.
2158 BaseReg = getReg(Addr);
2159 Scale = 1; IndexReg = 0; Disp = 0;
2163 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2164 /// instruction. The load and store instructions are the only place where we
2165 /// need to worry about the memory layout of the target machine.
2167 void ISel::visitLoadInst(LoadInst &I) {
2168 // Check to see if this load instruction is going to be folded into a binary
2169 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2170 // pattern matching instruction selector be nice?
2171 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2172 Instruction *User = cast<Instruction>(I.use_back());
2173 switch (User->getOpcode()) {
2174 default: User = 0; break;
2175 case Instruction::Add:
2176 case Instruction::Sub:
2177 case Instruction::And:
2178 case Instruction::Or:
2179 case Instruction::Xor:
2184 // Okay, we found a user. If the load is the first operand and there is
2185 // no second operand load, reverse the operand ordering. Note that this
2186 // can fail for a subtract (ie, no change will be made).
2187 if (!isa<LoadInst>(User->getOperand(1)))
2188 cast<BinaryOperator>(User)->swapOperands();
2190 // Okay, now that everything is set up, if this load is used by the second
2191 // operand, and if there are no instructions that invalidate the load
2192 // before the binary operator, eliminate the load.
2193 if (User->getOperand(1) == &I &&
2194 isSafeToFoldLoadIntoInstruction(I, *User))
2195 return; // Eliminate the load!
2199 unsigned DestReg = getReg(I);
2200 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2201 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2203 unsigned Class = getClassB(I.getType());
2204 if (Class == cLong) {
2205 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2206 BaseReg, Scale, IndexReg, Disp);
2207 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2208 BaseReg, Scale, IndexReg, Disp+4);
2212 static const unsigned Opcodes[] = {
2213 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2215 unsigned Opcode = Opcodes[Class];
2216 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2217 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2218 BaseReg, Scale, IndexReg, Disp);
2221 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2224 void ISel::visitStoreInst(StoreInst &I) {
2225 unsigned BaseReg, Scale, IndexReg, Disp;
2226 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2228 const Type *ValTy = I.getOperand(0)->getType();
2229 unsigned Class = getClassB(ValTy);
2231 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2232 uint64_t Val = CI->getRawValue();
2233 if (Class == cLong) {
2234 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2235 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2236 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2237 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2239 static const unsigned Opcodes[] = {
2240 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2242 unsigned Opcode = Opcodes[Class];
2243 addFullAddress(BuildMI(BB, Opcode, 5),
2244 BaseReg, Scale, IndexReg, Disp).addImm(Val);
2246 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2247 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2248 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2250 if (Class == cLong) {
2251 unsigned ValReg = getReg(I.getOperand(0));
2252 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2253 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2254 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2255 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2257 unsigned ValReg = getReg(I.getOperand(0));
2258 static const unsigned Opcodes[] = {
2259 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2261 unsigned Opcode = Opcodes[Class];
2262 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2263 addFullAddress(BuildMI(BB, Opcode, 1+4),
2264 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2270 /// visitCastInst - Here we have various kinds of copying with or without sign
2271 /// extension going on.
2273 void ISel::visitCastInst(CastInst &CI) {
2274 Value *Op = CI.getOperand(0);
2275 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2276 // of the case are GEP instructions, then the cast does not need to be
2277 // generated explicitly, it will be folded into the GEP.
2278 if (CI.getType() == Type::LongTy &&
2279 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2280 bool AllUsesAreGEPs = true;
2281 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2282 if (!isa<GetElementPtrInst>(*I)) {
2283 AllUsesAreGEPs = false;
2287 // No need to codegen this cast if all users are getelementptr instrs...
2288 if (AllUsesAreGEPs) return;
2291 unsigned DestReg = getReg(CI);
2292 MachineBasicBlock::iterator MI = BB->end();
2293 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2296 /// emitCastOperation - Common code shared between visitCastInst and constant
2297 /// expression cast support.
2299 void ISel::emitCastOperation(MachineBasicBlock *BB,
2300 MachineBasicBlock::iterator IP,
2301 Value *Src, const Type *DestTy,
2303 unsigned SrcReg = getReg(Src, BB, IP);
2304 const Type *SrcTy = Src->getType();
2305 unsigned SrcClass = getClassB(SrcTy);
2306 unsigned DestClass = getClassB(DestTy);
2308 // Implement casts to bool by using compare on the operand followed by set if
2309 // not zero on the result.
2310 if (DestTy == Type::BoolTy) {
2313 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2316 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2319 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2322 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2323 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2327 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2328 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2329 BuildMI(*BB, IP, X86::SAHF, 1);
2333 // If the zero flag is not set, then the value is true, set the byte to
2335 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2339 static const unsigned RegRegMove[] = {
2340 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2343 // Implement casts between values of the same type class (as determined by
2344 // getClass) by using a register-to-register move.
2345 if (SrcClass == DestClass) {
2346 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2347 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2348 } else if (SrcClass == cFP) {
2349 if (SrcTy == Type::FloatTy) { // double -> float
2350 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2351 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2352 } else { // float -> double
2353 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2354 "Unknown cFP member!");
2355 // Truncate from double to float by storing to memory as short, then
2357 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2358 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2359 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2360 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2362 } else if (SrcClass == cLong) {
2363 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2364 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2366 assert(0 && "Cannot handle this type of cast instruction!");
2372 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2373 // or zero extension, depending on whether the source type was signed.
2374 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2375 SrcClass < DestClass) {
2376 bool isLong = DestClass == cLong;
2377 if (isLong) DestClass = cInt;
2379 static const unsigned Opc[][4] = {
2380 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2381 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
2384 bool isUnsigned = SrcTy->isUnsigned();
2385 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2386 DestReg).addReg(SrcReg);
2388 if (isLong) { // Handle upper 32 bits as appropriate...
2389 if (isUnsigned) // Zero out top bits...
2390 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2391 else // Sign extend bottom half...
2392 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2397 // Special case long -> int ...
2398 if (SrcClass == cLong && DestClass == cInt) {
2399 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2403 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2404 // move out of AX or AL.
2405 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2406 && SrcClass > DestClass) {
2407 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2408 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2409 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2413 // Handle casts from integer to floating point now...
2414 if (DestClass == cFP) {
2415 // Promote the integer to a type supported by FLD. We do this because there
2416 // are no unsigned FLD instructions, so we must promote an unsigned value to
2417 // a larger signed value, then use FLD on the larger value.
2419 const Type *PromoteType = 0;
2420 unsigned PromoteOpcode;
2421 unsigned RealDestReg = DestReg;
2422 switch (SrcTy->getPrimitiveID()) {
2423 case Type::BoolTyID:
2424 case Type::SByteTyID:
2425 // We don't have the facilities for directly loading byte sized data from
2426 // memory (even signed). Promote it to 16 bits.
2427 PromoteType = Type::ShortTy;
2428 PromoteOpcode = X86::MOVSX16rr8;
2430 case Type::UByteTyID:
2431 PromoteType = Type::ShortTy;
2432 PromoteOpcode = X86::MOVZX16rr8;
2434 case Type::UShortTyID:
2435 PromoteType = Type::IntTy;
2436 PromoteOpcode = X86::MOVZX32rr16;
2438 case Type::UIntTyID: {
2439 // Make a 64 bit temporary... and zero out the top of it...
2440 unsigned TmpReg = makeAnotherReg(Type::LongTy);
2441 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2442 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2443 SrcTy = Type::LongTy;
2448 case Type::ULongTyID:
2449 // Don't fild into the read destination.
2450 DestReg = makeAnotherReg(Type::DoubleTy);
2452 default: // No promotion needed...
2457 unsigned TmpReg = makeAnotherReg(PromoteType);
2458 unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
2459 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2460 SrcTy = PromoteType;
2461 SrcClass = getClass(PromoteType);
2465 // Spill the integer to memory and reload it from there...
2467 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2469 if (SrcClass == cLong) {
2470 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2471 FrameIdx).addReg(SrcReg);
2472 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2473 FrameIdx, 4).addReg(SrcReg+1);
2475 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2476 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2477 FrameIdx).addReg(SrcReg);
2480 static const unsigned Op2[] =
2481 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2482 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2484 // We need special handling for unsigned 64-bit integer sources. If the
2485 // input number has the "sign bit" set, then we loaded it incorrectly as a
2486 // negative 64-bit number. In this case, add an offset value.
2487 if (SrcTy == Type::ULongTy) {
2488 // Emit a test instruction to see if the dynamic input value was signed.
2489 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2491 // If the sign bit is set, get a pointer to an offset, otherwise get a
2492 // pointer to a zero.
2493 MachineConstantPool *CP = F->getConstantPool();
2494 unsigned Zero = makeAnotherReg(Type::IntTy);
2495 Constant *Null = Constant::getNullValue(Type::UIntTy);
2496 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
2497 CP->getConstantPoolIndex(Null));
2498 unsigned Offset = makeAnotherReg(Type::IntTy);
2499 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2501 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2502 CP->getConstantPoolIndex(OffsetCst));
2503 unsigned Addr = makeAnotherReg(Type::IntTy);
2504 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2506 // Load the constant for an add. FIXME: this could make an 'fadd' that
2507 // reads directly from memory, but we don't support these yet.
2508 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2509 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2511 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2512 .addReg(ConstReg).addReg(DestReg);
2518 // Handle casts from floating point to integer now...
2519 if (SrcClass == cFP) {
2520 // Change the floating point control register to use "round towards zero"
2521 // mode when truncating to an integer value.
2523 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2524 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2526 // Load the old value of the high byte of the control word...
2527 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2528 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2531 // Set the high part to be round to zero...
2532 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2533 CWFrameIdx, 1).addImm(12);
2535 // Reload the modified control word now...
2536 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2538 // Restore the memory image of control word to original value
2539 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2540 CWFrameIdx, 1).addReg(HighPartOfCW);
2542 // We don't have the facilities for directly storing byte sized data to
2543 // memory. Promote it to 16 bits. We also must promote unsigned values to
2544 // larger classes because we only have signed FP stores.
2545 unsigned StoreClass = DestClass;
2546 const Type *StoreTy = DestTy;
2547 if (StoreClass == cByte || DestTy->isUnsigned())
2548 switch (StoreClass) {
2549 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2550 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2551 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
2552 // The following treatment of cLong may not be perfectly right,
2553 // but it survives chains of casts of the form
2554 // double->ulong->double.
2555 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
2556 default: assert(0 && "Unknown store class!");
2559 // Spill the integer to memory and reload it from there...
2561 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2563 static const unsigned Op1[] =
2564 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2565 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2566 FrameIdx).addReg(SrcReg);
2568 if (DestClass == cLong) {
2569 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2570 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2573 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2574 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2577 // Reload the original control word now...
2578 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2582 // Anything we haven't handled already, we can't (yet) handle at all.
2583 assert(0 && "Unhandled cast instruction!");
2587 /// visitVANextInst - Implement the va_next instruction...
2589 void ISel::visitVANextInst(VANextInst &I) {
2590 unsigned VAList = getReg(I.getOperand(0));
2591 unsigned DestReg = getReg(I);
2594 switch (I.getArgType()->getPrimitiveID()) {
2597 assert(0 && "Error: bad type for va_next instruction!");
2599 case Type::PointerTyID:
2600 case Type::UIntTyID:
2604 case Type::ULongTyID:
2605 case Type::LongTyID:
2606 case Type::DoubleTyID:
2611 // Increment the VAList pointer...
2612 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2615 void ISel::visitVAArgInst(VAArgInst &I) {
2616 unsigned VAList = getReg(I.getOperand(0));
2617 unsigned DestReg = getReg(I);
2619 switch (I.getType()->getPrimitiveID()) {
2622 assert(0 && "Error: bad type for va_next instruction!");
2624 case Type::PointerTyID:
2625 case Type::UIntTyID:
2627 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2629 case Type::ULongTyID:
2630 case Type::LongTyID:
2631 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2632 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2634 case Type::DoubleTyID:
2635 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2640 /// visitGetElementPtrInst - instruction-select GEP instructions
2642 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2643 // If this GEP instruction will be folded into all of its users, we don't need
2644 // to explicitly calculate it!
2645 unsigned A, B, C, D;
2646 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2647 // Check all of the users of the instruction to see if they are loads and
2649 bool AllWillFold = true;
2650 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2651 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2652 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2653 cast<Instruction>(*UI)->getOperand(0) == &I) {
2654 AllWillFold = false;
2658 // If the instruction is foldable, and will be folded into all users, don't
2660 if (AllWillFold) return;
2663 unsigned outputReg = getReg(I);
2664 emitGEPOperation(BB, BB->end(), I.getOperand(0),
2665 I.op_begin()+1, I.op_end(), outputReg);
2668 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2669 /// GEPTypes (the derived types being stepped through at each level). On return
2670 /// from this function, if some indexes of the instruction are representable as
2671 /// an X86 lea instruction, the machine operands are put into the Ops
2672 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2673 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2674 /// addressing mode that only partially consumes the input, the BaseReg input of
2675 /// the addressing mode must be left free.
2677 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2679 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2680 std::vector<Value*> &GEPOps,
2681 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2682 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2683 const TargetData &TD = TM.getTargetData();
2685 // Clear out the state we are working with...
2686 BaseReg = 0; // No base register
2687 Scale = 1; // Unit scale
2688 IndexReg = 0; // No index register
2689 Disp = 0; // No displacement
2691 // While there are GEP indexes that can be folded into the current address,
2692 // keep processing them.
2693 while (!GEPTypes.empty()) {
2694 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2695 // It's a struct access. CUI is the index into the structure,
2696 // which names the field. This index must have unsigned type.
2697 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2699 // Use the TargetData structure to pick out what the layout of the
2700 // structure is in memory. Since the structure index must be constant, we
2701 // can get its value and use it to find the right byte offset from the
2702 // StructLayout class's list of structure member offsets.
2703 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2704 GEPOps.pop_back(); // Consume a GEP operand
2705 GEPTypes.pop_back();
2707 // It's an array or pointer access: [ArraySize x ElementType].
2708 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2709 Value *idx = GEPOps.back();
2711 // idx is the index into the array. Unlike with structure
2712 // indices, we may not know its actual value at code-generation
2714 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2716 // If idx is a constant, fold it into the offset.
2717 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2718 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2719 Disp += TypeSize*CSI->getValue();
2721 // If the index reg is already taken, we can't handle this index.
2722 if (IndexReg) return;
2724 // If this is a size that we can handle, then add the index as
2726 case 1: case 2: case 4: case 8:
2727 // These are all acceptable scales on X86.
2731 // Otherwise, we can't handle this scale
2735 if (CastInst *CI = dyn_cast<CastInst>(idx))
2736 if (CI->getOperand(0)->getType() == Type::IntTy ||
2737 CI->getOperand(0)->getType() == Type::UIntTy)
2738 idx = CI->getOperand(0);
2740 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2743 GEPOps.pop_back(); // Consume a GEP operand
2744 GEPTypes.pop_back();
2748 // GEPTypes is empty, which means we have a single operand left. See if we
2749 // can set it as the base register.
2751 // FIXME: When addressing modes are more powerful/correct, we could load
2752 // global addresses directly as 32-bit immediates.
2753 assert(BaseReg == 0);
2754 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2755 GEPOps.pop_back(); // Consume the last GEP operand
2759 /// isGEPFoldable - Return true if the specified GEP can be completely
2760 /// folded into the addressing mode of a load/store or lea instruction.
2761 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2762 Value *Src, User::op_iterator IdxBegin,
2763 User::op_iterator IdxEnd, unsigned &BaseReg,
2764 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2765 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2766 Src = CPR->getValue();
2768 std::vector<Value*> GEPOps;
2769 GEPOps.resize(IdxEnd-IdxBegin+1);
2771 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2773 std::vector<const Type*> GEPTypes;
2774 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2775 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2777 MachineBasicBlock::iterator IP;
2778 if (MBB) IP = MBB->end();
2779 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2781 // We can fold it away iff the getGEPIndex call eliminated all operands.
2782 return GEPOps.empty();
2785 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2786 MachineBasicBlock::iterator IP,
2787 Value *Src, User::op_iterator IdxBegin,
2788 User::op_iterator IdxEnd, unsigned TargetReg) {
2789 const TargetData &TD = TM.getTargetData();
2790 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2791 Src = CPR->getValue();
2793 std::vector<Value*> GEPOps;
2794 GEPOps.resize(IdxEnd-IdxBegin+1);
2796 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2798 std::vector<const Type*> GEPTypes;
2799 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2800 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2802 // Keep emitting instructions until we consume the entire GEP instruction.
2803 while (!GEPOps.empty()) {
2804 unsigned OldSize = GEPOps.size();
2805 unsigned BaseReg, Scale, IndexReg, Disp;
2806 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2808 if (GEPOps.size() != OldSize) {
2809 // getGEPIndex consumed some of the input. Build an LEA instruction here.
2810 unsigned NextTarget = 0;
2811 if (!GEPOps.empty()) {
2812 assert(BaseReg == 0 &&
2813 "getGEPIndex should have left the base register open for chaining!");
2814 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2817 if (IndexReg == 0 && Disp == 0)
2818 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2820 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
2821 BaseReg, Scale, IndexReg, Disp);
2823 TargetReg = NextTarget;
2824 } else if (GEPTypes.empty()) {
2825 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2826 // all operands are consumed but the base pointer. If so, just load it
2827 // into the register.
2828 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2829 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
2831 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2832 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2834 break; // we are now done
2837 // It's an array or pointer access: [ArraySize x ElementType].
2838 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2839 Value *idx = GEPOps.back();
2840 GEPOps.pop_back(); // Consume a GEP operand
2841 GEPTypes.pop_back();
2843 // idx is the index into the array. Unlike with structure
2844 // indices, we may not know its actual value at code-generation
2846 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2848 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2849 // operand on X86. Handle this case directly now...
2850 if (CastInst *CI = dyn_cast<CastInst>(idx))
2851 if (CI->getOperand(0)->getType() == Type::IntTy ||
2852 CI->getOperand(0)->getType() == Type::UIntTy)
2853 idx = CI->getOperand(0);
2855 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2856 // must find the size of the pointed-to type (Not coincidentally, the next
2857 // type is the type of the elements in the array).
2858 const Type *ElTy = SqTy->getElementType();
2859 unsigned elementSize = TD.getTypeSize(ElTy);
2861 // If idxReg is a constant, we don't need to perform the multiply!
2862 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2863 if (!CSI->isNullValue()) {
2864 unsigned Offset = elementSize*CSI->getValue();
2865 unsigned Reg = makeAnotherReg(Type::UIntTy);
2866 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
2867 .addReg(Reg).addImm(Offset);
2868 --IP; // Insert the next instruction before this one.
2869 TargetReg = Reg; // Codegen the rest of the GEP into this
2871 } else if (elementSize == 1) {
2872 // If the element size is 1, we don't have to multiply, just add
2873 unsigned idxReg = getReg(idx, MBB, IP);
2874 unsigned Reg = makeAnotherReg(Type::UIntTy);
2875 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
2876 --IP; // Insert the next instruction before this one.
2877 TargetReg = Reg; // Codegen the rest of the GEP into this
2879 unsigned idxReg = getReg(idx, MBB, IP);
2880 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2882 // Make sure we can back the iterator up to point to the first
2883 // instruction emitted.
2884 MachineBasicBlock::iterator BeforeIt = IP;
2885 if (IP == MBB->begin())
2886 BeforeIt = MBB->end();
2889 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2891 // Emit an ADD to add OffsetReg to the basePtr.
2892 unsigned Reg = makeAnotherReg(Type::UIntTy);
2893 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
2894 .addReg(Reg).addReg(OffsetReg);
2896 // Step to the first instruction of the multiply.
2897 if (BeforeIt == MBB->end())
2902 TargetReg = Reg; // Codegen the rest of the GEP into this
2909 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2910 /// frame manager, otherwise do it the hard way.
2912 void ISel::visitAllocaInst(AllocaInst &I) {
2913 // Find the data size of the alloca inst's getAllocatedType.
2914 const Type *Ty = I.getAllocatedType();
2915 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2917 // If this is a fixed size alloca in the entry block for the function,
2918 // statically stack allocate the space.
2920 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2921 if (I.getParent() == I.getParent()->getParent()->begin()) {
2922 TySize *= CUI->getValue(); // Get total allocated size...
2923 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2925 // Create a new stack object using the frame manager...
2926 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2927 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
2932 // Create a register to hold the temporary result of multiplying the type size
2933 // constant by the variable amount.
2934 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2935 unsigned SrcReg1 = getReg(I.getArraySize());
2937 // TotalSizeReg = mul <numelements>, <TypeSize>
2938 MachineBasicBlock::iterator MBBI = BB->end();
2939 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2941 // AddedSize = add <TotalSizeReg>, 15
2942 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2943 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2945 // AlignedSize = and <AddedSize>, ~15
2946 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2947 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2949 // Subtract size from stack pointer, thereby allocating some space.
2950 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2952 // Put a pointer to the space into the result register, by copying
2953 // the stack pointer.
2954 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
2956 // Inform the Frame Information that we have just allocated a variable-sized
2958 F->getFrameInfo()->CreateVariableSizedObject();
2961 /// visitMallocInst - Malloc instructions are code generated into direct calls
2962 /// to the library malloc.
2964 void ISel::visitMallocInst(MallocInst &I) {
2965 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2968 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2969 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2971 Arg = makeAnotherReg(Type::UIntTy);
2972 unsigned Op0Reg = getReg(I.getOperand(0));
2973 MachineBasicBlock::iterator MBBI = BB->end();
2974 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2977 std::vector<ValueRecord> Args;
2978 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2979 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2980 1).addExternalSymbol("malloc", true);
2981 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2985 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2988 void ISel::visitFreeInst(FreeInst &I) {
2989 std::vector<ValueRecord> Args;
2990 Args.push_back(ValueRecord(I.getOperand(0)));
2991 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2992 1).addExternalSymbol("free", true);
2993 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2996 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2997 /// into a machine code representation is a very simple peep-hole fashion. The
2998 /// generated code sucks but the implementation is nice and simple.
3000 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3001 return new ISel(TM);