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.
110 void LowerUnknownIntrinsicFunctionCalls(Function &F);
112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
115 void LoadArgumentsToVirtualRegs(Function &F);
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
121 void SelectPHINodes();
123 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
124 /// that need them. This only occurs due to the floating point stackifier
125 /// not being aggressive enough to handle arbitrary global stackification.
127 void InsertFPRegKills();
129 // Visitation methods for various instructions. These methods simply emit
130 // fixed X86 code for each instruction.
133 // Control flow operators
134 void visitReturnInst(ReturnInst &RI);
135 void visitBranchInst(BranchInst &BI);
141 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
142 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
144 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
145 const std::vector<ValueRecord> &Args);
146 void visitCallInst(CallInst &I);
147 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
149 // Arithmetic operators
150 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
151 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
152 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
153 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
154 unsigned DestReg, const Type *DestTy,
155 unsigned Op0Reg, unsigned Op1Reg);
156 void doMultiplyConst(MachineBasicBlock *MBB,
157 MachineBasicBlock::iterator MBBI,
158 unsigned DestReg, const Type *DestTy,
159 unsigned Op0Reg, unsigned Op1Val);
160 void visitMul(BinaryOperator &B);
162 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
163 void visitRem(BinaryOperator &B) { visitDivRem(B); }
164 void visitDivRem(BinaryOperator &B);
167 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
168 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
169 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
171 // Comparison operators...
172 void visitSetCondInst(SetCondInst &I);
173 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
174 MachineBasicBlock *MBB,
175 MachineBasicBlock::iterator MBBI);
177 // Memory Instructions
178 void visitLoadInst(LoadInst &I);
179 void visitStoreInst(StoreInst &I);
180 void visitGetElementPtrInst(GetElementPtrInst &I);
181 void visitAllocaInst(AllocaInst &I);
182 void visitMallocInst(MallocInst &I);
183 void visitFreeInst(FreeInst &I);
186 void visitShiftInst(ShiftInst &I);
187 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
188 void visitCastInst(CastInst &I);
189 void visitVANextInst(VANextInst &I);
190 void visitVAArgInst(VAArgInst &I);
192 void visitInstruction(Instruction &I) {
193 std::cerr << "Cannot instruction select: " << I;
197 /// promote32 - Make a value 32-bits wide, and put it somewhere.
199 void promote32(unsigned targetReg, const ValueRecord &VR);
201 // getGEPIndex - This is used to fold GEP instructions into X86 addressing
203 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
204 std::vector<Value*> &GEPOps,
205 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
206 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
208 /// isGEPFoldable - Return true if the specified GEP can be completely
209 /// folded into the addressing mode of a load/store or lea instruction.
210 bool isGEPFoldable(MachineBasicBlock *MBB,
211 Value *Src, User::op_iterator IdxBegin,
212 User::op_iterator IdxEnd, unsigned &BaseReg,
213 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
215 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
216 /// constant expression GEP support.
218 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
219 Value *Src, User::op_iterator IdxBegin,
220 User::op_iterator IdxEnd, unsigned TargetReg);
222 /// emitCastOperation - Common code shared between visitCastInst and
223 /// constant expression cast support.
224 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
225 Value *Src, const Type *DestTy, unsigned TargetReg);
227 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
228 /// and constant expression support.
229 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
230 MachineBasicBlock::iterator IP,
231 Value *Op0, Value *Op1,
232 unsigned OperatorClass, unsigned TargetReg);
234 void emitDivRemOperation(MachineBasicBlock *BB,
235 MachineBasicBlock::iterator IP,
236 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
237 const Type *Ty, unsigned TargetReg);
239 /// emitSetCCOperation - Common code shared between visitSetCondInst and
240 /// constant expression support.
241 void emitSetCCOperation(MachineBasicBlock *BB,
242 MachineBasicBlock::iterator IP,
243 Value *Op0, Value *Op1, unsigned Opcode,
246 /// emitShiftOperation - Common code shared between visitShiftInst and
247 /// constant expression support.
248 void emitShiftOperation(MachineBasicBlock *MBB,
249 MachineBasicBlock::iterator IP,
250 Value *Op, Value *ShiftAmount, bool isLeftShift,
251 const Type *ResultTy, unsigned DestReg);
254 /// copyConstantToRegister - Output the instructions required to put the
255 /// specified constant into the specified register.
257 void copyConstantToRegister(MachineBasicBlock *MBB,
258 MachineBasicBlock::iterator MBBI,
259 Constant *C, unsigned Reg);
261 /// makeAnotherReg - This method returns the next register number we haven't
264 /// Long values are handled somewhat specially. They are always allocated
265 /// as pairs of 32 bit integer values. The register number returned is the
266 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
267 /// of the long value.
269 unsigned makeAnotherReg(const Type *Ty) {
270 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
271 "Current target doesn't have X86 reg info??");
272 const X86RegisterInfo *MRI =
273 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
274 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
275 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
276 // Create the lower part
277 F->getSSARegMap()->createVirtualRegister(RC);
278 // Create the upper part.
279 return F->getSSARegMap()->createVirtualRegister(RC)-1;
282 // Add the mapping of regnumber => reg class to MachineFunction
283 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
284 return F->getSSARegMap()->createVirtualRegister(RC);
287 /// getReg - This method turns an LLVM value into a register number. This
288 /// is guaranteed to produce the same register number for a particular value
289 /// every time it is queried.
291 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
292 unsigned getReg(Value *V) {
293 // Just append to the end of the current bb.
294 MachineBasicBlock::iterator It = BB->end();
295 return getReg(V, BB, It);
297 unsigned getReg(Value *V, MachineBasicBlock *MBB,
298 MachineBasicBlock::iterator IPt) {
299 unsigned &Reg = RegMap[V];
301 Reg = makeAnotherReg(V->getType());
305 // If this operand is a constant, emit the code to copy the constant into
306 // the register here...
308 if (Constant *C = dyn_cast<Constant>(V)) {
309 copyConstantToRegister(MBB, IPt, C, Reg);
310 RegMap.erase(V); // Assign a new name to this constant if ref'd again
311 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
312 // Move the address of the global into the register
313 BuildMI(*MBB, IPt, X86::MOVri32, 1, Reg).addGlobalAddress(GV);
314 RegMap.erase(V); // Assign a new name to this address if ref'd again
322 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
326 cByte, cShort, cInt, cFP, cLong
329 /// getClass - Turn a primitive type into a "class" number which is based on the
330 /// size of the type, and whether or not it is floating point.
332 static inline TypeClass getClass(const Type *Ty) {
333 switch (Ty->getPrimitiveID()) {
334 case Type::SByteTyID:
335 case Type::UByteTyID: return cByte; // Byte operands are class #0
336 case Type::ShortTyID:
337 case Type::UShortTyID: return cShort; // Short operands are class #1
340 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
342 case Type::FloatTyID:
343 case Type::DoubleTyID: return cFP; // Floating Point is #3
346 case Type::ULongTyID: return cLong; // Longs are class #4
348 assert(0 && "Invalid type to getClass!");
349 return cByte; // not reached
353 // getClassB - Just like getClass, but treat boolean values as bytes.
354 static inline TypeClass getClassB(const Type *Ty) {
355 if (Ty == Type::BoolTy) return cByte;
360 /// copyConstantToRegister - Output the instructions required to put the
361 /// specified constant into the specified register.
363 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
364 MachineBasicBlock::iterator IP,
365 Constant *C, unsigned R) {
366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
368 switch (CE->getOpcode()) {
369 case Instruction::GetElementPtr:
370 emitGEPOperation(MBB, IP, CE->getOperand(0),
371 CE->op_begin()+1, CE->op_end(), R);
373 case Instruction::Cast:
374 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
377 case Instruction::Xor: ++Class; // FALL THROUGH
378 case Instruction::Or: ++Class; // FALL THROUGH
379 case Instruction::And: ++Class; // FALL THROUGH
380 case Instruction::Sub: ++Class; // FALL THROUGH
381 case Instruction::Add:
382 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
386 case Instruction::Mul: {
387 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
388 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
389 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
392 case Instruction::Div:
393 case Instruction::Rem: {
394 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
395 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
396 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
397 CE->getOpcode() == Instruction::Div,
402 case Instruction::SetNE:
403 case Instruction::SetEQ:
404 case Instruction::SetLT:
405 case Instruction::SetGT:
406 case Instruction::SetLE:
407 case Instruction::SetGE:
408 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
412 case Instruction::Shl:
413 case Instruction::Shr:
414 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
415 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
419 std::cerr << "Offending expr: " << C << "\n";
420 assert(0 && "Constant expression not yet handled!\n");
424 if (C->getType()->isIntegral()) {
425 unsigned Class = getClassB(C->getType());
427 if (Class == cLong) {
428 // Copy the value into the register pair.
429 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
430 BuildMI(*MBB, IP, X86::MOVri32, 1, R).addImm(Val & 0xFFFFFFFF);
431 BuildMI(*MBB, IP, X86::MOVri32, 1, R+1).addImm(Val >> 32);
435 assert(Class <= cInt && "Type not handled yet!");
437 static const unsigned IntegralOpcodeTab[] = {
438 X86::MOVri8, X86::MOVri16, X86::MOVri32
441 if (C->getType() == Type::BoolTy) {
442 BuildMI(*MBB, IP, X86::MOVri8, 1, R).addImm(C == ConstantBool::True);
444 ConstantInt *CI = cast<ConstantInt>(C);
445 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
447 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
448 if (CFP->isExactlyValue(+0.0))
449 BuildMI(*MBB, IP, X86::FLD0, 0, R);
450 else if (CFP->isExactlyValue(+1.0))
451 BuildMI(*MBB, IP, X86::FLD1, 0, R);
453 // Otherwise we need to spill the constant to memory...
454 MachineConstantPool *CP = F->getConstantPool();
455 unsigned CPI = CP->getConstantPoolIndex(CFP);
456 const Type *Ty = CFP->getType();
458 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
459 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDm32 : X86::FLDm64;
460 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
463 } else if (isa<ConstantPointerNull>(C)) {
464 // Copy zero (null pointer) to the register.
465 BuildMI(*MBB, IP, X86::MOVri32, 1, R).addImm(0);
466 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
467 BuildMI(*MBB, IP, X86::MOVri32, 1, R).addGlobalAddress(CPR->getValue());
469 std::cerr << "Offending constant: " << C << "\n";
470 assert(0 && "Type not handled yet!");
474 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
475 /// the stack into virtual registers.
477 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
478 // Emit instructions to load the arguments... On entry to a function on the
479 // X86, the stack frame looks like this:
481 // [ESP] -- return address
482 // [ESP + 4] -- first argument (leftmost lexically)
483 // [ESP + 8] -- second argument, if first argument is four bytes in size
486 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
487 MachineFrameInfo *MFI = F->getFrameInfo();
489 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
490 unsigned Reg = getReg(*I);
492 int FI; // Frame object index
493 switch (getClassB(I->getType())) {
495 FI = MFI->CreateFixedObject(1, ArgOffset);
496 addFrameReference(BuildMI(BB, X86::MOVrm8, 4, Reg), FI);
499 FI = MFI->CreateFixedObject(2, ArgOffset);
500 addFrameReference(BuildMI(BB, X86::MOVrm16, 4, Reg), FI);
503 FI = MFI->CreateFixedObject(4, ArgOffset);
504 addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
507 FI = MFI->CreateFixedObject(8, ArgOffset);
508 addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
509 addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg+1), FI, 4);
510 ArgOffset += 4; // longs require 4 additional bytes
514 if (I->getType() == Type::FloatTy) {
515 Opcode = X86::FLDm32;
516 FI = MFI->CreateFixedObject(4, ArgOffset);
518 Opcode = X86::FLDm64;
519 FI = MFI->CreateFixedObject(8, ArgOffset);
520 ArgOffset += 4; // doubles require 4 additional bytes
522 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
525 assert(0 && "Unhandled argument type!");
527 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
530 // If the function takes variable number of arguments, add a frame offset for
531 // the start of the first vararg value... this is used to expand
533 if (Fn.getFunctionType()->isVarArg())
534 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
538 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
539 /// because we have to generate our sources into the source basic blocks, not
542 void ISel::SelectPHINodes() {
543 const TargetInstrInfo &TII = TM.getInstrInfo();
544 const Function &LF = *F->getFunction(); // The LLVM function...
545 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
546 const BasicBlock *BB = I;
547 MachineBasicBlock &MBB = *MBBMap[I];
549 // Loop over all of the PHI nodes in the LLVM basic block...
550 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
551 for (BasicBlock::const_iterator I = BB->begin();
552 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
554 // Create a new machine instr PHI node, and insert it.
555 unsigned PHIReg = getReg(*PN);
556 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
557 X86::PHI, PN->getNumOperands(), PHIReg);
559 MachineInstr *LongPhiMI = 0;
560 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
561 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
562 X86::PHI, PN->getNumOperands(), PHIReg+1);
564 // PHIValues - Map of blocks to incoming virtual registers. We use this
565 // so that we only initialize one incoming value for a particular block,
566 // even if the block has multiple entries in the PHI node.
568 std::map<MachineBasicBlock*, unsigned> PHIValues;
570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
571 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
573 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
574 PHIValues.lower_bound(PredMBB);
576 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
577 // We already inserted an initialization of the register for this
578 // predecessor. Recycle it.
579 ValReg = EntryIt->second;
582 // Get the incoming value into a virtual register.
584 Value *Val = PN->getIncomingValue(i);
586 // If this is a constant or GlobalValue, we may have to insert code
587 // into the basic block to compute it into a virtual register.
588 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
589 // Because we don't want to clobber any values which might be in
590 // physical registers with the computation of this constant (which
591 // might be arbitrarily complex if it is a constant expression),
592 // just insert the computation at the top of the basic block.
593 MachineBasicBlock::iterator PI = PredMBB->begin();
595 // Skip over any PHI nodes though!
596 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
599 ValReg = getReg(Val, PredMBB, PI);
601 ValReg = getReg(Val);
604 // Remember that we inserted a value for this PHI for this predecessor
605 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
608 PhiMI->addRegOperand(ValReg);
609 PhiMI->addMachineBasicBlockOperand(PredMBB);
611 LongPhiMI->addRegOperand(ValReg+1);
612 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
616 // Now that we emitted all of the incoming values for the PHI node, make
617 // sure to reposition the InsertPoint after the PHI that we just added.
618 // This is needed because we might have inserted a constant into this
619 // block, right after the PHI's which is before the old insert point!
620 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
626 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
627 /// compensation code on critical edges. As such, it requires that we kill all
628 /// FP registers on the exit from any blocks that either ARE critical edges, or
629 /// branch to a block that has incoming critical edges.
631 /// Note that this kill instruction will eventually be eliminated when
632 /// restrictions in the stackifier are relaxed.
634 static bool RequiresFPRegKill(const BasicBlock *BB) {
636 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
637 const BasicBlock *Succ = *SI;
638 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
639 ++PI; // Block have at least one predecessory
640 if (PI != PE) { // If it has exactly one, this isn't crit edge
641 // If this block has more than one predecessor, check all of the
642 // predecessors to see if they have multiple successors. If so, then the
643 // block we are analyzing needs an FPRegKill.
644 for (PI = pred_begin(Succ); PI != PE; ++PI) {
645 const BasicBlock *Pred = *PI;
646 succ_const_iterator SI2 = succ_begin(Pred);
647 ++SI2; // There must be at least one successor of this block.
648 if (SI2 != succ_end(Pred))
649 return true; // Yes, we must insert the kill on this edge.
653 // If we got this far, there is no need to insert the kill instruction.
660 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
661 // need them. This only occurs due to the floating point stackifier not being
662 // aggressive enough to handle arbitrary global stackification.
664 // Currently we insert an FP_REG_KILL instruction into each block that uses or
665 // defines a floating point virtual register.
667 // When the global register allocators (like linear scan) finally update live
668 // variable analysis, we can keep floating point values in registers across
669 // portions of the CFG that do not involve critical edges. This will be a big
670 // win, but we are waiting on the global allocators before we can do this.
672 // With a bit of work, the floating point stackifier pass can be enhanced to
673 // break critical edges as needed (to make a place to put compensation code),
674 // but this will require some infrastructure improvements as well.
676 void ISel::InsertFPRegKills() {
677 SSARegMap &RegMap = *F->getSSARegMap();
679 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
680 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
681 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
682 MachineOperand& MO = I->getOperand(i);
683 if (MO.isRegister() && MO.getReg()) {
684 unsigned Reg = MO.getReg();
685 if (MRegisterInfo::isVirtualRegister(Reg))
686 if (RegMap.getRegClass(Reg)->getSize() == 10)
690 // If we haven't found an FP register use or def in this basic block, check
691 // to see if any of our successors has an FP PHI node, which will cause a
692 // copy to be inserted into this block.
693 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
694 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
695 MachineBasicBlock *SBB = MBBMap[*SI];
696 for (MachineBasicBlock::iterator I = SBB->begin();
697 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
698 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
704 // Okay, this block uses an FP register. If the block has successors (ie,
705 // it's not an unwind/return), insert the FP_REG_KILL instruction.
706 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
707 RequiresFPRegKill(BB->getBasicBlock())) {
708 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
715 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
716 // the conditional branch instruction which is the only user of the cc
717 // instruction. This is the case if the conditional branch is the only user of
718 // the setcc, and if the setcc is in the same basic block as the conditional
719 // branch. We also don't handle long arguments below, so we reject them here as
722 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
723 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
724 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
725 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
726 const Type *Ty = SCI->getOperand(0)->getType();
727 if (Ty != Type::LongTy && Ty != Type::ULongTy)
733 // Return a fixed numbering for setcc instructions which does not depend on the
734 // order of the opcodes.
736 static unsigned getSetCCNumber(unsigned Opcode) {
738 default: assert(0 && "Unknown setcc instruction!");
739 case Instruction::SetEQ: return 0;
740 case Instruction::SetNE: return 1;
741 case Instruction::SetLT: return 2;
742 case Instruction::SetGE: return 3;
743 case Instruction::SetGT: return 4;
744 case Instruction::SetLE: return 5;
748 // LLVM -> X86 signed X86 unsigned
749 // ----- ---------- ------------
750 // seteq -> sete sete
751 // setne -> setne setne
752 // setlt -> setl setb
753 // setge -> setge setae
754 // setgt -> setg seta
755 // setle -> setle setbe
757 // sets // Used by comparison with 0 optimization
759 static const unsigned SetCCOpcodeTab[2][8] = {
760 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
762 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
763 X86::SETSr, X86::SETNSr },
766 // EmitComparison - This function emits a comparison of the two operands,
767 // returning the extended setcc code to use.
768 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
769 MachineBasicBlock *MBB,
770 MachineBasicBlock::iterator IP) {
771 // The arguments are already supposed to be of the same type.
772 const Type *CompTy = Op0->getType();
773 unsigned Class = getClassB(CompTy);
774 unsigned Op0r = getReg(Op0, MBB, IP);
776 // Special case handling of: cmp R, i
777 if (Class == cByte || Class == cShort || Class == cInt)
778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
779 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
781 // Mask off any upper bits of the constant, if there are any...
782 Op1v &= (1ULL << (8 << Class)) - 1;
784 // If this is a comparison against zero, emit more efficient code. We
785 // can't handle unsigned comparisons against zero unless they are == or
786 // !=. These should have been strength reduced already anyway.
787 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
788 static const unsigned TESTTab[] = {
789 X86::TESTrr8, X86::TESTrr16, X86::TESTrr32
791 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
793 if (OpNum == 2) return 6; // Map jl -> js
794 if (OpNum == 3) return 7; // Map jg -> jns
798 static const unsigned CMPTab[] = {
799 X86::CMPri8, X86::CMPri16, X86::CMPri32
802 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
806 // Special case handling of comparison against +/- 0.0
807 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
808 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
809 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
810 BuildMI(*MBB, IP, X86::FNSTSWr8, 0);
811 BuildMI(*MBB, IP, X86::SAHF, 1);
815 unsigned Op1r = getReg(Op1, MBB, IP);
817 default: assert(0 && "Unknown type class!");
818 // Emit: cmp <var1>, <var2> (do the comparison). We can
819 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
822 BuildMI(*MBB, IP, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
825 BuildMI(*MBB, IP, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
828 BuildMI(*MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
831 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
832 BuildMI(*MBB, IP, X86::FNSTSWr8, 0);
833 BuildMI(*MBB, IP, X86::SAHF, 1);
837 if (OpNum < 2) { // seteq, setne
838 unsigned LoTmp = makeAnotherReg(Type::IntTy);
839 unsigned HiTmp = makeAnotherReg(Type::IntTy);
840 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
841 BuildMI(*MBB, IP, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
842 BuildMI(*MBB, IP, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
843 BuildMI(*MBB, IP, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
844 break; // Allow the sete or setne to be generated from flags set by OR
846 // Emit a sequence of code which compares the high and low parts once
847 // each, then uses a conditional move to handle the overflow case. For
848 // example, a setlt for long would generate code like this:
850 // AL = lo(op1) < lo(op2) // Signedness depends on operands
851 // BL = hi(op1) < hi(op2) // Always unsigned comparison
852 // dest = hi(op1) == hi(op2) ? AL : BL;
855 // FIXME: This would be much better if we had hierarchical register
856 // classes! Until then, hardcode registers so that we can deal with their
857 // aliases (because we don't have conditional byte moves).
859 BuildMI(*MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
860 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
861 BuildMI(*MBB, IP, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
862 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
863 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
864 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
865 BuildMI(*MBB, IP, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX)
867 // NOTE: visitSetCondInst knows that the value is dumped into the BL
868 // register at this point for long values...
876 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
877 /// register, then move it to wherever the result should be.
879 void ISel::visitSetCondInst(SetCondInst &I) {
880 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
882 unsigned DestReg = getReg(I);
883 MachineBasicBlock::iterator MII = BB->end();
884 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
888 /// emitSetCCOperation - Common code shared between visitSetCondInst and
889 /// constant expression support.
890 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
891 MachineBasicBlock::iterator IP,
892 Value *Op0, Value *Op1, unsigned Opcode,
893 unsigned TargetReg) {
894 unsigned OpNum = getSetCCNumber(Opcode);
895 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
897 const Type *CompTy = Op0->getType();
898 unsigned CompClass = getClassB(CompTy);
899 bool isSigned = CompTy->isSigned() && CompClass != cFP;
901 if (CompClass != cLong || OpNum < 2) {
902 // Handle normal comparisons with a setcc instruction...
903 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
905 // Handle long comparisons by copying the value which is already in BL into
906 // the register we want...
907 BuildMI(*MBB, IP, X86::MOVrr8, 1, TargetReg).addReg(X86::BL);
914 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
915 /// operand, in the specified target register.
916 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
917 bool isUnsigned = VR.Ty->isUnsigned();
919 // Make sure we have the register number for this value...
920 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
922 switch (getClassB(VR.Ty)) {
924 // Extend value into target register (8->32)
926 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(Reg);
928 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(Reg);
931 // Extend value into target register (16->32)
933 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(Reg);
935 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(Reg);
938 // Move value into target register (32->32)
939 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(Reg);
942 assert(0 && "Unpromotable operand class in promote32");
946 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
947 /// we have the following possibilities:
949 /// ret void: No return value, simply emit a 'ret' instruction
950 /// ret sbyte, ubyte : Extend value into EAX and return
951 /// ret short, ushort: Extend value into EAX and return
952 /// ret int, uint : Move value into EAX and return
953 /// ret pointer : Move value into EAX and return
954 /// ret long, ulong : Move value into EAX/EDX and return
955 /// ret float/double : Top of FP stack
957 void ISel::visitReturnInst(ReturnInst &I) {
958 if (I.getNumOperands() == 0) {
959 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
963 Value *RetVal = I.getOperand(0);
964 unsigned RetReg = getReg(RetVal);
965 switch (getClassB(RetVal->getType())) {
966 case cByte: // integral return values: extend or move into EAX and return
969 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
970 // Declare that EAX is live on exit
971 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
973 case cFP: // Floats & Doubles: Return in ST(0)
974 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
975 // Declare that top-of-stack is live on exit
976 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
979 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
980 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
981 // Declare that EAX & EDX are live on exit
982 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
988 // Emit a 'ret' instruction
989 BuildMI(BB, X86::RET, 0);
992 // getBlockAfter - Return the basic block which occurs lexically after the
994 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
995 Function::iterator I = BB; ++I; // Get iterator to next block
996 return I != BB->getParent()->end() ? &*I : 0;
999 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1000 /// that since code layout is frozen at this point, that if we are trying to
1001 /// jump to a block that is the immediate successor of the current block, we can
1002 /// just make a fall-through (but we don't currently).
1004 void ISel::visitBranchInst(BranchInst &BI) {
1005 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1007 if (!BI.isConditional()) { // Unconditional branch?
1008 if (BI.getSuccessor(0) != NextBB)
1009 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1013 // See if we can fold the setcc into the branch itself...
1014 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1016 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1017 // computed some other way...
1018 unsigned condReg = getReg(BI.getCondition());
1019 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addImm(0);
1020 if (BI.getSuccessor(1) == NextBB) {
1021 if (BI.getSuccessor(0) != NextBB)
1022 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1024 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1026 if (BI.getSuccessor(0) != NextBB)
1027 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1032 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1033 MachineBasicBlock::iterator MII = BB->end();
1034 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1036 const Type *CompTy = SCI->getOperand(0)->getType();
1037 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1040 // LLVM -> X86 signed X86 unsigned
1041 // ----- ---------- ------------
1049 // js // Used by comparison with 0 optimization
1052 static const unsigned OpcodeTab[2][8] = {
1053 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1054 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1055 X86::JS, X86::JNS },
1058 if (BI.getSuccessor(0) != NextBB) {
1059 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1060 if (BI.getSuccessor(1) != NextBB)
1061 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1063 // Change to the inverse condition...
1064 if (BI.getSuccessor(1) != NextBB) {
1066 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1072 /// doCall - This emits an abstract call instruction, setting up the arguments
1073 /// and the return value as appropriate. For the actual function call itself,
1074 /// it inserts the specified CallMI instruction into the stream.
1076 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1077 const std::vector<ValueRecord> &Args) {
1079 // Count how many bytes are to be pushed on the stack...
1080 unsigned NumBytes = 0;
1082 if (!Args.empty()) {
1083 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1084 switch (getClassB(Args[i].Ty)) {
1085 case cByte: case cShort: case cInt:
1086 NumBytes += 4; break;
1088 NumBytes += 8; break;
1090 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1092 default: assert(0 && "Unknown class!");
1095 // Adjust the stack pointer for the new arguments...
1096 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1098 // Arguments go on the stack in reverse order, as specified by the ABI.
1099 unsigned ArgOffset = 0;
1100 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1101 unsigned ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1102 switch (getClassB(Args[i].Ty)) {
1105 // Promote arg to 32 bits wide into a temporary register...
1106 unsigned R = makeAnotherReg(Type::UIntTy);
1107 promote32(R, Args[i]);
1108 addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1109 X86::ESP, ArgOffset).addReg(R);
1113 addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1114 X86::ESP, ArgOffset).addReg(ArgReg);
1117 addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1118 X86::ESP, ArgOffset).addReg(ArgReg);
1119 addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1120 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1121 ArgOffset += 4; // 8 byte entry, not 4.
1125 if (Args[i].Ty == Type::FloatTy) {
1126 addRegOffset(BuildMI(BB, X86::FSTm32, 5),
1127 X86::ESP, ArgOffset).addReg(ArgReg);
1129 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1130 addRegOffset(BuildMI(BB, X86::FSTm64, 5),
1131 X86::ESP, ArgOffset).addReg(ArgReg);
1132 ArgOffset += 4; // 8 byte entry, not 4.
1136 default: assert(0 && "Unknown class!");
1141 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1144 BB->push_back(CallMI);
1146 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1148 // If there is a return value, scavenge the result from the location the call
1151 if (Ret.Ty != Type::VoidTy) {
1152 unsigned DestClass = getClassB(Ret.Ty);
1153 switch (DestClass) {
1157 // Integral results are in %eax, or the appropriate portion
1159 static const unsigned regRegMove[] = {
1160 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
1162 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1163 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1166 case cFP: // Floating-point return values live in %ST(0)
1167 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1169 case cLong: // Long values are left in EDX:EAX
1170 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
1171 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
1173 default: assert(0 && "Unknown class!");
1179 /// visitCallInst - Push args on stack and do a procedure call instruction.
1180 void ISel::visitCallInst(CallInst &CI) {
1181 MachineInstr *TheCall;
1182 if (Function *F = CI.getCalledFunction()) {
1183 // Is it an intrinsic function call?
1184 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1185 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1189 // Emit a CALL instruction with PC-relative displacement.
1190 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1191 } else { // Emit an indirect call...
1192 unsigned Reg = getReg(CI.getCalledValue());
1193 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
1196 std::vector<ValueRecord> Args;
1197 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1198 Args.push_back(ValueRecord(CI.getOperand(i)));
1200 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1201 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1205 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1206 /// function, lowering any calls to unknown intrinsic functions into the
1207 /// equivalent LLVM code.
1208 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1209 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1210 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1211 if (CallInst *CI = dyn_cast<CallInst>(I++))
1212 if (Function *F = CI->getCalledFunction())
1213 switch (F->getIntrinsicID()) {
1214 case Intrinsic::not_intrinsic:
1215 case Intrinsic::va_start:
1216 case Intrinsic::va_copy:
1217 case Intrinsic::va_end:
1218 case Intrinsic::returnaddress:
1219 case Intrinsic::frameaddress:
1220 case Intrinsic::memcpy:
1221 case Intrinsic::memset:
1222 // We directly implement these intrinsics
1225 // All other intrinsic calls we must lower.
1226 Instruction *Before = CI->getPrev();
1227 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1228 if (Before) { // Move iterator to instruction after call
1237 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1238 unsigned TmpReg1, TmpReg2;
1240 case Intrinsic::va_start:
1241 // Get the address of the first vararg value...
1242 TmpReg1 = getReg(CI);
1243 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
1246 case Intrinsic::va_copy:
1247 TmpReg1 = getReg(CI);
1248 TmpReg2 = getReg(CI.getOperand(1));
1249 BuildMI(BB, X86::MOVrr32, 1, TmpReg1).addReg(TmpReg2);
1251 case Intrinsic::va_end: return; // Noop on X86
1253 case Intrinsic::returnaddress:
1254 case Intrinsic::frameaddress:
1255 TmpReg1 = getReg(CI);
1256 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1257 if (ID == Intrinsic::returnaddress) {
1258 // Just load the return address
1259 addFrameReference(BuildMI(BB, X86::MOVrm32, 4, TmpReg1),
1260 ReturnAddressIndex);
1262 addFrameReference(BuildMI(BB, X86::LEAr32, 4, TmpReg1),
1263 ReturnAddressIndex, -4);
1266 // Values other than zero are not implemented yet.
1267 BuildMI(BB, X86::MOVri32, 1, TmpReg1).addImm(0);
1271 case Intrinsic::memcpy: {
1272 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1274 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1275 Align = AlignC->getRawValue();
1276 if (Align == 0) Align = 1;
1279 // Turn the byte code into # iterations
1282 switch (Align & 3) {
1283 case 2: // WORD aligned
1284 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1285 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1287 CountReg = makeAnotherReg(Type::IntTy);
1288 unsigned ByteReg = getReg(CI.getOperand(3));
1289 BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addImm(1);
1291 Opcode = X86::REP_MOVSW;
1293 case 0: // DWORD aligned
1294 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1295 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1297 CountReg = makeAnotherReg(Type::IntTy);
1298 unsigned ByteReg = getReg(CI.getOperand(3));
1299 BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addImm(2);
1301 Opcode = X86::REP_MOVSD;
1303 default: // BYTE aligned
1304 CountReg = getReg(CI.getOperand(3));
1305 Opcode = X86::REP_MOVSB;
1309 // No matter what the alignment is, we put the source in ESI, the
1310 // destination in EDI, and the count in ECX.
1311 TmpReg1 = getReg(CI.getOperand(1));
1312 TmpReg2 = getReg(CI.getOperand(2));
1313 BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1314 BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1315 BuildMI(BB, X86::MOVrr32, 1, X86::ESI).addReg(TmpReg2);
1316 BuildMI(BB, Opcode, 0);
1319 case Intrinsic::memset: {
1320 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1322 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1323 Align = AlignC->getRawValue();
1324 if (Align == 0) Align = 1;
1327 // Turn the byte code into # iterations
1330 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1331 unsigned Val = ValC->getRawValue() & 255;
1333 // If the value is a constant, then we can potentially use larger copies.
1334 switch (Align & 3) {
1335 case 2: // WORD aligned
1336 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1337 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1339 CountReg = makeAnotherReg(Type::IntTy);
1340 unsigned ByteReg = getReg(CI.getOperand(3));
1341 BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addImm(1);
1343 BuildMI(BB, X86::MOVri16, 1, X86::AX).addImm((Val << 8) | Val);
1344 Opcode = X86::REP_STOSW;
1346 case 0: // DWORD aligned
1347 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1348 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1350 CountReg = makeAnotherReg(Type::IntTy);
1351 unsigned ByteReg = getReg(CI.getOperand(3));
1352 BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addImm(2);
1354 Val = (Val << 8) | Val;
1355 BuildMI(BB, X86::MOVri32, 1, X86::EAX).addImm((Val << 16) | Val);
1356 Opcode = X86::REP_STOSD;
1358 default: // BYTE aligned
1359 CountReg = getReg(CI.getOperand(3));
1360 BuildMI(BB, X86::MOVri8, 1, X86::AL).addImm(Val);
1361 Opcode = X86::REP_STOSB;
1365 // If it's not a constant value we are storing, just fall back. We could
1366 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1367 unsigned ValReg = getReg(CI.getOperand(2));
1368 BuildMI(BB, X86::MOVrr8, 1, X86::AL).addReg(ValReg);
1369 CountReg = getReg(CI.getOperand(3));
1370 Opcode = X86::REP_STOSB;
1373 // No matter what the alignment is, we put the source in ESI, the
1374 // destination in EDI, and the count in ECX.
1375 TmpReg1 = getReg(CI.getOperand(1));
1376 //TmpReg2 = getReg(CI.getOperand(2));
1377 BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1378 BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1379 BuildMI(BB, Opcode, 0);
1383 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1388 /// visitSimpleBinary - Implement simple binary operators for integral types...
1389 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1391 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1392 unsigned DestReg = getReg(B);
1393 MachineBasicBlock::iterator MI = BB->end();
1394 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
1395 OperatorClass, DestReg);
1398 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1399 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1402 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1403 /// and constant expression support.
1405 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1406 MachineBasicBlock::iterator IP,
1407 Value *Op0, Value *Op1,
1408 unsigned OperatorClass, unsigned DestReg) {
1409 unsigned Class = getClassB(Op0->getType());
1411 // sub 0, X -> neg X
1412 if (OperatorClass == 1 && Class != cLong)
1413 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1414 if (CI->isNullValue()) {
1415 unsigned op1Reg = getReg(Op1, MBB, IP);
1417 default: assert(0 && "Unknown class for this function!");
1419 BuildMI(*MBB, IP, X86::NEGr8, 1, DestReg).addReg(op1Reg);
1422 BuildMI(*MBB, IP, X86::NEGr16, 1, DestReg).addReg(op1Reg);
1425 BuildMI(*MBB, IP, X86::NEGr32, 1, DestReg).addReg(op1Reg);
1429 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1430 if (CFP->isExactlyValue(-0.0)) {
1432 unsigned op1Reg = getReg(Op1, MBB, IP);
1433 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1437 if (!isa<ConstantInt>(Op1) || Class == cLong) {
1438 static const unsigned OpcodeTab[][4] = {
1439 // Arithmetic operators
1440 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
1441 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
1443 // Bitwise operators
1444 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
1445 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
1446 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
1449 bool isLong = false;
1450 if (Class == cLong) {
1452 Class = cInt; // Bottom 32 bits are handled just like ints
1455 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1456 assert(Opcode && "Floating point arguments to logical inst?");
1457 unsigned Op0r = getReg(Op0, MBB, IP);
1458 unsigned Op1r = getReg(Op1, MBB, IP);
1459 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1461 if (isLong) { // Handle the upper 32 bits of long values...
1462 static const unsigned TopTab[] = {
1463 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1465 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1466 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1471 // Special case: op Reg, <const>
1472 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1473 unsigned Op0r = getReg(Op0, MBB, IP);
1475 // xor X, -1 -> not X
1476 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1477 static unsigned const NOTTab[] = { X86::NOTr8, X86::NOTr16, X86::NOTr32 };
1478 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1482 // add X, -1 -> dec X
1483 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1484 static unsigned const DECTab[] = { X86::DECr8, X86::DECr16, X86::DECr32 };
1485 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1489 // add X, 1 -> inc X
1490 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1491 static unsigned const DECTab[] = { X86::INCr8, X86::INCr16, X86::INCr32 };
1492 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1496 static const unsigned OpcodeTab[][3] = {
1497 // Arithmetic operators
1498 { X86::ADDri8, X86::ADDri16, X86::ADDri32 }, // ADD
1499 { X86::SUBri8, X86::SUBri16, X86::SUBri32 }, // SUB
1501 // Bitwise operators
1502 { X86::ANDri8, X86::ANDri16, X86::ANDri32 }, // AND
1503 { X86:: ORri8, X86:: ORri16, X86:: ORri32 }, // OR
1504 { X86::XORri8, X86::XORri16, X86::XORri32 }, // XOR
1507 assert(Class < 3 && "General code handles 64-bit integer types!");
1508 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1509 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1511 // Mask off any upper bits of the constant, if there are any...
1512 Op1v &= (1ULL << (8 << Class)) - 1;
1513 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1v);
1516 /// doMultiply - Emit appropriate instructions to multiply together the
1517 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1518 /// result should be given as DestTy.
1520 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1521 unsigned DestReg, const Type *DestTy,
1522 unsigned op0Reg, unsigned op1Reg) {
1523 unsigned Class = getClass(DestTy);
1525 case cFP: // Floating point multiply
1526 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1530 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMULrr32:X86::IMULrr16, 2, DestReg)
1531 .addReg(op0Reg).addReg(op1Reg);
1534 // Must use the MUL instruction, which forces use of AL...
1535 BuildMI(*MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1536 BuildMI(*MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1537 BuildMI(*MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1540 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1544 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1545 // returns zero when the input is not exactly a power of two.
1546 static unsigned ExactLog2(unsigned Val) {
1547 if (Val == 0) return 0;
1550 if (Val & 1) return 0;
1557 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1558 MachineBasicBlock::iterator IP,
1559 unsigned DestReg, const Type *DestTy,
1560 unsigned op0Reg, unsigned ConstRHS) {
1561 unsigned Class = getClass(DestTy);
1563 // If the element size is exactly a power of 2, use a shift to get it.
1564 if (unsigned Shift = ExactLog2(ConstRHS)) {
1566 default: assert(0 && "Unknown class for this function!");
1568 BuildMI(*MBB, IP, X86::SHLri32,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1571 BuildMI(*MBB, IP, X86::SHLri32,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1574 BuildMI(*MBB, IP, X86::SHLri32,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1579 if (Class == cShort) {
1580 BuildMI(*MBB, IP, X86::IMULrri16,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1582 } else if (Class == cInt) {
1583 BuildMI(*MBB, IP, X86::IMULrri32,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1587 // Most general case, emit a normal multiply...
1588 static const unsigned MOVriTab[] = {
1589 X86::MOVri8, X86::MOVri16, X86::MOVri32
1592 unsigned TmpReg = makeAnotherReg(DestTy);
1593 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1595 // Emit a MUL to multiply the register holding the index by
1596 // elementSize, putting the result in OffsetReg.
1597 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1600 /// visitMul - Multiplies are not simple binary operators because they must deal
1601 /// with the EAX register explicitly.
1603 void ISel::visitMul(BinaryOperator &I) {
1604 unsigned Op0Reg = getReg(I.getOperand(0));
1605 unsigned DestReg = getReg(I);
1607 // Simple scalar multiply?
1608 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1609 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1610 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1611 MachineBasicBlock::iterator MBBI = BB->end();
1612 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1614 unsigned Op1Reg = getReg(I.getOperand(1));
1615 MachineBasicBlock::iterator MBBI = BB->end();
1616 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1619 unsigned Op1Reg = getReg(I.getOperand(1));
1621 // Long value. We have to do things the hard way...
1622 // Multiply the two low parts... capturing carry into EDX
1623 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1624 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1626 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1627 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1628 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1630 MachineBasicBlock::iterator MBBI = BB->end();
1631 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1632 BuildMI(*BB, MBBI, X86::IMULrr32,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1634 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1635 BuildMI(*BB, MBBI, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1636 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1639 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1640 BuildMI(*BB, MBBI, X86::IMULrr32,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1642 BuildMI(*BB, MBBI, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1643 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1648 /// visitDivRem - Handle division and remainder instructions... these
1649 /// instruction both require the same instructions to be generated, they just
1650 /// select the result from a different register. Note that both of these
1651 /// instructions work differently for signed and unsigned operands.
1653 void ISel::visitDivRem(BinaryOperator &I) {
1654 unsigned Op0Reg = getReg(I.getOperand(0));
1655 unsigned Op1Reg = getReg(I.getOperand(1));
1656 unsigned ResultReg = getReg(I);
1658 MachineBasicBlock::iterator IP = BB->end();
1659 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1660 I.getType(), ResultReg);
1663 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1664 MachineBasicBlock::iterator IP,
1665 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1666 const Type *Ty, unsigned ResultReg) {
1667 unsigned Class = getClass(Ty);
1669 case cFP: // Floating point divide
1671 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1672 } else { // Floating point remainder...
1673 MachineInstr *TheCall =
1674 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1675 std::vector<ValueRecord> Args;
1676 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1677 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1678 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1682 static const char *FnName[] =
1683 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1685 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1686 MachineInstr *TheCall =
1687 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1689 std::vector<ValueRecord> Args;
1690 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1691 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1692 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1695 case cByte: case cShort: case cInt:
1696 break; // Small integrals, handled below...
1697 default: assert(0 && "Unknown class!");
1700 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1701 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1702 static const unsigned SarOpcode[]={ X86::SARri8, X86::SARri16, X86::SARri32 };
1703 static const unsigned ClrOpcode[]={ X86::MOVri8, X86::MOVri16, X86::MOVri32 };
1704 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1706 static const unsigned DivOpcode[][4] = {
1707 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1708 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1711 bool isSigned = Ty->isSigned();
1712 unsigned Reg = Regs[Class];
1713 unsigned ExtReg = ExtRegs[Class];
1715 // Put the first operand into one of the A registers...
1716 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1719 // Emit a sign extension instruction...
1720 unsigned ShiftResult = makeAnotherReg(Ty);
1721 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1722 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1724 // If unsigned, emit a zeroing instruction... (reg = 0)
1725 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
1728 // Emit the appropriate divide or remainder instruction...
1729 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1731 // Figure out which register we want to pick the result out of...
1732 unsigned DestReg = isDiv ? Reg : ExtReg;
1734 // Put the result into the destination register...
1735 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1739 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1740 /// for constant immediate shift values, and for constant immediate
1741 /// shift values equal to 1. Even the general case is sort of special,
1742 /// because the shift amount has to be in CL, not just any old register.
1744 void ISel::visitShiftInst(ShiftInst &I) {
1745 MachineBasicBlock::iterator IP = BB->end ();
1746 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1747 I.getOpcode () == Instruction::Shl, I.getType (),
1751 /// emitShiftOperation - Common code shared between visitShiftInst and
1752 /// constant expression support.
1753 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1754 MachineBasicBlock::iterator IP,
1755 Value *Op, Value *ShiftAmount, bool isLeftShift,
1756 const Type *ResultTy, unsigned DestReg) {
1757 unsigned SrcReg = getReg (Op, MBB, IP);
1758 bool isSigned = ResultTy->isSigned ();
1759 unsigned Class = getClass (ResultTy);
1761 static const unsigned ConstantOperand[][4] = {
1762 { X86::SHRri8, X86::SHRri16, X86::SHRri32, X86::SHRDrr32i8 }, // SHR
1763 { X86::SARri8, X86::SARri16, X86::SARri32, X86::SHRDrr32i8 }, // SAR
1764 { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDrr32i8 }, // SHL
1765 { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDrr32i8 }, // SAL = SHL
1768 static const unsigned NonConstantOperand[][4] = {
1769 { X86::SHRrCL8, X86::SHRrCL16, X86::SHRrCL32 }, // SHR
1770 { X86::SARrCL8, X86::SARrCL16, X86::SARrCL32 }, // SAR
1771 { X86::SHLrCL8, X86::SHLrCL16, X86::SHLrCL32 }, // SHL
1772 { X86::SHLrCL8, X86::SHLrCL16, X86::SHLrCL32 }, // SAL = SHL
1775 // Longs, as usual, are handled specially...
1776 if (Class == cLong) {
1777 // If we have a constant shift, we can generate much more efficient code
1778 // than otherwise...
1780 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1781 unsigned Amount = CUI->getValue();
1783 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1785 BuildMI(*MBB, IP, Opc[3], 3,
1786 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1787 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
1789 BuildMI(*MBB, IP, Opc[3], 3,
1790 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
1791 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
1793 } else { // Shifting more than 32 bits
1796 BuildMI(*MBB, IP, X86::SHLri32, 2,
1797 DestReg + 1).addReg(SrcReg).addImm(Amount);
1798 BuildMI(*MBB, IP, X86::MOVri32, 1,
1801 unsigned Opcode = isSigned ? X86::SARri32 : X86::SHRri32;
1802 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
1803 BuildMI(*MBB, IP, X86::MOVri32, 1, DestReg+1).addImm(0);
1807 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1809 if (!isLeftShift && isSigned) {
1810 // If this is a SHR of a Long, then we need to do funny sign extension
1811 // stuff. TmpReg gets the value to use as the high-part if we are
1812 // shifting more than 32 bits.
1813 BuildMI(*MBB, IP, X86::SARri32, 2, TmpReg).addReg(SrcReg).addImm(31);
1815 // Other shifts use a fixed zero value if the shift is more than 32
1817 BuildMI(*MBB, IP, X86::MOVri32, 1, TmpReg).addImm(0);
1820 // Initialize CL with the shift amount...
1821 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
1822 BuildMI(*MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1824 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1825 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1827 // TmpReg2 = shld inHi, inLo
1828 BuildMI(*MBB, IP, X86::SHLDrrCL32,2,TmpReg2).addReg(SrcReg+1)
1830 // TmpReg3 = shl inLo, CL
1831 BuildMI(*MBB, IP, X86::SHLrCL32, 1, TmpReg3).addReg(SrcReg);
1833 // Set the flags to indicate whether the shift was by more than 32 bits.
1834 BuildMI(*MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addImm(32);
1836 // DestHi = (>32) ? TmpReg3 : TmpReg2;
1837 BuildMI(*MBB, IP, X86::CMOVNErr32, 2,
1838 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1839 // DestLo = (>32) ? TmpReg : TmpReg3;
1840 BuildMI(*MBB, IP, X86::CMOVNErr32, 2,
1841 DestReg).addReg(TmpReg3).addReg(TmpReg);
1843 // TmpReg2 = shrd inLo, inHi
1844 BuildMI(*MBB, IP, X86::SHRDrrCL32,2,TmpReg2).addReg(SrcReg)
1846 // TmpReg3 = s[ah]r inHi, CL
1847 BuildMI(*MBB, IP, isSigned ? X86::SARrCL32 : X86::SHRrCL32, 1, TmpReg3)
1850 // Set the flags to indicate whether the shift was by more than 32 bits.
1851 BuildMI(*MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addImm(32);
1853 // DestLo = (>32) ? TmpReg3 : TmpReg2;
1854 BuildMI(*MBB, IP, X86::CMOVNErr32, 2,
1855 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1857 // DestHi = (>32) ? TmpReg : TmpReg3;
1858 BuildMI(*MBB, IP, X86::CMOVNErr32, 2,
1859 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1865 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1866 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1867 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1869 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1870 BuildMI(*MBB, IP, Opc[Class], 2,
1871 DestReg).addReg(SrcReg).addImm(CUI->getValue());
1872 } else { // The shift amount is non-constant.
1873 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
1874 BuildMI(*MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1876 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1877 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
1882 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1883 /// instruction. The load and store instructions are the only place where we
1884 /// need to worry about the memory layout of the target machine.
1886 void ISel::visitLoadInst(LoadInst &I) {
1887 unsigned DestReg = getReg(I);
1888 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1889 Value *Addr = I.getOperand(0);
1890 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1891 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1892 BaseReg, Scale, IndexReg, Disp))
1893 Addr = 0; // Address is consumed!
1894 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1895 if (CE->getOpcode() == Instruction::GetElementPtr)
1896 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1897 BaseReg, Scale, IndexReg, Disp))
1902 // If it's not foldable, reset addr mode.
1903 BaseReg = getReg(Addr);
1904 Scale = 1; IndexReg = 0; Disp = 0;
1907 unsigned Class = getClassB(I.getType());
1908 if (Class == cLong) {
1909 addFullAddress(BuildMI(BB, X86::MOVrm32, 4, DestReg),
1910 BaseReg, Scale, IndexReg, Disp);
1911 addFullAddress(BuildMI(BB, X86::MOVrm32, 4, DestReg+1),
1912 BaseReg, Scale, IndexReg, Disp+4);
1916 static const unsigned Opcodes[] = {
1917 X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FLDm32
1919 unsigned Opcode = Opcodes[Class];
1920 if (I.getType() == Type::DoubleTy) Opcode = X86::FLDm64;
1921 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
1922 BaseReg, Scale, IndexReg, Disp);
1925 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1928 void ISel::visitStoreInst(StoreInst &I) {
1929 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1930 Value *Addr = I.getOperand(1);
1931 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1932 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1933 BaseReg, Scale, IndexReg, Disp))
1934 Addr = 0; // Address is consumed!
1935 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1936 if (CE->getOpcode() == Instruction::GetElementPtr)
1937 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1938 BaseReg, Scale, IndexReg, Disp))
1943 // If it's not foldable, reset addr mode.
1944 BaseReg = getReg(Addr);
1945 Scale = 1; IndexReg = 0; Disp = 0;
1948 const Type *ValTy = I.getOperand(0)->getType();
1949 unsigned Class = getClassB(ValTy);
1951 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
1952 uint64_t Val = CI->getRawValue();
1953 if (Class == cLong) {
1954 addFullAddress(BuildMI(BB, X86::MOVmi32, 5),
1955 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
1956 addFullAddress(BuildMI(BB, X86::MOVmi32, 5),
1957 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
1959 static const unsigned Opcodes[] = {
1960 X86::MOVmi8, X86::MOVmi16, X86::MOVmi32
1962 unsigned Opcode = Opcodes[Class];
1963 addFullAddress(BuildMI(BB, Opcode, 5),
1964 BaseReg, Scale, IndexReg, Disp).addImm(Val);
1966 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
1967 addFullAddress(BuildMI(BB, X86::MOVmi8, 5),
1968 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
1970 if (Class == cLong) {
1971 unsigned ValReg = getReg(I.getOperand(0));
1972 addFullAddress(BuildMI(BB, X86::MOVmr32, 5),
1973 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
1974 addFullAddress(BuildMI(BB, X86::MOVmr32, 5),
1975 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
1977 unsigned ValReg = getReg(I.getOperand(0));
1978 static const unsigned Opcodes[] = {
1979 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FSTm32
1981 unsigned Opcode = Opcodes[Class];
1982 if (ValTy == Type::DoubleTy) Opcode = X86::FSTm64;
1983 addFullAddress(BuildMI(BB, Opcode, 1+4),
1984 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
1990 /// visitCastInst - Here we have various kinds of copying with or without
1991 /// sign extension going on.
1992 void ISel::visitCastInst(CastInst &CI) {
1993 Value *Op = CI.getOperand(0);
1994 // If this is a cast from a 32-bit integer to a Long type, and the only uses
1995 // of the case are GEP instructions, then the cast does not need to be
1996 // generated explicitly, it will be folded into the GEP.
1997 if (CI.getType() == Type::LongTy &&
1998 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
1999 bool AllUsesAreGEPs = true;
2000 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2001 if (!isa<GetElementPtrInst>(*I)) {
2002 AllUsesAreGEPs = false;
2006 // No need to codegen this cast if all users are getelementptr instrs...
2007 if (AllUsesAreGEPs) return;
2010 unsigned DestReg = getReg(CI);
2011 MachineBasicBlock::iterator MI = BB->end();
2012 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2015 /// emitCastOperation - Common code shared between visitCastInst and
2016 /// constant expression cast support.
2017 void ISel::emitCastOperation(MachineBasicBlock *BB,
2018 MachineBasicBlock::iterator IP,
2019 Value *Src, const Type *DestTy,
2021 unsigned SrcReg = getReg(Src, BB, IP);
2022 const Type *SrcTy = Src->getType();
2023 unsigned SrcClass = getClassB(SrcTy);
2024 unsigned DestClass = getClassB(DestTy);
2026 // Implement casts to bool by using compare on the operand followed by set if
2027 // not zero on the result.
2028 if (DestTy == Type::BoolTy) {
2031 BuildMI(*BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
2034 BuildMI(*BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
2037 BuildMI(*BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
2040 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2041 BuildMI(*BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2045 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2046 BuildMI(*BB, IP, X86::FNSTSWr8, 0);
2047 BuildMI(*BB, IP, X86::SAHF, 1);
2051 // If the zero flag is not set, then the value is true, set the byte to
2053 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2057 static const unsigned RegRegMove[] = {
2058 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
2061 // Implement casts between values of the same type class (as determined by
2062 // getClass) by using a register-to-register move.
2063 if (SrcClass == DestClass) {
2064 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2065 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2066 } else if (SrcClass == cFP) {
2067 if (SrcTy == Type::FloatTy) { // double -> float
2068 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2069 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2070 } else { // float -> double
2071 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2072 "Unknown cFP member!");
2073 // Truncate from double to float by storing to memory as short, then
2075 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2076 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2077 addFrameReference(BuildMI(*BB, IP, X86::FSTm32, 5), FrameIdx).addReg(SrcReg);
2078 addFrameReference(BuildMI(*BB, IP, X86::FLDm32, 5, DestReg), FrameIdx);
2080 } else if (SrcClass == cLong) {
2081 BuildMI(*BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2082 BuildMI(*BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
2084 assert(0 && "Cannot handle this type of cast instruction!");
2090 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2091 // or zero extension, depending on whether the source type was signed.
2092 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2093 SrcClass < DestClass) {
2094 bool isLong = DestClass == cLong;
2095 if (isLong) DestClass = cInt;
2097 static const unsigned Opc[][4] = {
2098 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
2099 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
2102 bool isUnsigned = SrcTy->isUnsigned();
2103 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2104 DestReg).addReg(SrcReg);
2106 if (isLong) { // Handle upper 32 bits as appropriate...
2107 if (isUnsigned) // Zero out top bits...
2108 BuildMI(*BB, IP, X86::MOVri32, 1, DestReg+1).addImm(0);
2109 else // Sign extend bottom half...
2110 BuildMI(*BB, IP, X86::SARri32, 2, DestReg+1).addReg(DestReg).addImm(31);
2115 // Special case long -> int ...
2116 if (SrcClass == cLong && DestClass == cInt) {
2117 BuildMI(*BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2121 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2122 // move out of AX or AL.
2123 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2124 && SrcClass > DestClass) {
2125 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2126 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2127 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2131 // Handle casts from integer to floating point now...
2132 if (DestClass == cFP) {
2133 // Promote the integer to a type supported by FLD. We do this because there
2134 // are no unsigned FLD instructions, so we must promote an unsigned value to
2135 // a larger signed value, then use FLD on the larger value.
2137 const Type *PromoteType = 0;
2138 unsigned PromoteOpcode;
2139 unsigned RealDestReg = DestReg;
2140 switch (SrcTy->getPrimitiveID()) {
2141 case Type::BoolTyID:
2142 case Type::SByteTyID:
2143 // We don't have the facilities for directly loading byte sized data from
2144 // memory (even signed). Promote it to 16 bits.
2145 PromoteType = Type::ShortTy;
2146 PromoteOpcode = X86::MOVSXr16r8;
2148 case Type::UByteTyID:
2149 PromoteType = Type::ShortTy;
2150 PromoteOpcode = X86::MOVZXr16r8;
2152 case Type::UShortTyID:
2153 PromoteType = Type::IntTy;
2154 PromoteOpcode = X86::MOVZXr32r16;
2156 case Type::UIntTyID: {
2157 // Make a 64 bit temporary... and zero out the top of it...
2158 unsigned TmpReg = makeAnotherReg(Type::LongTy);
2159 BuildMI(*BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
2160 BuildMI(*BB, IP, X86::MOVri32, 1, TmpReg+1).addImm(0);
2161 SrcTy = Type::LongTy;
2166 case Type::ULongTyID:
2167 // Don't fild into the read destination.
2168 DestReg = makeAnotherReg(Type::DoubleTy);
2170 default: // No promotion needed...
2175 unsigned TmpReg = makeAnotherReg(PromoteType);
2176 unsigned Opc = SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8;
2177 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2178 SrcTy = PromoteType;
2179 SrcClass = getClass(PromoteType);
2183 // Spill the integer to memory and reload it from there...
2185 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2187 if (SrcClass == cLong) {
2188 addFrameReference(BuildMI(*BB, IP, X86::MOVmr32, 5),
2189 FrameIdx).addReg(SrcReg);
2190 addFrameReference(BuildMI(*BB, IP, X86::MOVmr32, 5),
2191 FrameIdx, 4).addReg(SrcReg+1);
2193 static const unsigned Op1[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
2194 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2195 FrameIdx).addReg(SrcReg);
2198 static const unsigned Op2[] =
2199 { 0/*byte*/, X86::FILDm16, X86::FILDm32, 0/*FP*/, X86::FILDm64 };
2200 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2202 // We need special handling for unsigned 64-bit integer sources. If the
2203 // input number has the "sign bit" set, then we loaded it incorrectly as a
2204 // negative 64-bit number. In this case, add an offset value.
2205 if (SrcTy == Type::ULongTy) {
2206 // Emit a test instruction to see if the dynamic input value was signed.
2207 BuildMI(*BB, IP, X86::TESTrr32, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2209 // If the sign bit is set, get a pointer to an offset, otherwise get a
2210 // pointer to a zero.
2211 MachineConstantPool *CP = F->getConstantPool();
2212 unsigned Zero = makeAnotherReg(Type::IntTy);
2213 Constant *Null = Constant::getNullValue(Type::UIntTy);
2214 addConstantPoolReference(BuildMI(*BB, IP, X86::LEAr32, 5, Zero),
2215 CP->getConstantPoolIndex(Null));
2216 unsigned Offset = makeAnotherReg(Type::IntTy);
2217 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2219 addConstantPoolReference(BuildMI(*BB, IP, X86::LEAr32, 5, Offset),
2220 CP->getConstantPoolIndex(OffsetCst));
2221 unsigned Addr = makeAnotherReg(Type::IntTy);
2222 BuildMI(*BB, IP, X86::CMOVSrr32, 2, Addr).addReg(Zero).addReg(Offset);
2224 // Load the constant for an add. FIXME: this could make an 'fadd' that
2225 // reads directly from memory, but we don't support these yet.
2226 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2227 addDirectMem(BuildMI(*BB, IP, X86::FLDm32, 4, ConstReg), Addr);
2229 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2230 .addReg(ConstReg).addReg(DestReg);
2236 // Handle casts from floating point to integer now...
2237 if (SrcClass == cFP) {
2238 // Change the floating point control register to use "round towards zero"
2239 // mode when truncating to an integer value.
2241 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2242 addFrameReference(BuildMI(*BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
2244 // Load the old value of the high byte of the control word...
2245 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2246 addFrameReference(BuildMI(*BB, IP, X86::MOVrm8, 4, HighPartOfCW),
2249 // Set the high part to be round to zero...
2250 addFrameReference(BuildMI(*BB, IP, X86::MOVmi8, 5),
2251 CWFrameIdx, 1).addImm(12);
2253 // Reload the modified control word now...
2254 addFrameReference(BuildMI(*BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2256 // Restore the memory image of control word to original value
2257 addFrameReference(BuildMI(*BB, IP, X86::MOVmr8, 5),
2258 CWFrameIdx, 1).addReg(HighPartOfCW);
2260 // We don't have the facilities for directly storing byte sized data to
2261 // memory. Promote it to 16 bits. We also must promote unsigned values to
2262 // larger classes because we only have signed FP stores.
2263 unsigned StoreClass = DestClass;
2264 const Type *StoreTy = DestTy;
2265 if (StoreClass == cByte || DestTy->isUnsigned())
2266 switch (StoreClass) {
2267 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2268 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2269 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
2270 // The following treatment of cLong may not be perfectly right,
2271 // but it survives chains of casts of the form
2272 // double->ulong->double.
2273 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
2274 default: assert(0 && "Unknown store class!");
2277 // Spill the integer to memory and reload it from there...
2279 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2281 static const unsigned Op1[] =
2282 { 0, X86::FISTm16, X86::FISTm32, 0, X86::FISTPm64 };
2283 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2284 FrameIdx).addReg(SrcReg);
2286 if (DestClass == cLong) {
2287 addFrameReference(BuildMI(*BB, IP, X86::MOVrm32, 4, DestReg), FrameIdx);
2288 addFrameReference(BuildMI(*BB, IP, X86::MOVrm32, 4, DestReg+1),
2291 static const unsigned Op2[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
2292 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2295 // Reload the original control word now...
2296 addFrameReference(BuildMI(*BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2300 // Anything we haven't handled already, we can't (yet) handle at all.
2301 assert(0 && "Unhandled cast instruction!");
2305 /// visitVANextInst - Implement the va_next instruction...
2307 void ISel::visitVANextInst(VANextInst &I) {
2308 unsigned VAList = getReg(I.getOperand(0));
2309 unsigned DestReg = getReg(I);
2312 switch (I.getArgType()->getPrimitiveID()) {
2315 assert(0 && "Error: bad type for va_next instruction!");
2317 case Type::PointerTyID:
2318 case Type::UIntTyID:
2322 case Type::ULongTyID:
2323 case Type::LongTyID:
2324 case Type::DoubleTyID:
2329 // Increment the VAList pointer...
2330 BuildMI(BB, X86::ADDri32, 2, DestReg).addReg(VAList).addImm(Size);
2333 void ISel::visitVAArgInst(VAArgInst &I) {
2334 unsigned VAList = getReg(I.getOperand(0));
2335 unsigned DestReg = getReg(I);
2337 switch (I.getType()->getPrimitiveID()) {
2340 assert(0 && "Error: bad type for va_next instruction!");
2342 case Type::PointerTyID:
2343 case Type::UIntTyID:
2345 addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2347 case Type::ULongTyID:
2348 case Type::LongTyID:
2349 addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2350 addRegOffset(BuildMI(BB, X86::MOVrm32, 4, DestReg+1), VAList, 4);
2352 case Type::DoubleTyID:
2353 addDirectMem(BuildMI(BB, X86::FLDm64, 4, DestReg), VAList);
2359 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2360 // If this GEP instruction will be folded into all of its users, we don't need
2361 // to explicitly calculate it!
2362 unsigned A, B, C, D;
2363 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2364 // Check all of the users of the instruction to see if they are loads and
2366 bool AllWillFold = true;
2367 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2368 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2369 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2370 cast<Instruction>(*UI)->getOperand(0) == &I) {
2371 AllWillFold = false;
2375 // If the instruction is foldable, and will be folded into all users, don't
2377 if (AllWillFold) return;
2380 unsigned outputReg = getReg(I);
2381 emitGEPOperation(BB, BB->end(), I.getOperand(0),
2382 I.op_begin()+1, I.op_end(), outputReg);
2385 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2386 /// GEPTypes (the derived types being stepped through at each level). On return
2387 /// from this function, if some indexes of the instruction are representable as
2388 /// an X86 lea instruction, the machine operands are put into the Ops
2389 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2390 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2391 /// addressing mode that only partially consumes the input, the BaseReg input of
2392 /// the addressing mode must be left free.
2394 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2396 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2397 std::vector<Value*> &GEPOps,
2398 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2399 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2400 const TargetData &TD = TM.getTargetData();
2402 // Clear out the state we are working with...
2403 BaseReg = 0; // No base register
2404 Scale = 1; // Unit scale
2405 IndexReg = 0; // No index register
2406 Disp = 0; // No displacement
2408 // While there are GEP indexes that can be folded into the current address,
2409 // keep processing them.
2410 while (!GEPTypes.empty()) {
2411 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2412 // It's a struct access. CUI is the index into the structure,
2413 // which names the field. This index must have unsigned type.
2414 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2416 // Use the TargetData structure to pick out what the layout of the
2417 // structure is in memory. Since the structure index must be constant, we
2418 // can get its value and use it to find the right byte offset from the
2419 // StructLayout class's list of structure member offsets.
2420 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2421 GEPOps.pop_back(); // Consume a GEP operand
2422 GEPTypes.pop_back();
2424 // It's an array or pointer access: [ArraySize x ElementType].
2425 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2426 Value *idx = GEPOps.back();
2428 // idx is the index into the array. Unlike with structure
2429 // indices, we may not know its actual value at code-generation
2431 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2433 // If idx is a constant, fold it into the offset.
2434 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2435 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2436 Disp += TypeSize*CSI->getValue();
2438 // If the index reg is already taken, we can't handle this index.
2439 if (IndexReg) return;
2441 // If this is a size that we can handle, then add the index as
2443 case 1: case 2: case 4: case 8:
2444 // These are all acceptable scales on X86.
2448 // Otherwise, we can't handle this scale
2452 if (CastInst *CI = dyn_cast<CastInst>(idx))
2453 if (CI->getOperand(0)->getType() == Type::IntTy ||
2454 CI->getOperand(0)->getType() == Type::UIntTy)
2455 idx = CI->getOperand(0);
2457 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2460 GEPOps.pop_back(); // Consume a GEP operand
2461 GEPTypes.pop_back();
2465 // GEPTypes is empty, which means we have a single operand left. See if we
2466 // can set it as the base register.
2468 // FIXME: When addressing modes are more powerful/correct, we could load
2469 // global addresses directly as 32-bit immediates.
2470 assert(BaseReg == 0);
2471 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2472 GEPOps.pop_back(); // Consume the last GEP operand
2476 /// isGEPFoldable - Return true if the specified GEP can be completely
2477 /// folded into the addressing mode of a load/store or lea instruction.
2478 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2479 Value *Src, User::op_iterator IdxBegin,
2480 User::op_iterator IdxEnd, unsigned &BaseReg,
2481 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2482 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2483 Src = CPR->getValue();
2485 std::vector<Value*> GEPOps;
2486 GEPOps.resize(IdxEnd-IdxBegin+1);
2488 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2490 std::vector<const Type*> GEPTypes;
2491 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2492 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2494 MachineBasicBlock::iterator IP;
2495 if (MBB) IP = MBB->end();
2496 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2498 // We can fold it away iff the getGEPIndex call eliminated all operands.
2499 return GEPOps.empty();
2502 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2503 MachineBasicBlock::iterator IP,
2504 Value *Src, User::op_iterator IdxBegin,
2505 User::op_iterator IdxEnd, unsigned TargetReg) {
2506 const TargetData &TD = TM.getTargetData();
2507 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2508 Src = CPR->getValue();
2510 std::vector<Value*> GEPOps;
2511 GEPOps.resize(IdxEnd-IdxBegin+1);
2513 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2515 std::vector<const Type*> GEPTypes;
2516 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2517 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2519 // Keep emitting instructions until we consume the entire GEP instruction.
2520 while (!GEPOps.empty()) {
2521 unsigned OldSize = GEPOps.size();
2522 unsigned BaseReg, Scale, IndexReg, Disp;
2523 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2525 if (GEPOps.size() != OldSize) {
2526 // getGEPIndex consumed some of the input. Build an LEA instruction here.
2527 unsigned NextTarget = 0;
2528 if (!GEPOps.empty()) {
2529 assert(BaseReg == 0 &&
2530 "getGEPIndex should have left the base register open for chaining!");
2531 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2534 if (IndexReg == 0 && Disp == 0)
2535 BuildMI(*MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2537 addFullAddress(BuildMI(*MBB, IP, X86::LEAr32, 5, TargetReg),
2538 BaseReg, Scale, IndexReg, Disp);
2540 TargetReg = NextTarget;
2541 } else if (GEPTypes.empty()) {
2542 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2543 // all operands are consumed but the base pointer. If so, just load it
2544 // into the register.
2545 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2546 BuildMI(*MBB, IP, X86::MOVri32, 1, TargetReg).addGlobalAddress(GV);
2548 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2549 BuildMI(*MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2551 break; // we are now done
2554 // It's an array or pointer access: [ArraySize x ElementType].
2555 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2556 Value *idx = GEPOps.back();
2557 GEPOps.pop_back(); // Consume a GEP operand
2558 GEPTypes.pop_back();
2560 // idx is the index into the array. Unlike with structure
2561 // indices, we may not know its actual value at code-generation
2563 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2565 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2566 // operand on X86. Handle this case directly now...
2567 if (CastInst *CI = dyn_cast<CastInst>(idx))
2568 if (CI->getOperand(0)->getType() == Type::IntTy ||
2569 CI->getOperand(0)->getType() == Type::UIntTy)
2570 idx = CI->getOperand(0);
2572 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2573 // must find the size of the pointed-to type (Not coincidentally, the next
2574 // type is the type of the elements in the array).
2575 const Type *ElTy = SqTy->getElementType();
2576 unsigned elementSize = TD.getTypeSize(ElTy);
2578 // If idxReg is a constant, we don't need to perform the multiply!
2579 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2580 if (!CSI->isNullValue()) {
2581 unsigned Offset = elementSize*CSI->getValue();
2582 unsigned Reg = makeAnotherReg(Type::UIntTy);
2583 BuildMI(*MBB, IP, X86::ADDri32, 2, TargetReg)
2584 .addReg(Reg).addImm(Offset);
2585 --IP; // Insert the next instruction before this one.
2586 TargetReg = Reg; // Codegen the rest of the GEP into this
2588 } else if (elementSize == 1) {
2589 // If the element size is 1, we don't have to multiply, just add
2590 unsigned idxReg = getReg(idx, MBB, IP);
2591 unsigned Reg = makeAnotherReg(Type::UIntTy);
2592 BuildMI(*MBB, IP, X86::ADDrr32, 2,TargetReg).addReg(Reg).addReg(idxReg);
2593 --IP; // Insert the next instruction before this one.
2594 TargetReg = Reg; // Codegen the rest of the GEP into this
2596 unsigned idxReg = getReg(idx, MBB, IP);
2597 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2599 // Make sure we can back the iterator up to point to the first
2600 // instruction emitted.
2601 MachineBasicBlock::iterator BeforeIt = IP;
2602 if (IP == MBB->begin())
2603 BeforeIt = MBB->end();
2606 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2608 // Emit an ADD to add OffsetReg to the basePtr.
2609 unsigned Reg = makeAnotherReg(Type::UIntTy);
2610 BuildMI(*MBB, IP, X86::ADDrr32, 2, TargetReg)
2611 .addReg(Reg).addReg(OffsetReg);
2613 // Step to the first instruction of the multiply.
2614 if (BeforeIt == MBB->end())
2619 TargetReg = Reg; // Codegen the rest of the GEP into this
2626 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2627 /// frame manager, otherwise do it the hard way.
2629 void ISel::visitAllocaInst(AllocaInst &I) {
2630 // Find the data size of the alloca inst's getAllocatedType.
2631 const Type *Ty = I.getAllocatedType();
2632 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2634 // If this is a fixed size alloca in the entry block for the function,
2635 // statically stack allocate the space.
2637 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2638 if (I.getParent() == I.getParent()->getParent()->begin()) {
2639 TySize *= CUI->getValue(); // Get total allocated size...
2640 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2642 // Create a new stack object using the frame manager...
2643 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2644 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2649 // Create a register to hold the temporary result of multiplying the type size
2650 // constant by the variable amount.
2651 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2652 unsigned SrcReg1 = getReg(I.getArraySize());
2654 // TotalSizeReg = mul <numelements>, <TypeSize>
2655 MachineBasicBlock::iterator MBBI = BB->end();
2656 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2658 // AddedSize = add <TotalSizeReg>, 15
2659 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2660 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2662 // AlignedSize = and <AddedSize>, ~15
2663 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2664 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2666 // Subtract size from stack pointer, thereby allocating some space.
2667 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2669 // Put a pointer to the space into the result register, by copying
2670 // the stack pointer.
2671 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2673 // Inform the Frame Information that we have just allocated a variable-sized
2675 F->getFrameInfo()->CreateVariableSizedObject();
2678 /// visitMallocInst - Malloc instructions are code generated into direct calls
2679 /// to the library malloc.
2681 void ISel::visitMallocInst(MallocInst &I) {
2682 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2685 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2686 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2688 Arg = makeAnotherReg(Type::UIntTy);
2689 unsigned Op0Reg = getReg(I.getOperand(0));
2690 MachineBasicBlock::iterator MBBI = BB->end();
2691 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2694 std::vector<ValueRecord> Args;
2695 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2696 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2697 1).addExternalSymbol("malloc", true);
2698 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2702 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2705 void ISel::visitFreeInst(FreeInst &I) {
2706 std::vector<ValueRecord> Args;
2707 Args.push_back(ValueRecord(I.getOperand(0)));
2708 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2709 1).addExternalSymbol("free", true);
2710 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2713 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2714 /// into a machine code representation is a very simple peep-hole fashion. The
2715 /// generated code sucks but the implementation is nice and simple.
2717 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2718 return new ISel(TM);